<?php
include "db.php";

session_start();

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

if (!isset($_GET['certificate_id'])) {
    header("Location: all-certificates.php?error=Certificate ID missing");
    exit();
}

$certificate_id = $_GET['certificate_id'];

try {
    $db = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Begin transaction
    $db->beginTransaction();

    // Get the student_id for the certificate to be deleted
    $query = "SELECT student_id FROM certificates WHERE certificate_id = :certificate_id";
    $stmt = $db->prepare($query);
    $stmt->bindParam(":certificate_id", $certificate_id);
    $stmt->execute();
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$result) {
        $db->rollBack();
        header("Location: all-certificates.php?error=Certificate not found");
        exit();
    }

    $student_id = $result['student_id'];

    // Delete the certificate
    $deleteQuery = "DELETE FROM certificates WHERE certificate_id = :certificate_id";
    $deleteStmt = $db->prepare($deleteQuery);
    $deleteStmt->bindParam(":certificate_id", $certificate_id);
    $deleteStmt->execute();

    // Update the student's isCertIssued flag to 0 to mark certificate as not issued
    $updateQuery = "UPDATE students SET isCertIssued = 0 WHERE student_id = :student_id";
    $updateStmt = $db->prepare($updateQuery);
    $updateStmt->bindParam(":student_id", $student_id);
    $updateStmt->execute();

    // Commit transaction
    $db->commit();

    header("Location: all-certificates.php?success=Certificate deleted successfully");
    exit();

} catch (PDOException $e) {
    if ($db->inTransaction()) {
        $db->rollBack();
    }
    header("Location: all-certificates.php?error=Error deleting certificate: " . urlencode($e->getMessage()));
    exit();
}
?>
