<?php
/**
 * Fair play / anti-cheating: player-facing summary aligned with FIDE Handbook §09 themes.
 *
 * @package Chess_Podium
 */

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

final class ChessPodium_FairPlayDisplay
{
    /**
     * @return array<string, string> slug => translated description for players
     */
    public static function measure_definitions(): array
    {
        return [
            'no_devices_playing_venue' => __('In the playing venue, electronic devices capable of communication or chess assistance are not permitted, except as explicitly authorised by the arbiters.', 'chess-podium'),
            'devices_off_or_deposited' => __('Mobile phones and similar devices must be switched off and may be deposited or stored outside the playing area as instructed before play.', 'chess-podium'),
            'cooperation_with_screening' => __('Players must cooperate with arbiters and fair play officials with proportionate screening measures (e.g. bag checks) applied at this event.', 'chess-podium'),
            'random_checks' => __('Random checks may be carried out during the tournament as decided by the arbiters.', 'chess-podium'),
            'delayed_live_transmission' => __('If games are broadcast live, transmission may be delayed relative to the boards, as announced by the organizers.', 'chess-podium'),
            'fair_play_officer_named' => __('A fair play contact or officer is designated for this event (see below).', 'chess-podium'),
            'complaint_procedure_known' => __('Information on raising concerns or complaints follows FIDE Fair Play procedures; ask the arbiters or see official FIDE forms and regulations.', 'chess-podium'),
        ];
    }

    /**
     * @return string[] valid slugs from raw JSON or array
     */
    public static function decode_measures(?string $json): array
    {
        if ($json === null || $json === '') {
            return [];
        }
        $decoded = json_decode($json, true);
        if (!is_array($decoded)) {
            return [];
        }
        $allowed = array_keys(self::measure_definitions());
        $out = [];
        foreach ($decoded as $slug) {
            $slug = is_string($slug) ? sanitize_key($slug) : '';
            if ($slug !== '' && in_array($slug, $allowed, true)) {
                $out[] = $slug;
            }
        }
        return array_values(array_unique($out));
    }

    /**
     * @param string[] $slugs
     */
    public static function encode_measures(array $slugs): string
    {
        $allowed = array_keys(self::measure_definitions());
        $clean = [];
        foreach ($slugs as $s) {
            $s = sanitize_key((string) $s);
            if ($s !== '' && in_array($s, $allowed, true)) {
                $clean[] = $s;
            }
        }
        $clean = array_values(array_unique($clean));
        sort($clean);
        return wp_json_encode($clean);
    }

    public static function should_display(object $tournament): bool
    {
        return !empty($tournament->fair_play_public);
    }

    /**
     * HTML fragment for live page and static export (already escaped).
     */
    public static function render_section_html(object $tournament): string
    {
        if (!self::should_display($tournament)) {
            return '';
        }
        $measures = self::decode_measures(isset($tournament->fair_play_measures) ? (string) $tournament->fair_play_measures : '');
        $defs = self::measure_definitions();
        $officer = isset($tournament->fair_play_officer) ? trim((string) $tournament->fair_play_officer) : '';
        $complaintUrlRaw = isset($tournament->fair_play_complaint_url) ? trim((string) $tournament->fair_play_complaint_url) : '';
        $complaintUrl = ($complaintUrlRaw !== '') ? esc_url($complaintUrlRaw) : '';
        $additional = isset($tournament->fair_play_additional) ? trim((string) $tournament->fair_play_additional) : '';
        $hasDetail = $measures !== [] || $officer !== '' || $complaintUrlRaw !== '' || $additional !== '';

        $handbookUrl = 'https://handbook.fide.com/chapter/AntiCheatingRegulations';
        $fplPdfUrl = 'https://handbook.fide.com/files/handbook/FPL_Regulations_2024.pdf';

        ob_start();
        ?>
        <section class="cp-fair-play" id="cp-fair-play" style="margin:1.5rem 0;padding:1rem 1.25rem;border:1px solid #e2e8f0;border-radius:8px;background:#f8fafc;">
            <h2 style="margin-top:0;"><?php echo esc_html__('Fair play & anti-cheating', 'chess-podium'); ?></h2>
            <p class="cp-fair-play-intro" style="font-size:0.95em;color:#475569;margin-top:0;">
                <?php echo esc_html__('The following is a player-facing summary of measures announced for this tournament. It reflects common themes from the FIDE Handbook (§09 Anti-Cheating / Fair Play). It does not replace the official FIDE regulations, protection measures, or the arbiters’ instructions.', 'chess-podium'); ?>
                <?php
                echo ' ';
                echo '<a href="' . esc_url($handbookUrl) . '" target="_blank" rel="noopener noreferrer">' . esc_html__('FIDE Handbook — Anti-Cheating', 'chess-podium') . '</a>';
                echo ' · ';
                echo '<a href="' . esc_url($fplPdfUrl) . '" target="_blank" rel="noopener noreferrer">' . esc_html__('Fair Play Regulations (PDF)', 'chess-podium') . '</a>';
                ?>
            </p>
            <?php if ($measures !== []): ?>
                <h3 style="font-size:1.05em;margin-bottom:0.5rem;"><?php echo esc_html__('Measures for this event', 'chess-podium'); ?></h3>
                <ul style="margin:0 0 1rem 1.25rem;padding:0;">
                    <?php foreach ($measures as $slug): ?>
                        <?php if (isset($defs[$slug])): ?>
                            <li style="margin-bottom:0.35em;"><?php echo esc_html($defs[$slug]); ?></li>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </ul>
            <?php elseif (!$hasDetail): ?>
                <p style="margin:0 0 1rem;color:#64748b;font-size:0.95em;"><?php echo esc_html__('The organizers will publish specific fair play measures for this event here.', 'chess-podium'); ?></p>
            <?php endif; ?>
            <?php if ($officer !== ''): ?>
                <p style="margin:0.75rem 0 0;"><strong><?php echo esc_html__('Fair play contact / officer', 'chess-podium'); ?>:</strong> <?php echo esc_html($officer); ?></p>
            <?php endif; ?>
            <?php if ($complaintUrl !== '' && $complaintUrlRaw !== ''): ?>
                <p style="margin:0.5rem 0 0;">
                    <a href="<?php echo esc_url($complaintUrl); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('Complaints or further information (link)', 'chess-podium'); ?></a>
                </p>
            <?php endif; ?>
            <?php if ($additional !== ''): ?>
                <div class="cp-fair-play-additional" style="margin-top:1rem;font-size:0.95em;">
                    <h3 style="font-size:1.05em;margin-bottom:0.5rem;"><?php echo esc_html__('Additional protocols & local rules', 'chess-podium'); ?></h3>
                    <div class="cp-fair-play-additional-body"><?php echo wp_kses_post($additional); ?></div>
                </div>
            <?php endif; ?>
        </section>
        <?php
        return (string) ob_get_clean();
    }
}
