<?php
include "db.php";
session_start();

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

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

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

    // Delete all certificates first to maintain referential integrity
    $deleteCertificatesQuery = "DELETE FROM certificates";
    $db->exec($deleteCertificatesQuery);

    // Delete all students
    $deleteStudentsQuery = "DELETE FROM students";
    $db->exec($deleteStudentsQuery);

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

    header("Location: all-students.php?success=All students and their certificates have been deleted successfully.");
    exit();

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