<?php
session_start();
include 'layouts/dbconn.php';

// Check if the user is not logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check if the user has delete permission
$user_id = $_SESSION['user_id'];
$role_query = "SELECT role_id FROM users WHERE user_id = ?";
$role_stmt = $conn->prepare($role_query);
$role_stmt->bind_param('i', $user_id);
$role_stmt->execute();
$role_result = $role_stmt->get_result();

if ($role_result->num_rows === 0) {
    $_SESSION['error_message'] = "User not found";
    header('Location: file_list.php');
    exit();
}

$role_id = $role_result->fetch_assoc()['role_id'];

// Only allow admin (role_id = 1) to delete files
if ($role_id != 1) {
    $_SESSION['error_message'] = "You don't have permission to delete files";
    header('Location: file_list.php');
    exit();
}

// Check if file_id is provided
if (!isset($_POST['file_id']) || empty($_POST['file_id'])) {
    $_SESSION['error_message'] = "No file ID provided";
    header('Location: file_list.php');
    exit();
}

$file_id = intval($_POST['file_id']);

// Get file details to log deletion
$file_query = "SELECT file_number FROM files WHERE id = ?";
$file_stmt = $conn->prepare($file_query);
$file_stmt->bind_param('i', $file_id);
$file_stmt->execute();
$file_result = $file_stmt->get_result();

if ($file_result->num_rows === 0) {
    $_SESSION['error_message'] = "File not found";
    header('Location: file_list.php');
    exit();
}

$file_number = $file_result->fetch_assoc()['file_number'];

try {
    // Start transaction
    $conn->begin_transaction();
    
    // Get user name for logging
    $user_query = "SELECT full_name FROM users WHERE user_id = ?";
    $user_stmt = $conn->prepare($user_query);
    $user_stmt->bind_param('i', $user_id);
    $user_stmt->execute();
    $user_result = $user_stmt->get_result();
    $deleted_by = $user_result->fetch_assoc()['full_name'];
    
    // Log the deletion in deleted_records table
    $log_query = "INSERT INTO deleted_records (file_number, date_deleted, deleted_by) VALUES (?, NOW(), ?)";
    $log_stmt = $conn->prepare($log_query);
    $log_stmt->bind_param('ss', $file_number, $deleted_by);
    
    if (!$log_stmt->execute()) {
        throw new Exception("Failed to log deletion: " . $log_stmt->error);
    }
    
    // Delete container details
    $container_query = "DELETE FROM container_details WHERE file_number = ?";
    $container_stmt = $conn->prepare($container_query);
    $container_stmt->bind_param('s', $file_number);
    
    if (!$container_stmt->execute()) {
        throw new Exception("Failed to delete container details: " . $container_stmt->error);
    }
    
    // Delete charges
    $charges_query = "DELETE FROM charges WHERE file_number = ?";
    $charges_stmt = $conn->prepare($charges_query);
    $charges_stmt->bind_param('s', $file_number);
    
    if (!$charges_stmt->execute()) {
        throw new Exception("Failed to delete charges: " . $charges_stmt->error);
    }
    
    // Delete notifications
    $notif_query = "DELETE FROM notifications WHERE file_number = ?";
    $notif_stmt = $conn->prepare($notif_query);
    $notif_stmt->bind_param('s', $file_number);
    
    if (!$notif_stmt->execute()) {
        throw new Exception("Failed to delete notifications: " . $notif_stmt->error);
    }
    
    // Delete pre_proforma entries
    $preproforma_query = "DELETE FROM pre_proforma WHERE file_number = ?";
    $preproforma_stmt = $conn->prepare($preproforma_query);
    $preproforma_stmt->bind_param('s', $file_number);
    
    if (!$preproforma_stmt->execute()) {
        throw new Exception("Failed to delete pre_proforma entries: " . $preproforma_stmt->error);
    }
    
    // Delete shipping_line entries
    $shipping_query = "DELETE FROM shipping_line WHERE file_no = ?";
    $shipping_stmt = $conn->prepare($shipping_query);
    $shipping_stmt->bind_param('s', $file_number);
    
    if (!$shipping_stmt->execute()) {
        throw new Exception("Failed to delete shipping_line entries: " . $shipping_stmt->error);
    }
    
    // Delete truck_details entries
    $truck_query = "DELETE FROM truck_details WHERE file_no = ?";
    $truck_stmt = $conn->prepare($truck_query);
    $truck_stmt->bind_param('s', $file_number);
    
    if (!$truck_stmt->execute()) {
        throw new Exception("Failed to delete truck_details entries: " . $truck_stmt->error);
    }
    
    // Delete delivery_returns entries
    $delivery_query = "DELETE FROM delivery_returns WHERE file_number = ?";
    $delivery_stmt = $conn->prepare($delivery_query);
    $delivery_stmt->bind_param('s', $file_number);
    
    if (!$delivery_stmt->execute()) {
        throw new Exception("Failed to delete delivery_returns entries: " . $delivery_stmt->error);
    }
    
    // Finally, delete the main file
    $file_delete_query = "DELETE FROM files WHERE id = ?";
    $file_delete_stmt = $conn->prepare($file_delete_query);
    $file_delete_stmt->bind_param('i', $file_id);
    
    if (!$file_delete_stmt->execute()) {
        throw new Exception("Failed to delete file: " . $file_delete_stmt->error);
    }
    
    // Commit transaction
    $conn->commit();
    
    $_SESSION['success_message'] = "File $file_number has been successfully deleted";
    header('Location: file_list.php');
    exit();
    
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    
    // Log the error
    error_log("Error deleting file $file_number: " . $e->getMessage());
    
    $_SESSION['error_message'] = "Error deleting file: " . $e->getMessage();
    header('Location: file_list.php');
    exit();
}
?>