<?php
require_once '../db.php';
require_once '../fpdf/fpdf.php';
require_once 'email_helper.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);

$logFile = __DIR__ . '/newsletter_log.txt';
file_put_contents($logFile, "\n=== " . date('Y-m-d H:i:s') . " - Certificate Generation Started ===\n", FILE_APPEND);

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    die("Invalid request method.");
}

$competition_id = intval($_POST['competition_id'] ?? 0);
if ($competition_id <= 0) {
    die("Invalid competition ID.");
}

// Fetch competition details
$comp_stmt = $conn->prepare("SELECT title FROM competitions WHERE id = ?");
$comp_stmt->bind_param("i", $competition_id);
$comp_stmt->execute();
$competition = $comp_stmt->get_result()->fetch_assoc();
$comp_stmt->close();

if (!$competition) {
    die("Competition not found.");
}

$competition_title = $competition['title'];

// Fetch all participants
$stmt = $conn->prepare("SELECT id, name, email, position, is_certificate_sent FROM competition_entries WHERE competition_id = ?");
$stmt->bind_param("i", $competition_id);
$stmt->execute();
$entries = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

if (empty($entries)) {
    die("No participants found for this competition.");
}

// Create certificate folder
$certDir = "../certificates/competition_" . $competition_id;
if (!is_dir($certDir)) mkdir($certDir, 0777, true);

// Helper for ordinal numbers
function ordinal($num) {
    $ends = ['th','st','nd','rd','th','th','th','th','th','th'];
    if ((($num % 100) >= 11) && (($num % 100) <= 13))
        return $num. 'th';
    else
        return $num. $ends[$num % 10];
}

// Custom FPDF class
class PDF_Certificate extends FPDF {
    function Header() {
        $bgPath = "../images/certificate_bg.png";
        if (file_exists($bgPath)) {
            $this->Image($bgPath, 0, 0, 297, 210);
        }

        // Decorative border
        $this->SetLineWidth(1);
        $this->SetDrawColor(150, 130, 40);
        $this->Rect(5, 5, 287, 200, 'D');
    }
}

if (ob_get_length()) ob_end_clean();

$total = $sent = $skipped = 0;

