<?php

namespace GriffinForms\Includes\CommandPalette\Providers;

use GriffinForms\Config;
use GriffinForms\Includes\CommandPalette\SearchProviderInterface;
use GriffinForms\Includes\CommandPalette\SearchResultItem;

class RecentFormsProvider implements SearchProviderInterface
{
    private const LIMIT = 5;

    private Config $config;

    public function __construct()
    {
        $this->config = Config::getInstance();
    }

    public function getProviderId(): string
    {
        return 'recent_forms';
    }

    public function getLabel(): string
    {
        return 'Forms';
    }

    public function getPriority(): int
    {
        return 10;
    }

    public function getQuickItems(int $form_id): array
    {
        return $this->fetchForms('', $form_id);
    }

    public function query(string $query, int $form_id): array
    {
        return $this->fetchForms($query, $form_id);
    }

    private function fetchForms(string $query, int $form_id): array
    {
        global $wpdb;

        $table = $this->config->getTable('form');
        if (!$table) {
            return [];
        }

        if ($query !== '') {
            $like  = '%' . $wpdb->esc_like($query) . '%';
            $rows  = $form_id > 0
                ? $wpdb->get_results($wpdb->prepare(
                    "SELECT id, name FROM %i WHERE name LIKE %s AND id != %d ORDER BY last_edited DESC LIMIT %d",
                    $table, $like, $form_id, self::LIMIT
                ), ARRAY_A)
                : $wpdb->get_results($wpdb->prepare(
                    "SELECT id, name FROM %i WHERE name LIKE %s ORDER BY last_edited DESC LIMIT %d",
                    $table, $like, self::LIMIT
                ), ARRAY_A);
        } else {
            $rows = $form_id > 0
                ? $wpdb->get_results($wpdb->prepare(
                    "SELECT id, name FROM %i WHERE id != %d ORDER BY last_edited DESC LIMIT %d",
                    $table, $form_id, self::LIMIT
                ), ARRAY_A)
                : $wpdb->get_results($wpdb->prepare(
                    "SELECT id, name FROM %i ORDER BY last_edited DESC LIMIT %d",
                    $table, self::LIMIT
                ), ARRAY_A);
        }

        if (empty($rows)) {
            return [];
        }

        $items = [];
        foreach ($rows as $row) {
            $id    = (int) $row['id'];
            $label = (string) $row['name'];
            $url   = admin_url('admin.php?page=griffinforms-app&form_id=' . $id);

            $items[] = new SearchResultItem(
                result_id:      'recent_form_' . $id,
                provider_id:    $this->getProviderId(),
                label:          $label,
                action_type:    'navigate_url',
                action_payload: ['url' => $url],
                description:    '',
                icon:           'form',
                score:          0
            );
        }

        return $items;
    }
}
