<?php
session_start();
include "dbconnect.php"; // Database connection

// Check if an ID is passed via the URL
if (isset($_GET['id'])) {
    $id = (int)$_GET['id'];

    // First, fetch the file path of the visa document for deletion
    $sql = "SELECT visa_upload FROM visa_management WHERE id = ?";
    $stmt = $con->prepare($sql);
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    // Check if record exists
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $visa_upload = $row['visa_upload'];

        // Delete the file if it exists
        if (!empty($visa_upload) && file_exists($visa_upload)) {
            unlink($visa_upload); // Delete the file
        }

        // Now, delete the record from the database
        $delete_sql = "DELETE FROM visa_management WHERE id = ?";
        $delete_stmt = $con->prepare($delete_sql);
        $delete_stmt->bind_param("i", $id);

        if ($delete_stmt->execute()) {
            // Record deleted successfully
            $_SESSION['message'] = "Record and associated document deleted successfully.";
            $_SESSION['message_type'] = "success";
        } else {
            // Error occurred while deleting
            $_SESSION['message'] = "Error occurred while deleting the record.";
            $_SESSION['message_type'] = "danger";
        }
    } else {
        $_SESSION['message'] = "Record not found.";
        $_SESSION['message_type'] = "danger";
    }

    // Redirect to the visa management page
    header("Location: visalist.php");
    exit;
} else {
    // If no ID is provided, redirect to the visa list page
    $_SESSION['message'] = "Invalid request. No ID specified.";
    $_SESSION['message_type'] = "danger";
    header("Location: visalist.php");
    exit;
}
?>
