<?php
// Database connection
require_once ('../models/db_connection.php'); // adjust to your actual DB connection file

if (isset($_GET['id'])) {
    $studentId = $_GET['id']; // Get the student ID

    // Step 1: Get the filename associated with the student
    $getFileQuery = "SELECT * FROM students WHERE student_id = '$studentId'";
    $result = mysqli_query($conn, $getFileQuery);
    $studentData = mysqli_fetch_assoc($result);
    $filename = $studentData['filename'];

    // Step 2: Check if the file exists in the 'uploads' folder
    $filePath = 'uploads/' . $filename; // Path to the uploads folder
    if (file_exists($filePath)) {
        // Step 3: If the file exists, delete it
        unlink($filePath);
    }

    // Step 4: Delete the student from the database
    $deleteStudentQuery = "DELETE FROM students WHERE student_id = '$studentId'";
    if (mysqli_query($conn, $deleteStudentQuery)) {
        $delcos = mysqli_query($conn, "DELETE FROM student_course WHERE s_id ='$studentData[en_id]'");
        if($delcos){
        echo "<script>
                alert('Student and associated file deleted successfully');
                window.location.href = '../student/view_students.php'; // Redirect after deletion
              </script>";
        }
    } else {
        echo "<script>alert('Error deleting student: " . mysqli_error($conn) . "');</script>";
    }
} else {
    echo "<script>alert('Invalid student ID');</script>";
}
