<?php
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);

include "db.php";

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$user_id   = $_SESSION['user_id'];
$course_id = isset($_GET['course']) ? intval($_GET['course']) : 0;

/* ---------- FETCH USER ---------- */
$userStmt = $conn->prepare("SELECT fullname FROM users WHERE id=?");
$userStmt->bind_param("i", $user_id);
$userStmt->execute();
$user = $userStmt->get_result()->fetch_assoc();
if (!$user) die("User not found");

/* ---------- FETCH COURSE ---------- */
$courseStmt = $conn->prepare("SELECT title FROM courses WHERE id=?");
$courseStmt->bind_param("i", $course_id);
$courseStmt->execute();
$course = $courseStmt->get_result()->fetch_assoc();
if (!$course) die("Course not found");

/* ---------- CHECK CERTIFICATE ---------- */
$certStmt = $conn->prepare(
    "SELECT image_path, image_type, certificate_code 
     FROM certificates 
     WHERE user_id=? AND course_id=?"
);
$certStmt->bind_param("ii", $user_id, $course_id);
$certStmt->execute();
$existingCert = $certStmt->get_result()->fetch_assoc();

/* Track if certificate already existed */
$alreadyIssued = $existingCert ? true : false;

/* ---------- GENERATE CERTIFICATE ---------- */
if (!$existingCert) {

    $templatePath = __DIR__ . "/template.jpeg";
    $fontPath     = __DIR__ . "/Roboto-VariableFont_wdth,wght.ttf";
    $certDir      = __DIR__ . "/certificates";

    if (!is_dir($certDir)) {
        mkdir($certDir, 0755, true);
    }

    /* Generate UNIQUE CERTIFICATE CODE */
    $certificateCode = 'NO-CODE-' . date('Y') . '-' . strtoupper(bin2hex(random_bytes(4)));

    $info  = getimagesize($templatePath);
    $image = ($info[2] === IMAGETYPE_PNG)
        ? imagecreatefrompng($templatePath)
        : imagecreatefromjpeg($templatePath);

    $black = imagecolorallocate($image, 0, 0, 0);
    $blue  = imagecolorallocate($image, 28, 64, 150);
    $gray  = imagecolorallocate($image, 120, 120, 120);

    $studentName = strtoupper($user['fullname']);
    $courseTitle = $course['title'];

    function centerX($img, $size, $font, $text) {
        $box = imagettfbbox($size, 0, $font, $text);
        return (int) round((imagesx($img) - ($box[2] - $box[0])) / 2);
    }

    /* Student Name */
    imagettftext(
        $image, 30, 0,
        centerX($image, 30, $fontPath, $studentName),
        520, $black, $fontPath, $studentName
    );

    /* Course Title */
    imagettftext(
        $image, 30, 0,
        centerX($image, 30, $fontPath, $courseTitle),
        650, $blue, $fontPath, $courseTitle
    );

    /* Certificate Code (BOTTOM LEFT) */
    imagettftext(
        $image, 14, 0,
        80,
        imagesy($image) - 20,
        $gray,
        $fontPath,
        "Certificate ID: $certificateCode"
    );

    $filename = "certificate_{$user_id}_{$course_id}_" . time() . ".png";
    imagepng($image, "$certDir/$filename");
    imagedestroy($image);

    $dbPath   = "certificates/$filename";
    $issuedAt = date("Y-m-d H:i:s");

    $insert = $conn->prepare(
        "INSERT INTO certificates 
        (user_id, course_id, certificate_code, image_path, issued_at, image_type)
        VALUES (?, ?, ?, ?, ?, 'image/png')"
    );
    $insert->bind_param(
        "iisss",
        $user_id,
        $course_id,
        $certificateCode,
        $dbPath,
        $issuedAt
    );
    $insert->execute();

    $existingCert = [
        'image_path'       => $dbPath,
        'image_type'       => 'image/png',
        'certificate_code' => $certificateCode
    ];
}

/* ---------- DOWNLOAD ---------- */
if (isset($_POST['download']) && !$alreadyIssued) {
    $fullPath = __DIR__ . "/" . $existingCert['image_path'];

    header("Content-Type: " . $existingCert['image_type']);
    header("Content-Disposition: attachment; filename=Certificate-{$user['fullname']}.png");
    header("Content-Length: " . filesize($fullPath));
    readfile($fullPath);
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Certificate Preview</title>

<style>
body{
    margin:0;
    font-family:Arial, sans-serif;
    background:#f4f6f9;
    display:flex;
    flex-direction:column;
    min-height:100vh;
}
.container{
    flex:1;
    text-align:center;
    padding:20px;
}
img{
    width:100%;
    max-width:900px;
    border-radius:12px;
    border:4px solid #ddd;
    box-shadow:0 10px 25px rgba(0,0,0,.1);
}
button{
    margin-top:20px;
    padding:14px 30px;
    font-size:16px;
    border:none;
    border-radius:10px;
    background:#0a3d91;
    color:#fff;
    cursor:pointer;
}
button:disabled{
    background:#999;
    cursor:not-allowed;
}
</style>
</head>

<body>

<div class="container">
    <h2 style="color:rgb(18,108,201);">Your Certificate</h2>

    <img src="<?= htmlspecialchars($existingCert['image_path']) ?>" alt="Certificate">

    <p style="color:#555;font-size:14px;">
        Certificate ID: <strong><?= htmlspecialchars($existingCert['certificate_code']) ?></strong>
    </p>

    <form method="post">
        <button type="submit" name="download" <?= $alreadyIssued ? 'disabled' : '' ?>>
            <?= $alreadyIssued ? 'Certificate Already Downloaded' : 'Download Certificate' ?>
        </button>
    </form>
</div><br><br><br><br><br><br>

<?php include "footer.php"; ?>

</body>
</html>
