<?php
/**
 * Sponsor Manager - Logos displayed on tournament pages and brochure PDF
 *
 * @package Chess_Podium
 */

if (!defined('ABSPATH')) {
    exit;
}

final class ChessPodium_Sponsors
{
    public static function db_table(): string
    {
        global $wpdb;
        return $wpdb->prefix . 'regina_sponsors';
    }

    public static function create_table(): void
    {
        global $wpdb;
        $table = self::db_table();
        if ($wpdb->get_var("SHOW TABLES LIKE '$table'") !== $table) {
            $charset = $wpdb->get_charset_collate();
            $sql = "CREATE TABLE $table (
                id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
                name VARCHAR(191) NOT NULL DEFAULT '',
                logo_url VARCHAR(500) NOT NULL DEFAULT '',
                url VARCHAR(500) NULL,
                sort_order INT NOT NULL DEFAULT 0,
                tournament_ids TEXT NULL,
                created_at DATETIME NOT NULL,
                PRIMARY KEY (id),
                KEY sort_order (sort_order)
            ) $charset";
            require_once ABSPATH . 'wp-admin/includes/upgrade.php';
            dbDelta($sql);
        }
        $col = $wpdb->get_var("SHOW COLUMNS FROM $table LIKE 'tournament_ids'"); // phpcs:ignore
        if ($col === null) {
            $wpdb->query("ALTER TABLE $table ADD COLUMN tournament_ids TEXT NULL AFTER sort_order"); // phpcs:ignore
        }
    }

    public static function get_all(): array
    {
        global $wpdb;
        $table = self::db_table();
        $rows = $wpdb->get_results("SELECT id, name, logo_url, url, sort_order, tournament_ids FROM $table ORDER BY sort_order ASC, id ASC");
        return $rows ?: [];
    }

    /** Returns sponsors that apply to the given tournament. NULL/empty tournament_ids = all tournaments. */
    public static function get_for_tournament(int $tournamentId): array
    {
        $all = self::get_all();
        $result = [];
        foreach ($all as $s) {
            $ids = $s->tournament_ids ?? '';
            if ($ids === '' || $ids === null) {
                $result[] = $s;
                continue;
            }
            $decoded = json_decode($ids, true);
            if (!is_array($decoded)) {
                $result[] = $s;
                continue;
            }
            if (in_array($tournamentId, array_map('intval', $decoded), true)) {
                $result[] = $s;
            }
        }
        return $result;
    }

    public static function add(string $name, string $logoUrl, string $url = '', array $tournamentIds = []): int
    {
        global $wpdb;
        $table = self::db_table();
        $maxOrder = (int) $wpdb->get_var("SELECT COALESCE(MAX(sort_order), 0) FROM $table");
        $tidsJson = empty($tournamentIds) ? null : wp_json_encode(array_values(array_map('intval', array_unique($tournamentIds))));
        $wpdb->insert($table, [
            'name' => $name,
            'logo_url' => $logoUrl,
            'url' => $url ?: null,
            'sort_order' => $maxOrder + 1,
            'tournament_ids' => $tidsJson,
            'created_at' => current_time('mysql'),
        ], ['%s', '%s', '%s', '%d', '%s', '%s']);
        return (int) $wpdb->insert_id;
    }

    public static function update(int $id, string $name, string $logoUrl, string $url = '', array $tournamentIds = []): bool
    {
        global $wpdb;
        $table = self::db_table();
        $tidsJson = empty($tournamentIds) ? null : wp_json_encode(array_values(array_map('intval', array_unique($tournamentIds))));
        return (bool) $wpdb->update($table, [
            'name' => $name,
            'logo_url' => $logoUrl,
            'url' => $url ?: null,
            'tournament_ids' => $tidsJson,
        ], ['id' => $id], ['%s', '%s', '%s', '%s'], ['%d']);
    }

    public static function delete(int $id): bool
    {
        global $wpdb;
        $table = self::db_table();
        return (bool) $wpdb->delete($table, ['id' => $id], ['%d']);
    }

    public static function reorder(array $ids): void
    {
        global $wpdb;
        $table = self::db_table();
        foreach ($ids as $i => $id) {
            $wpdb->update($table, ['sort_order' => $i], ['id' => (int) $id], ['%d'], ['%d']);
        }
    }

    /** Returns HTML for sponsor logos. Pass $tournamentId to filter by tournament (null = all). */
    public static function render_html(string $cssClass = 'cp-sponsors', ?int $tournamentId = null): string
    {
        $sponsors = $tournamentId !== null ? self::get_for_tournament($tournamentId) : self::get_all();
        if (empty($sponsors)) {
            return '';
        }
        $items = '';
        foreach ($sponsors as $s) {
            $logoUrl = esc_url((string) $s->logo_url);
            $name = esc_attr((string) $s->name);
            $url = !empty($s->url) ? esc_url((string) $s->url) : '';
            $img = '<img src="' . $logoUrl . '" alt="' . $name . '" class="cp-sponsor-logo" loading="lazy">';
            $items .= '<span class="cp-sponsor-item">';
            if ($url) {
                $items .= '<a href="' . $url . '" target="_blank" rel="noopener nofollow" title="' . $name . '">' . $img . '</a>';
            } else {
                $items .= $img;
            }
            $items .= '</span>';
        }
        return '<div class="' . esc_attr($cssClass) . '"><div class="cp-sponsors-inner">' . $items . '</div></div>';
    }

    /**
     * Enqueue admin scripts for the sponsors page (Media Library for logo selection).
     * Must be called from admin_enqueue_scripts when on the sponsors page.
     * Requires wp_enqueue_media() to be called beforehand.
     */
    public static function enqueue_admin_scripts(): void
    {
        $pluginFile = defined('CHESS_PODIUM_PLUGIN_DIR') ? CHESS_PODIUM_PLUGIN_DIR . '/chess-podium.php' : dirname(__DIR__) . '/chess-podium.php';
        wp_enqueue_script(
            'chess-podium-sponsors-admin',
            plugins_url('assets/js/sponsors-admin.js', $pluginFile),
            ['jquery'],
            '1.0.0',
            true
        );
        wp_localize_script('chess-podium-sponsors-admin', 'chessPodiumSponsorsAdmin', [
            'selectTitle' => __('Select sponsor logo', 'chess-podium'),
            'useImageText' => __('Use image', 'chess-podium'),
        ]);
    }
}
