<?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=vdacocmz_schdb_coll", "vdacocmz_mendohz", "@Dei22*#");

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

$csv_no = $_GET['csv_no'];

// Check if the records exist
$check_query = "SELECT * FROM tbl_student_results WHERE csv_no = ?";
$stmt = $conn->prepare($check_query);
$stmt->execute([$csv_no]);
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($records)) {
    // Records not found, redirect to the previous page
    header("Location: uploaded_class_results.php");
    exit();
}

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

// Check if the deletion was successful
if ($stmt->rowCount() > 0) {
    $success_message = "Records with CSV Number: $csv_no successfully deleted.";
    echo '<script type="text/javascript">
        alert("' . $success_message . '");
        window.location.href = document.referrer;
        </script>';
} else {
    $error_message = "Error deleting records.";
    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 Class Results</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>
