<?php
require_once('source/session.php');
require_once('source/error.php');
require_once('source/dbconfig.php');
require_once('source/function.php');

// Create a database connection 
$conn = new PDO("mysql:host=localhost;dbname=british_schdb_coll", "british_smt_user", "@British22*#");

// Ensure record_id is provided in the URL
if (!isset($_GET['record_id'])) {
    header("Location: edit_subject.php");
    exit();
}

$record_id = $_GET['record_id'];

// Check if the record exists
$check_query = "SELECT * FROM tbl_student_results WHERE id = ?";
$stmt = $conn->prepare($check_query);
$stmt->execute([$record_id]);
$record = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$record) {
    // Record not found, redirect to the search page
    header("Location: edit_subject.php");
    exit();
}

// Attempt to delete the record
$delete_query = "DELETE FROM tbl_student_results WHERE id = ?";
$stmt = $conn->prepare($delete_query);
$stmt->execute([$record_id]);

// Check if the deletion was successful
if ($stmt->rowCount() > 0) {
    $success_message = "Record successfully deleted.";
    echo '<script type="text/javascript">
        alert("' . $success_message . '");
        window.location.href = document.referrer;
        </script>';
} else {
    $error_message = "Error deleting record.";
    echo '<script type="text/javascript">
        alert("' . $error_message . '");
        window.location.href = document.referrer;
        </script>';
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <!-- Your head section goes here -->
</head>

<body class="fixed-nav sticky-footer bg-dark" id="page-top">
    <!-- Your navigation goes here -->

    <div class="content-wrapper">
        <div class="container-fluid">
            <!-- Breadcrumbs go here -->

            <div class="row">
                <div class="col-lg-12">
                    <center>
                        <h2>Delete Result</h2>
                    </center>

                    <div class="form-container">
                        <?php
                        if (isset($success_message)) {
                            echo "<p style='color: green;'>$success_message</p>";
                        } elseif (isset($error_message)) {
                            echo "<p style='color: red;'>$error_message</p>";
                        }
                        ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Your footer goes here -->

    <!-- Your scripts go here -->
</body>

</html>
