<?php
/**
 * Tournament SEO and Social (Open Graph, Twitter Cards)
 *
 * @package Chess_Podium
 */

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

final class ChessPodium_TournamentSeo
{
    /**
     * Get image URL for tournament (logo or venue photo, for social sharing).
     */
    public static function get_tournament_og_image(object $tournament): string
    {
        $tid = (int) $tournament->id;
        if (class_exists('ChessPodium_PdfBrochure')) {
            $logo = ChessPodium_PdfBrochure::get_meta($tid, 'brochure_logo');
            if ($logo !== '' && $logo !== null) {
                return $logo;
            }
            $venuePhotos = ChessPodium_PdfBrochure::get_meta($tid, 'brochure_venue_photos');
            if ($venuePhotos) {
                $arr = json_decode($venuePhotos, true);
                if (is_array($arr) && !empty($arr[0])) {
                    return (string) $arr[0];
                }
            }
        }
        $photos = class_exists('ChessPodiumPlugin') ? ChessPodiumPlugin::get_photos($tid) : [];
        if (!empty($photos) && isset($photos[0]->photo_url)) {
            return (string) $photos[0]->photo_url;
        }
        return class_exists('ChessPodiumPlugin') ? ChessPodiumPlugin::get_default_logo_url() : '';
    }

    /**
     * Build meta description for tournament.
     */
    public static function get_tournament_description(object $tournament, int $playerCount = 0): string
    {
        $venue = class_exists('ChessPodium_PdfBrochure') ? ChessPodium_PdfBrochure::get_meta((int) $tournament->id, 'venue_name') : null;
        $parts = [(string) $tournament->name];
        if ($venue) {
            $parts[] = $venue;
        }
        if ($playerCount > 0) {
            $parts[] = sprintf(_n('%d player', '%d players', $playerCount, 'chess-podium'), $playerCount);
        }
        $parts[] = sprintf(__('%d rounds', 'chess-podium'), (int) $tournament->rounds_total);
        return implode(' — ', $parts);
    }

    /**
     * Output meta tags for tournament (SEO + Open Graph + Twitter).
     */
    public static function output_meta_tags(object $tournament, string $pageUrl, string $pageTitle, ?int $playerCount = null): void
    {
        $desc = self::get_tournament_description($tournament, $playerCount ?? 0);
        $image = self::get_tournament_og_image($tournament);
        $siteName = get_bloginfo('name');

        echo '<meta name="description" content="' . esc_attr(wp_strip_all_tags($desc)) . '">' . "\n";
        echo '<meta property="og:type" content="website">' . "\n";
        echo '<meta property="og:title" content="' . esc_attr(wp_strip_all_tags($pageTitle)) . '">' . "\n";
        echo '<meta property="og:description" content="' . esc_attr(wp_strip_all_tags($desc)) . '">' . "\n";
        echo '<meta property="og:url" content="' . esc_url($pageUrl) . '">' . "\n";
        echo '<meta property="og:site_name" content="' . esc_attr($siteName) . '">' . "\n";
        if ($image !== '') {
            echo '<meta property="og:image" content="' . esc_url($image) . '">' . "\n";
            echo '<meta property="og:image:width" content="1200">' . "\n";
            echo '<meta property="og:image:height" content="630">' . "\n";
        }
        echo '<meta name="twitter:card" content="summary_large_image">' . "\n";
        echo '<meta name="twitter:title" content="' . esc_attr(wp_strip_all_tags($pageTitle)) . '">' . "\n";
        echo '<meta name="twitter:description" content="' . esc_attr(wp_strip_all_tags($desc)) . '">' . "\n";
        if ($image !== '') {
            echo '<meta name="twitter:image" content="' . esc_url($image) . '">' . "\n";
        }
        echo '<link rel="canonical" href="' . esc_url($pageUrl) . '">' . "\n";
    }

    /**
     * Output meta tags for exported HTML (relative URLs, needs base).
     */
    public static function get_export_meta_html(object $tournament, string $pageTitle, string $pageUrl, ?int $playerCount = null): string
    {
        ob_start();
        self::output_meta_tags($tournament, $pageUrl, $pageTitle, $playerCount);
        return ob_get_clean();
    }

    public static function init(): void
    {
        add_action('wp', [self::class, 'maybe_register_shortcode_meta'], 5);
    }

    /**
     * When page has tournament shortcode, register wp_head callback for meta.
     */
    public static function maybe_register_shortcode_meta(): void
    {
        if (!is_singular()) {
            return;
        }
        $post = get_post();
        if (!$post || empty($post->post_content)) {
            return;
        }
        if (strpos($post->post_content, '[chess_podium_tournament') === false && strpos($post->post_content, '[regina_torneo') === false) {
            return;
        }
        $tid = 0;
        if (preg_match('/\[(?:chess_podium_tournament|regina_torneo)\s+id=["\']?(\d+)["\']?/', $post->post_content, $m)) {
            $tid = (int) $m[1];
        }
        $tournament = $tid > 0 && class_exists('ChessPodiumPlugin')
            ? ChessPodiumPlugin::get_tournament($tid)
            : (class_exists('ChessPodiumPlugin') ? ChessPodiumPlugin::get_latest_tournament() : null);
        if (!$tournament) {
            return;
        }
        $playerCount = 0;
        if (class_exists('ChessPodiumPlugin')) {
            $players = ChessPodiumPlugin::get_players((int) $tournament->id);
            $playerCount = is_array($players) ? count($players) : 0;
        }
        add_action('wp_head', function () use ($tournament, $playerCount) {
            $title = (string) $tournament->name . ' - ' . get_bloginfo('name');
            $url = get_permalink();
            if ($url) {
                ChessPodium_TournamentSeo::output_meta_tags($tournament, $url, $title, $playerCount);
            }
        }, 1);
    }
}
ChessPodium_TournamentSeo::init();
