<?php
/**
 * PDF Certificate Generator - Diplomas and participation certificates
 *
 * @package Chess_Podium
 */

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

final class ChessPodium_PdfCertificate
{
    /**
     * Get proportional dimensions for image to fit within max box (preserves aspect ratio).
     *
     * @param string $url    Image URL (local or remote).
     * @param int    $maxW   Max width in px.
     * @param int    $maxH   Max height in px.
     * @return array{width: int, height: int}
     */
    private static function get_image_fit_dimensions(string $url, int $maxW, int $maxH): array
    {
        $w = $maxW;
        $h = $maxH;
        $path = '';
        $url = strtok($url, '?');
        $uploadDir = wp_upload_dir();
        $baseUrl = rtrim($uploadDir['baseurl'], '/');
        $baseDir = rtrim($uploadDir['basedir'], DIRECTORY_SEPARATOR);
        if ($baseUrl !== '' && strpos($url, $baseUrl) === 0) {
            $path = $baseDir . str_replace('/', DIRECTORY_SEPARATOR, substr($url, strlen($baseUrl)));
        } elseif (defined('CHESS_PODIUM_PLUGIN_DIR')) {
            $pluginUrl = plugins_url('', CHESS_PODIUM_PLUGIN_DIR . '/chess-podium.php');
            if ($pluginUrl !== '' && strpos($url, $pluginUrl) === 0) {
                $rel = substr($url, strlen($pluginUrl));
                $path = CHESS_PODIUM_PLUGIN_DIR . str_replace('/', DIRECTORY_SEPARATOR, $rel);
            }
        }
        if ($path !== '' && file_exists($path) && is_readable($path)) {
            $size = @getimagesize($path);
            if ($size && isset($size[0], $size[1]) && $size[0] > 0 && $size[1] > 0) {
                $ratio = min($maxW / $size[0], $maxH / $size[1], 1.0);
                $w = (int) round($size[0] * $ratio);
                $h = (int) round($size[1] * $ratio);
                $w = max(20, min($w, $maxW));
                $h = max(20, min($h, $maxH));
            }
        }
        return ['width' => $w, 'height' => $h];
    }

    private static function get_certificate_assets(int $tournamentId): array
    {
        $logo = ChessPodium_PdfBrochure::get_meta($tournamentId, 'brochure_logo') ?: '';
        $venuePhotos = ChessPodium_PdfBrochure::get_meta($tournamentId, 'brochure_venue_photos');
        $venuePhoto = '';
        if ($venuePhotos) {
            $arr = json_decode($venuePhotos, true);
            if (is_array($arr) && !empty($arr[0])) {
                $venuePhoto = (string) $arr[0];
            }
        }
        if ($logo === '' && class_exists('ChessPodiumPlugin')) {
            $logo = ChessPodiumPlugin::get_default_logo_url();
        }
        return ['logo' => $logo, 'venue_photo' => $venuePhoto];
    }

