<?php
// File: /admin/generate_certificate.php
require_once '../db.php';
require_once 'email_helper.php';
require_once '../fpdf/fpdf.php';

class PDF_Certificate extends FPDF {
    function Header() {
        // Optional background image
        if (file_exists("../images/certificate_bg.jpg")) {
            $this->Image("../images/certificate_bg.jpg", 0, 0, 297, 210);
        }

        // Gold border frame
        $this->SetDrawColor(218, 165, 32); // gold
        $this->SetLineWidth(2);
        $this->Rect(10, 10, 277, 190, 'D');
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $entry_id = intval($_POST['entry_id']);
    $position = $_POST['position'];
    $competition_id = intval($_POST['competition_id']);

    $entry = $conn->query("SELECT * FROM competition_entries WHERE id = $entry_id")->fetch_assoc();
    $competition = $conn->query("SELECT * FROM competitions WHERE id = $competition_id")->fetch_assoc();

    if (!$entry || !$competition) {
        die("Invalid entry or competition data.");
    }

    $cert_dir = "../certificates/competition_{$competition_id}/";
    if (!is_dir($cert_dir)) mkdir($cert_dir, 0777, true);

    $isWinner = in_array($position, ['1st', '2nd', '3rd']);
    $title = $isWinner ? 'Certificate of Achievement' : 'Certificate of Participation';
    $filename = "{$cert_dir}" . strtolower($position === 'none' ? 'participation' : $position) . "_{$entry['id']}.pdf";

    // Create PDF
    $pdf = new PDF_Certificate('L', 'mm', 'A4');
    $pdf->AddPage();

    // Logo
    if (file_exists("../images/logo.png")) {
        $pdf->Image("../images/logo.png", 15, 15, 35);
    }

    // Title
    $pdf->SetFont('Times', 'B', 38);
    $pdf->SetTextColor(184, 134, 11); // gold text
    $pdf->Cell(0, 40, $title, 0, 1, 'C');

    // Participant info
    $pdf->SetFont('Times', '', 20);
    $pdf->SetTextColor(0, 0, 0);
    $pdf->Ln(10);
    $pdf->Cell(0, 10, 'This certificate is proudly presented to', 0, 1, 'C');
    $pdf->SetFont('Times', 'B', 26);
    $pdf->Cell(0, 15, strtoupper($entry['name']), 0, 1, 'C');
    $pdf->Ln(10);

    $pdf->SetFont('Times', '', 18);
    if ($isWinner) {
        $pdf->Cell(0, 10, "for securing the {$position} place in", 0, 1, 'C');
    } else {
        $pdf->Cell(0, 10, "for participating in", 0, 1, 'C');
    }

    $pdf->SetFont('Times', 'B', 22);
    $pdf->Cell(0, 12, '"' . $competition['title'] . '"', 0, 1, 'C');
    $pdf->Ln(15);

    // Date
    $pdf->SetFont('Times', '', 14);
    $pdf->Cell(0, 10, "Date: " . date('F j, Y'), 0, 1, 'C');

    // Signature
    if (file_exists("../images/signature.png")) {
        $pdf->Image("../images/signature.png", 220, 135, 45);
    }

    $pdf->SetFont('Arial', 'I', 14);
    $pdf->SetTextColor(0, 80, 0);
    $pdf->Ln(20);
    $pdf->Cell(0, 10, "United Cultural Forum", 0, 1, 'C');

    $pdf->Output('F', $filename);

    // Update DB
    $stmt = $conn->prepare("UPDATE competition_entries 
                            SET position=?, certificate_path=?, certificate_sent_at=NOW() 
                            WHERE id=?");
    $stmt->bind_param("ssi", $position, $filename, $entry_id);
    $stmt->execute();
    $stmt->close();

    // Send email
    $subject = $isWinner 
        ? "🎉 Congratulations! You Won {$position} Place in {$competition['title']}"
        : "Thank You for Participating in {$competition['title']}";

    $body = "
        <p>Dear <strong>{$entry['name']}</strong>,</p>
        <p>" . ($isWinner 
                ? "We are delighted to inform you that you have secured the <strong>{$position}</strong> place in <em>{$competition['title']}</em>!" 
                : "We sincerely appreciate your participation in the <em>{$competition['title']}</em> competition.") . "</p>
        <p>Your official certificate is attached below.</p>
        <p>Warm regards,<br><strong>United Cultural Forum</strong></p>
    ";

    admin_send_email($entry['email'], $subject, $body);
    header("Location: competition_entries.php?id={$competition_id}&status=cert_sent");
    exit();
}
?>