foreach ($entries as $entry) {
    $id = $entry['id'];
    $name = trim($entry['name']);
    $email = trim($entry['email']);
    $position = trim($entry['position'] ?? '');
    $alreadySent = intval($entry['is_certificate_sent'] ?? 0);

    $pdf = new PDF_Certificate('L', 'mm', 'A4');
    $pdf->AddPage();
    $pdf->SetAutoPageBreak(false);

    // ---- Certificate Layout ----
    $logoPath = "../images/ucf_logo.png";
    if (file_exists($logoPath)) {
        $pageWidth = 297;
        $logoWidth = 80; // slightly wider logo
        $xPos = ($pageWidth - $logoWidth) / 2;
        $pdf->Image($logoPath, $xPos, 25, $logoWidth);
        $pdf->Ln(65); // spacing BELOW logo (increased to prevent overlap)
    } else {
        $pdf->Ln(40);
    }

    // Determine colors and text
    if ($position == 1) {
        $title = "Certificate of Achievement";
        $subtext = "is awarded to";
        $color = [218,165,32];
    } elseif ($position == 2) {
        $title = "Certificate of Excellence";
        $subtext = "is awarded to";
        $color = [192,192,192];
    } elseif ($position == 3) {
        $title = "Certificate of Merit";
        $subtext = "is awarded to";
        $color = [205,127,50];
    } else {
        $title = "Certificate of Participation";
        $subtext = "is proudly presented to";
        $color = [0, 0, 0];
    }

    // Certificate Title
    $pdf->SetFont('Arial', 'B', 32);
    $pdf->SetTextColor($color[0], $color[1], $color[2]);
    $pdf->Cell(0, 20, $title, 0, 1, 'C');

    // Subtitle
    $pdf->Ln(8);
    $pdf->SetFont('Arial', '', 18);
    $pdf->SetTextColor(0, 0, 0);
    $pdf->Cell(0, 12, "This certificate $subtext", 0, 1, 'C');

    // Recipient name
    $pdf->Ln(6);
    $pdf->SetFont('Arial', 'B', 28);
    $pdf->SetTextColor(0, 60, 120);
    $pdf->Cell(0, 15, $name, 0, 1, 'C');

    // Participation details
    $pdf->Ln(10);
    $pdf->SetFont('Arial', '', 18);
    $pdf->SetTextColor(0, 0, 0);
    if (!empty($position)) {
        $pdf->Cell(0, 12, "for securing the position of " . ordinal($position) . " place in", 0, 1, 'C');
    } else {
        $pdf->Cell(0, 12, "for participation in", 0, 1, 'C');
    }

    // Competition name
    $pdf->Ln(3);
    $pdf->SetFont('Arial', 'I', 22);
    $pdf->SetTextColor(60, 40, 0);
    $pdf->Cell(0, 15, $competition_title, 0, 1, 'C');

    // Date and footer
    $pdf->Ln(22);
    $pdf->SetFont('Arial', '', 14);
    $pdf->SetTextColor(50, 50, 50);
    $pdf->Cell(0, 10, "Date: " . date("d M Y"), 0, 1, 'C');

    $pdf->Ln(5);
    $pdf->SetFont('Arial', 'I', 12);
    $pdf->SetTextColor(80, 80, 80);
    $pdf->Cell(0, 10, 'Issued by United Cultural Forum', 0, 1, 'C');

    // Signature (bottom right)
    $signPath = "../images/signature.png";
    if (file_exists($signPath)) {
        $pdf->Image($signPath, 220, 155, 45);
    }

    // Save PDF
    $file_path = "$certDir/{$id}_certificate.pdf";
    $pdf->Output('F', $file_path);

    $relative_path = str_replace('../', '', $file_path);
    $update = $conn->prepare("UPDATE competition_entries SET certificate_path = ? WHERE id = ?");
    $update->bind_param("si", $relative_path, $id);
    $update->execute();
    $update->close();
    $total++;

    // Skip already emailed
    if ($alreadySent === 1) {
        $skipped++;
        continue;
    }

    // Email
    $subject = "Your Certificate - $competition_title";
    $body = "
        <p>Dear <strong>$name</strong>,</p>
        <p>Congratulations on your participation in <b>$competition_title</b>!</p>
        <p>Please find your attached certificate below.</p>
        <p>Warm regards,<br><strong>United Cultural Forum</strong></p>
    ";

    $emailSent = admin_send_email($email, $subject, $body);

    if ($emailSent) {
        $sent++;
        file_put_contents($logFile, "✅ Email sent to $email\n", FILE_APPEND);
        $flag = 1;
    } else {
        file_put_contents($logFile, "❌ Email failed to $email\n", FILE_APPEND);
        $flag = 0;
    }

    $update2 = $conn->prepare("UPDATE competition_entries SET is_certificate_sent = ?, emailed_at = NOW() WHERE id = ?");
    $update2->bind_param("ii", $flag, $id);
    $update2->execute();
    $update2->close();
}

// Output success
header("Content-Type: text/html; charset=UTF-8");
echo "<div style='padding:40px; text-align:center; font-family:Arial; color:green;'>
<h2>✅ $total Certificates Processed</h2>
<h3>📧 $sent Emails Sent Successfully</h3>
<h4>🕓 $skipped Skipped (Already Sent)</h4>
<p>Saved under: <b>$certDir</b></p>
<a href='competition_entries.php?id=$competition_id' 
   style='display:inline-block;margin-top:20px;color:#0066cc;text-decoration:none;font-size:18px;'>
   ← Back to Entries
</a>
</div>";
?>