    /**
     * Generate HTML for a single winner diploma (1st, 2nd, 3rd).
     */
    public static function generate_winner_html(object $tournament, array $player, int $position, float $points): string
    {
        $positionLabels = [
            1 => __('1st place', 'chess-podium'),
            2 => __('2nd place', 'chess-podium'),
            3 => __('3rd place', 'chess-podium'),
        ];
        $positionLabel = $positionLabels[$position] ?? sprintf(__('%dth place', 'chess-podium'), $position);
        $venueName = ChessPodium_PdfBrochure::get_meta((int) $tournament->id, 'venue_name') ?: '';
        $startDate = ChessPodium_PdfBrochure::get_meta((int) $tournament->id, 'start_date') ?: '';
        $dateFormatted = $startDate ? date_i18n(get_option('date_format'), strtotime($startDate)) : '';
        $assets = self::get_certificate_assets((int) $tournament->id);

        ob_start();
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <style>
                @page { margin: 1.2cm; }
                body { font-family: "DejaVu Sans", Helvetica, Arial, sans-serif; margin: 0; padding: 0; color: #1a365d; background: #fefefe; }
                .cp-cert-wrap { min-height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; padding: 20px 0; }
                .cp-cert-border { border: 4px double #c9a227; padding: 36px 48px; max-width: 88%; background: #fff; box-shadow: 0 0 0 1px #e2e8f0; }
                .cp-cert-logo { width: 140px; height: 56px; margin: 0 auto 16px; display: block; }
                .cp-cert-title { font-family: "DejaVu Serif", Georgia, serif; font-size: 13pt; font-weight: bold; color: #1a365d; text-transform: uppercase; letter-spacing: 3px; margin: 0 0 6px 0; border-bottom: 2px solid #c9a227; display: inline-block; padding-bottom: 4px; }
                .cp-cert-tournament { font-family: "DejaVu Serif", Georgia, serif; font-size: 24pt; font-weight: bold; color: #1a365d; margin: 14px 0 20px 0; line-height: 1.3; }
                .cp-cert-details { font-size: 11pt; color: #4a5568; margin: 6px 0; }
                .cp-cert-award { font-size: 14pt; color: #c9a227; font-weight: bold; margin: 18px 0 16px 0; text-transform: uppercase; letter-spacing: 2px; }
                .cp-cert-name { font-family: "DejaVu Serif", Georgia, serif; font-size: 30pt; font-weight: bold; color: #1a365d; margin: 12px 0 8px 0; }
                .cp-cert-footer { font-size: 9pt; color: #718096; margin-top: 24px; padding-top: 12px; border-top: 1px solid #e2e8f0; }
                .cp-cert-venue-img { width: 160px; height: 64px; margin: 16px auto 0; display: block; border: 1px solid #e2e8f0; }
            </style>
        </head>
        <body>
        <div class="cp-cert-wrap">
            <div class="cp-cert-border">
                <?php if ($assets['logo'] !== ''): ?>
                <?php $logoDim = self::get_image_fit_dimensions($assets['logo'], 160, 80); ?>
                <p><img src="<?php echo esc_url($assets['logo']); ?>" alt="" class="cp-cert-logo" style="width:<?php echo (int) $logoDim['width']; ?>px;height:<?php echo (int) $logoDim['height']; ?>px;display:block;margin:0 auto 16px;"></p>
                <?php endif; ?>
                <p class="cp-cert-title"><?php esc_html_e('Certificate of merit', 'chess-podium'); ?></p>
                <h1 class="cp-cert-tournament"><?php echo esc_html((string) $tournament->name); ?></h1>
                <?php if ($venueName || $dateFormatted): ?>
                <p class="cp-cert-details"><?php echo esc_html(trim($venueName . ($venueName && $dateFormatted ? ' — ' : '') . $dateFormatted)); ?></p>
                <?php endif; ?>
                <p class="cp-cert-award"><?php echo esc_html($positionLabel); ?></p>
                <p class="cp-cert-name"><?php echo esc_html($player['name'] ?? ''); ?></p>
                <p class="cp-cert-details"><?php echo esc_html(sprintf(__('%s points', 'chess-podium'), number_format($points, 1, ',', ''))); ?></p>
                <?php if (!empty($player['title'])): ?>
                <p class="cp-cert-details"><?php echo esc_html($player['title']); ?></p>
                <?php endif; ?>
                <?php if ($assets['venue_photo'] !== ''): ?>
                <?php $venueDim = self::get_image_fit_dimensions($assets['venue_photo'], 200, 120); ?>
                <p><img src="<?php echo esc_url($assets['venue_photo']); ?>" alt="" class="cp-cert-venue-img" style="width:<?php echo (int) $venueDim['width']; ?>px;height:<?php echo (int) $venueDim['height']; ?>px;display:block;margin:16px auto 0;"></p>
                <?php endif; ?>
                <p class="cp-cert-footer"><?php echo esc_html((string) $tournament->name); ?> &bull; Chess Podium</p>
            </div>
        </div>
        </body>
        </html>
        <?php
        return ob_get_clean();
    }

    /**
     * Generate HTML for a participation certificate.
     */
    public static function generate_participation_html(object $tournament, array $player, float $points): string
    {
        $venueName = ChessPodium_PdfBrochure::get_meta((int) $tournament->id, 'venue_name') ?: '';
        $startDate = ChessPodium_PdfBrochure::get_meta((int) $tournament->id, 'start_date') ?: '';
        $dateFormatted = $startDate ? date_i18n(get_option('date_format'), strtotime($startDate)) : '';
        $roundsTotal = (int) $tournament->rounds_total ?: 0;
        $assets = self::get_certificate_assets((int) $tournament->id);

        ob_start();
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <style>
                @page { margin: 1.2cm; }
                body { font-family: "DejaVu Sans", Helvetica, Arial, sans-serif; margin: 0; padding: 0; color: #1a365d; background: #fefefe; }
                .cp-cert-wrap { min-height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; padding: 20px 0; }
                .cp-cert-border { border: 3px solid #2c5282; padding: 32px 44px; max-width: 88%; background: #fff; box-shadow: 0 0 0 1px #e2e8f0; border-radius: 2px; }
                .cp-cert-logo { width: 120px; height: 48px; margin: 0 auto 14px; display: block; }
                .cp-cert-title { font-family: "DejaVu Serif", Georgia, serif; font-size: 12pt; font-weight: bold; color: #2d3748; text-transform: uppercase; letter-spacing: 3px; margin: 0 0 6px 0; border-bottom: 2px solid #2c5282; display: inline-block; padding-bottom: 4px; }
                .cp-cert-tournament { font-family: "DejaVu Serif", Georgia, serif; font-size: 20pt; font-weight: bold; color: #1a365d; margin: 12px 0 18px 0; line-height: 1.3; }
                .cp-cert-name { font-family: "DejaVu Serif", Georgia, serif; font-size: 24pt; font-weight: bold; color: #1a365d; margin: 14px 0 8px 0; }
                .cp-cert-details { font-size: 10pt; color: #4a5568; margin: 6px 0; }
                .cp-cert-footer { font-size: 9pt; color: #718096; margin-top: 20px; padding-top: 12px; border-top: 1px solid #e2e8f0; }
                .cp-cert-venue-img { width: 140px; height: 56px; margin: 14px auto 0; display: block; border: 1px solid #e2e8f0; }
            </style>
        </head>
        <body>
        <div class="cp-cert-wrap">
            <div class="cp-cert-border">
                <?php if ($assets['logo'] !== ''): ?>
                <?php $logoDim = self::get_image_fit_dimensions($assets['logo'], 140, 70); ?>
                <p><img src="<?php echo esc_url($assets['logo']); ?>" alt="" class="cp-cert-logo" style="width:<?php echo (int) $logoDim['width']; ?>px;height:<?php echo (int) $logoDim['height']; ?>px;display:block;margin:0 auto 14px;"></p>
                <?php endif; ?>
                <p class="cp-cert-title"><?php esc_html_e('Certificate of participation', 'chess-podium'); ?></p>
                <h1 class="cp-cert-tournament"><?php echo esc_html((string) $tournament->name); ?></h1>
                <?php if ($venueName || $dateFormatted): ?>
                <p class="cp-cert-details"><?php echo esc_html(trim($venueName . ($venueName && $dateFormatted ? ' — ' : '') . $dateFormatted)); ?></p>
                <?php endif; ?>
                <p class="cp-cert-name"><?php echo esc_html($player['name'] ?? ''); ?></p>
                <p class="cp-cert-details"><?php echo esc_html(sprintf(__('%s points', 'chess-podium'), number_format($points, 1, ',', ''))); ?><?php echo $roundsTotal > 0 ? ' &bull; ' . esc_html(sprintf(__('%d rounds', 'chess-podium'), $roundsTotal)) : ''; ?></p>
                <?php if (!empty($player['title'])): ?>
                <p class="cp-cert-details"><?php echo esc_html($player['title']); ?></p>
                <?php endif; ?>
                <?php if ($assets['venue_photo'] !== ''): ?>
                <?php $venueDim = self::get_image_fit_dimensions($assets['venue_photo'], 180, 100); ?>
                <p><img src="<?php echo esc_url($assets['venue_photo']); ?>" alt="" class="cp-cert-venue-img" style="width:<?php echo (int) $venueDim['width']; ?>px;height:<?php echo (int) $venueDim['height']; ?>px;display:block;margin:14px auto 0;"></p>
                <?php endif; ?>
                <p class="cp-cert-footer"><?php echo esc_html((string) $tournament->name); ?> &bull; Chess Podium</p>
            </div>
        </div>
        </body>
        </html>
        <?php
        return ob_get_clean();
    }

    /**
     * Generate a PDF with multiple certificates (one per page).
     *
     * @param int    $tournamentId Tournament ID.
     * @param string $type         'winners' (top 3) or 'participation' (all).
     * @return string|null PDF binary content or null on failure.
     */
    public static function generate_pdf(int $tournamentId, string $type): ?string
    {
        $locale = function_exists('get_user_locale') ? get_user_locale() : get_locale();
        if (function_exists('switch_to_locale') && $locale) {
            switch_to_locale($locale);
        }
        if (class_exists('ChessPodiumPlugin')) {
            ChessPodiumPlugin::load_textdomain();
        }

        $tournament = ChessPodiumPlugin::get_tournament($tournamentId);
        if (!$tournament) {
            if (function_exists('restore_previous_locale')) {
                restore_previous_locale();
            }
            return null;
        }

        $standings = ChessPodiumPlugin::compute_standings($tournamentId);
        if (empty($standings)) {
            if (function_exists('restore_previous_locale')) {
                restore_previous_locale();
            }
            return null;
        }

        $autoload = CHESS_PODIUM_PLUGIN_DIR . '/lib/dompdf/vendor/autoload.php';
        if (!file_exists($autoload)) {
            $autoload = CHESS_PODIUM_PLUGIN_DIR . '/vendor/autoload.php';
        }
        if (!file_exists($autoload)) {
            return null;
        }
        require_once $autoload;
        if (!class_exists('Dompdf\Dompdf')) {
            return null;
        }

        $htmlParts = [];

        if ($type === 'winners') {
            $top = array_slice($standings, 0, 3);
            foreach ($top as $i => $row) {
                $position = $i + 1;
                $htmlParts[] = self::generate_winner_html($tournament, $row, $position, (float) ($row['points'] ?? 0));
            }
        } else {
            foreach ($standings as $row) {
                $htmlParts[] = self::generate_participation_html($tournament, $row, (float) ($row['points'] ?? 0));
            }
        }

        if (empty($htmlParts)) {
            return null;
        }

        $fullHtml = self::combine_pages($htmlParts);

        $dompdf = new \Dompdf\Dompdf(['isRemoteEnabled' => true]);
        $dompdf->loadHtml($fullHtml, 'UTF-8');
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();
        $output = $dompdf->output();

        if (function_exists('restore_previous_locale')) {
            restore_previous_locale();
        }
        return $output;
    }

    /**
     * Combine multiple certificate HTML pages with page breaks.
     */
    private static function combine_pages(array $htmlParts): string
    {
        $style = '
            @page { margin: 1.2cm; }
            body { font-family: "DejaVu Sans", Helvetica, Arial, sans-serif; margin: 0; padding: 0; color: #1a365d; background: #fefefe; }
            .cp-cert-page { page-break-after: always; min-height: 100vh; }
            .cp-cert-page:last-child { page-break-after: auto; }
            .cp-cert-wrap { text-align: center; padding: 20px 0; }
            .cp-cert-border { border: 4px double #c9a227; padding: 36px 48px; max-width: 88%; margin: 0 auto; background: #fff; }
            .cp-cert-logo { width: 140px; height: 56px; margin: 0 auto 16px; display: block; }
            .cp-cert-title { font-family: "DejaVu Serif", Georgia, serif; font-size: 13pt; font-weight: bold; color: #1a365d; text-transform: uppercase; letter-spacing: 3px; margin: 0 0 6px 0; border-bottom: 2px solid #c9a227; display: inline-block; padding-bottom: 4px; }
            .cp-cert-tournament { font-family: "DejaVu Serif", Georgia, serif; font-size: 24pt; font-weight: bold; color: #1a365d; margin: 14px 0 20px 0; line-height: 1.3; }
            .cp-cert-details { font-size: 11pt; color: #4a5568; margin: 6px 0; }
            .cp-cert-award { font-size: 14pt; color: #c9a227; font-weight: bold; margin: 18px 0 16px 0; text-transform: uppercase; letter-spacing: 2px; }
            .cp-cert-name { font-family: "DejaVu Serif", Georgia, serif; font-size: 30pt; font-weight: bold; color: #1a365d; margin: 12px 0 8px 0; }
            .cp-cert-footer { font-size: 9pt; color: #718096; margin-top: 24px; padding-top: 12px; border-top: 1px solid #e2e8f0; }
            .cp-cert-venue-img { width: 160px; height: 64px; margin: 16px auto 0; display: block; border: 1px solid #e2e8f0; }
        ';
        $pages = [];
        foreach ($htmlParts as $html) {
            $doc = new \DOMDocument();
            libxml_use_internal_errors(true);
            $doc->loadHTML('<?xml encoding="UTF-8">' . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
            libxml_clear_errors();
            $body = $doc->getElementsByTagName('body')->item(0);
            $inner = $body ? $doc->saveHTML($body) : $html;
            $pages[] = '<div class="cp-cert-page">' . preg_replace('/<\/?body[^>]*>/', '', $inner) . '</div>';
        }
        // HTML string for dompdf PDF output only; not sent to browser. wp_enqueue_style does not apply.
        return '<!DOCTYPE html><html><head><meta charset="UTF-8"><style>' . $style . '</style></head><body>' . implode('', $pages) . '</body></html>';
    }
}
