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

header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

if (!isset($_SESSION['user_id'])) {
    $_SESSION['swal_error'] = "You must be logged in to perform this action";
    header('Location: login.php');
    exit();
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    try {
        // Start transaction
        $conn->begin_transaction();
        
        $file_no = $_POST["file_no"];
        $transporter_name = isset($_POST["transporter_name"]) ? $_POST["transporter_name"][0] : '';
        $user_id = $_SESSION['user_id'];

        // Get file ID from file_number
        $file_id_query = "SELECT id FROM files WHERE file_number = ?";
        $file_id_stmt = $conn->prepare($file_id_query);
        $file_id_stmt->bind_param('s', $file_no);
        $file_id_stmt->execute();
        $file_id_result = $file_id_stmt->get_result();
        if ($file_id_result->num_rows === 0) {
            throw new Exception("File not found");
        }
        $file_id_row = $file_id_result->fetch_assoc();
        $file_id = $file_id_row['id'];

        // Truck details arrays
        $container_codes = $_POST["containers"];
        $truck_trailers = $_POST["truck_trailer_no"];
        $driver_names = $_POST["driver_name"];
        $driver_numbers = $_POST["driver_phone_number"];
        $driver_licenses = $_POST["driver_license"];

        // Dates arrays
        $load_dates = $_POST["load_date"];
        $port_dates = $_POST["port_date"];
        $border_dates = $_POST["border_date"];
        $border_crossing_dates = $_POST["border_crossing_date"];
        $dest_dates = $_POST["dest_date"];
        $offload_dates = $_POST["offload_date"];
        $empty_return_dates = $_POST["empty_return_date"];

        // Delete existing records for this file
        $delete_sql = "DELETE FROM shipment_data WHERE file_no = ?";
        $delete_stmt = $conn->prepare($delete_sql);
        $delete_stmt->bind_param("s", $file_no);
        $delete_stmt->execute();

        $delete_truck_sql = "DELETE FROM truck_details WHERE file_no = ?";
        $delete_truck_stmt = $conn->prepare($delete_truck_sql);
        $delete_truck_stmt->bind_param("s", $file_no);
        $delete_truck_stmt->execute();

        // Insert into shipment_data table
        $shipment_sql = "INSERT INTO shipment_data (file_no, transporter_name, load_date, port_date, 
                         border_date, border_crossing_date, dest_date, offload_date, empty_return_date, 
                         driver_name, driver_phone_number, driver_license)
                         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $shipment_stmt = $conn->prepare($shipment_sql);
        
        if ($shipment_stmt === false) {
            throw new Exception("Error preparing statement for shipment_data: " . $conn->error);
        }

        // Format dates
        $load_date = !empty($load_dates[0]) ? date('Y-m-d', strtotime($load_dates[0])) : null;
        $port_date = !empty($port_dates[0]) ? date('Y-m-d', strtotime($port_dates[0])) : null;
        $border_date = !empty($border_dates[0]) ? date('Y-m-d', strtotime($border_dates[0])) : null;
        $border_crossing_date = !empty($border_crossing_dates[0]) ? date('Y-m-d', strtotime($border_crossing_dates[0])) : null;
        $dest_date = !empty($dest_dates[0]) ? date('Y-m-d', strtotime($dest_dates[0])) : null;
        $offload_date = !empty($offload_dates[0]) ? date('Y-m-d', strtotime($offload_dates[0])) : null;
        $empty_return_date = !empty($empty_return_dates[0]) ? date('Y-m-d', strtotime($empty_return_dates[0])) : null;
        
        $shipment_stmt->bind_param("ssssssssssss", 
            $file_no, 
            $transporter_name, 
            $load_date, 
            $port_date, 
            $border_date, 
            $border_crossing_date, 
            $dest_date, 
            $offload_date, 
            $empty_return_date, 
            $driver_names[0], 
            $driver_numbers[0], 
            $driver_licenses[0]
        );

        if (!$shipment_stmt->execute()) {
            throw new Exception("Error inserting into shipment_data: " . $shipment_stmt->error);
        }

        // Insert into truck_details table for each truck
        $truck_sql = "INSERT INTO truck_details (file_no, container_code, transporter_name, load_date, 
                     truck_trailer_no, driver_name, driver_phone_number, driver_license, port_date, 
                     border_date, dest_date, offload_date, empty_return_date, border_crossing_date, user_id)
                     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $truck_stmt = $conn->prepare($truck_sql);

        if ($truck_stmt === false) {
            throw new Exception("Error preparing statement for truck_details: " . $conn->error);
        }

        for ($i = 0; $i < count($container_codes); $i++) {
            // Skip if container is empty
            if (empty($container_codes[$i])) continue;
            
            // Format dates
            $load_date = !empty($load_dates[$i]) ? date('Y-m-d', strtotime($load_dates[$i])) : null;
            $port_date = !empty($port_dates[$i]) ? date('Y-m-d', strtotime($port_dates[$i])) : null;
            $border_date = !empty($border_dates[$i]) ? date('Y-m-d', strtotime($border_dates[$i])) : null;
            $border_crossing_date = !empty($border_crossing_dates[$i]) ? date('Y-m-d', strtotime($border_crossing_dates[$i])) : null;
            $dest_date = !empty($dest_dates[$i]) ? date('Y-m-d', strtotime($dest_dates[$i])) : null;
            $offload_date = !empty($offload_dates[$i]) ? date('Y-m-d', strtotime($offload_dates[$i])) : null;
            $empty_return_date = !empty($empty_return_dates[$i]) ? date('Y-m-d', strtotime($empty_return_dates[$i])) : null;

            $truck_stmt->bind_param("ssssssssssssssi", 
                $file_no, 
                $container_codes[$i], 
                $transporter_name, 
                $load_date, 
                $truck_trailers[$i], 
                $driver_names[$i], 
                $driver_numbers[$i], 
                $driver_licenses[$i], 
                $port_date, 
                $border_date, 
                $dest_date, 
                $offload_date, 
                $empty_return_date, 
                $border_crossing_date, 
                $user_id
            );

            if (!$truck_stmt->execute()) {
                throw new Exception("Error inserting into truck_details: " . $truck_stmt->error);
            }
            
            // Also update the container details table
            $update_container_query = "UPDATE container_details SET 
                transporter_name = ?,
                driver_name = ?,
                driver_phone_number = ?,
                driver_license = ?,
                load_date = ?,
                truck_at_border_date = ?,
                border_crossing_date = ?,
                delivery_date = ?,
                empty_return_date = ?
                WHERE file_number = ? AND container_code = ?";
                
            $update_container_stmt = $conn->prepare($update_container_query);
            $update_container_stmt->bind_param(
                'sssssssssss',
                $transporter_name,
                $driver_names[$i],
                $driver_numbers[$i],
                $driver_licenses[$i],
                $load_date,
                $border_date,
                $border_crossing_date,
                $dest_date,
                $empty_return_date,
                $file_no,
                $container_codes[$i]
            );
            
            $update_container_stmt->execute();
        }

        // Update the corresponding record in the files table
        $update_sql = "UPDATE files
                     SET transporter = ?,
                         truck_trailer_no = ?,
                         driver_name = ?,
                         driver_phone_number = ?,
                         driver_license = ?,
                         load_date = ?,
                         truck_exit_date = ?,
                         truck_at_border_date = ?,
                         border_crossing_date = ?,
                         delivery_date = ?,
                         empty_return_date = ?
                     WHERE file_number = ?";
        
        $update_stmt = $conn->prepare($update_sql);
        
        if ($update_stmt === false) {
            throw new Exception("Error preparing statement for files update: " . $conn->error);
        }
        
        $update_stmt->bind_param("ssssssssssss", 
            $transporter_name, 
            $truck_trailers[0], 
            $driver_names[0], 
            $driver_numbers[0], 
            $driver_licenses[0], 
            $load_date, 
            $port_date,
            $border_date, 
            $border_crossing_date, 
            $dest_date, 
            $empty_return_date, 
            $file_no
        );
        
        if (!$update_stmt->execute()) {
            throw new Exception("Error updating files table: " . $update_stmt->error);
        }
        
        // Create a notification
        $notif_message = "Truck assignment updated for file number {$file_no}";
        $notif_type = 2; // Update notification type
        
        $notif_sql = "INSERT INTO notifications (file_id, file_number, notif_message, notif_message_id) 
                      VALUES (?, ?, ?, ?)";
        $notif_stmt = $conn->prepare($notif_sql);
        $notif_stmt->bind_param("issi", $file_id, $file_no, $notif_message, $notif_type);
        
        // Don't fail the transaction if notification creation fails
        try {
            $notif_stmt->execute();
        } catch (Exception $e) {
            // Log the error but continue
            error_log("Error creating notification: " . $e->getMessage());
        }
        
        // Commit the transaction
        $conn->commit();
        
        // Set success message
        $_SESSION['swal_success'] = "Truck assignment successfully updated for file: $file_no";
        
        // Redirect to the appropriate page
        header("Location: truck_list.php");
        exit();
        
    } catch (Exception $e) {
        // Rollback transaction if an error occurred
        $conn->rollback();
        
        // Log the error
        error_log("Error in truck assignment: " . $e->getMessage());
        
        // Set error message
        $_SESSION['swal_error'] = "Error: " . $e->getMessage();
        
        // Redirect back to the form
        header("Location: assign_trucks.php?file_number=" . urlencode($file_no));
        exit();
    } finally {
        // Close all statements
        if (isset($file_id_stmt)) $file_id_stmt->close();
        if (isset($delete_stmt)) $delete_stmt->close();
        if (isset($delete_truck_stmt)) $delete_truck_stmt->close();
        if (isset($shipment_stmt)) $shipment_stmt->close();
        if (isset($truck_stmt)) $truck_stmt->close();
        if (isset($update_container_stmt)) $update_container_stmt->close();
        if (isset($update_stmt)) $update_stmt->close();
        if (isset($notif_stmt)) $notif_stmt->close();
    }
} else {
    // Not a POST request
    $_SESSION['swal_error'] = "Invalid request method";
    header("Location: truck_list.php");
    exit();
}
?>