<?php

namespace GriffinForms\Includes\CommandPalette\Providers;

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

class ThemesProvider implements SearchProviderInterface
{
    private Config $config;

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

    public function getProviderId(): string { return 'themes'; }
    public function getLabel(): string      { return 'Themes'; }
    public function getPriority(): int      { return 40; }
    public function getQuickItems(int $form_id): array { return []; }

    public function query(string $query, int $form_id): array
    {
        if ($query === '') {
            return [];
        }

        global $wpdb;

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

        $like  = '%' . $wpdb->esc_like($query) . '%';
        $rows  = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT id, name, description FROM %i WHERE name LIKE %s ORDER BY name ASC LIMIT 10",
                $table, $like
            ),
            ARRAY_A
        );

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

        $results = [];
        foreach ($rows as $row) {
            $id   = (int) $row['id'];
            $name = (string) $row['name'];
            $desc = (string) ($row['description'] ?? '');
            if (strlen($desc) > 80) {
                $desc = substr($desc, 0, 80) . '…';
            }

            $results[] = new SearchResultItem(
                result_id:      'theme_' . $id,
                provider_id:    $this->getProviderId(),
                label:          $name,
                action_type:    'open_modal_with_context',
                action_payload: [
                    'modal_id' => 'griffinforms-builder-modal-formthemes',
                    'context'  => ['theme_id' => $id],
                ],
                description:    $desc,
                icon:           'theme',
                score:          0
            );
        }

        return $results;
    }
}
