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

// Check if user is logged in and has admin role
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] != 1) {
    // Redirect non-admin users
    header('Location: index.php');
    exit();
}

// Check if the deposit ID is provided
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    $_SESSION['error_message'] = "Invalid container deposit ID";
    header('Location: container_depo_list.php');
    exit();
}

$depositId = (int)$_GET['id'];
$userId = $_SESSION['user_id'];
$userIp = $_SERVER['REMOTE_ADDR'];

// Begin transaction to ensure both operations (delete and log) succeed or fail together
$conn->begin_transaction();

try {
    // First, get the deposit details for logging
    $getDepositQuery = "SELECT shipping_line, bl, container FROM container_deposit WHERE id = ?";
    $stmt = $conn->prepare($getDepositQuery);
    $stmt->bind_param("i", $depositId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        throw new Exception("Container deposit record not found");
    }
    
    $depositData = $result->fetch_assoc();
    $depositDetails = "Deleted container deposit record with ID: $depositId. " .
                     "Shipping Line: {$depositData['shipping_line']}, " .
                     "BL: {$depositData['bl']}, " .
                     "Container: {$depositData['container']}";
    
    // Delete the container deposit record
    $deleteQuery = "DELETE FROM container_deposit WHERE id = ?";
    $stmt = $conn->prepare($deleteQuery);
    $stmt->bind_param("i", $depositId);
    $deleteResult = $stmt->execute();
    
    if (!$deleteResult) {
        throw new Exception("Failed to delete container deposit record");
    }
    
    // Log the deletion action in admin_logs
    $logQuery = "INSERT INTO admin_logs (user_id, action, details, ip_address) VALUES (?, ?, ?, ?)";
    $stmt = $conn->prepare($logQuery);
    $action = "container_deposit_delete";
    $stmt->bind_param("isss", $userId, $action, $depositDetails, $userIp);
    $logResult = $stmt->execute();
    
    if (!$logResult) {
        throw new Exception("Failed to log the deletion action");
    }
    
    // Commit the transaction if both operations succeeded
    $conn->commit();
    
    // Set success message and redirect
    $_SESSION['success_message'] = "Container deposit record deleted successfully";
    header('Location: container_depo_list.php');
    exit();
    
} catch (Exception $e) {
    // Rollback the transaction if any operation failed
    $conn->rollback();
    
    // Set error message and redirect
    $_SESSION['error_message'] = "Error: " . $e->getMessage();
    header('Location: container_depo_list.php');
    exit();
}
?>