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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: index.php');
    exit();
}

// Get user ID for tracking
$user_id = $_SESSION['user_id'];

// Collect main shipment data
$file_number = $_POST['file_number'];
$customer = isset($_POST['customer']) ? intval($_POST['customer']) : null;
$consignee_name = $_POST['consignee_name'];
$trans_type = $_POST['trans_type'] ?? null;
$destination = $_POST['destination'];
$currency = $_POST['currency'] ?? '$';
$obl_no = $_POST['obl_no'] ?? null;
$eta = !empty($_POST['eta']) ? date('Y-m-d', strtotime($_POST['eta'])) : null;
$initial_eta = !empty($_POST['initial_eta']) ? date('Y-m-d', strtotime($_POST['initial_eta'])) : null;
$pre_alert_received_date = !empty($_POST['pre_alert_received_date']) ? date('Y-m-d', strtotime($_POST['pre_alert_received_date'])) : null;
$discharge_date = !empty($_POST['discharge_date']) ? date('Y-m-d', strtotime($_POST['discharge_date'])) : null;
$vno = $_POST['vno'] ?? null;
$port = $_POST['port'] ?? null;
$c_type = $_POST['c_type'];
$free_detention = $_POST['free_detention'] ?? null;
$remarks = $_POST['remarks'] ?? null;

// After collecting main shipment data, before the try block
if ($c_type === 'Bulk Cargo' || $c_type === 'Loose Cargo') {
    $total_trucks_required = isset($_POST['total_trucks_required']) ? intval($_POST['total_trucks_required']) : null;
    $trucks_to_assign = isset($_POST['trucks_to_assign']) ? intval($_POST['trucks_to_assign']) : null;
    $trucks_remaining = $total_trucks_required - $trucks_to_assign;

    // Insert initial truck records
    if ($c_type === 'Bulk Cargo') {
        $bulk_sql = "INSERT INTO bulk_cargo_details (
            file_number, 
            truck_reg,
            transporter,
            driver_name,
            tonnage,
            assignment_batch,
            created_by
        ) VALUES (?, 'Pending', NULL, NULL, 0, 1, ?)";
        
        $bulk_stmt = $conn->prepare($bulk_sql);
        
        for ($i = 0; $i < $trucks_to_assign; $i++) {
            $bulk_stmt->bind_param('si', $file_number, $user_id);
            if (!$bulk_stmt->execute()) {
                throw new Exception("Failed to create bulk cargo truck records");
            }
        }
    } else {
        $loose_sql = "INSERT INTO loose_cargo_details (
            file_number,
            truck_reg,
            transporter,
            driver_name,
            cbm,
            assignment_batch,
            created_by
        ) VALUES (?, 'Pending', NULL, NULL, 0, 1, ?)";
        
        $loose_stmt = $conn->prepare($loose_sql);
        
        for ($i = 0; $i < $trucks_to_assign; $i++) {
            $loose_stmt->bind_param('si', $file_number, $user_id);
            if (!$loose_stmt->execute()) {
                throw new Exception("Failed to create loose cargo truck records");
            }
        }
    }
}

// This is a transit shipment (local/transit = 2)
$local_transit = 2;

try {
    // Start transaction
    $conn->begin_transaction();
    
    // Insert main shipment record
    $sql = "INSERT INTO files (
                file_number, customer, trans_type, consignee_name, 
                destination, currency, obl_no, eta, initial_eta, 
                pre_alert_received_date, discharge_date, vno, port,
                remarks, `local/transit`, free_detention,
                total_trucks_required, trucks_assigned, trucks_remaining
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param(
        'sissssssssssssiiiii',
        $file_number, $customer, $trans_type, $consignee_name,
        $destination, $currency, $obl_no, $eta, $initial_eta,
        $pre_alert_received_date, $discharge_date, $vno, $port,
        $remarks, $local_transit, $free_detention,
        $total_trucks_required, $trucks_to_assign, $trucks_remaining
    );
    
    if (!$stmt->execute()) {
        throw new Exception("Error creating shipment: " . $stmt->error);
    }
    
    // Get the inserted file ID
    $file_id = $conn->insert_id;
    
    // Handle container details if cargo type is Container
    if ($c_type === 'Container') {
        $container_codes = $_POST['container_code'] ?? [];
        $container_sizes = $_POST['container_size'] ?? [];
        $transporters = $_POST['transporter'] ?? [];
        $driver_names = $_POST['driver_name'] ?? [];
        $driver_phones = $_POST['driver_phone_number'] ?? [];
        $driver_licenses = $_POST['driver_license'] ?? [];
        
        // Other container fields
        $delivery_order_apply_dates = $_POST['delivery_order_apply_date'] ?? [];
        $delivery_order_received_dates = $_POST['delivery_order_received_date'] ?? [];
        $obr_sct_received_dates = $_POST['obr_sct_received_date'] ?? [];
        $obr_ti_validation_dates = $_POST['obr_ti_validation_date'] ?? [];
        $t1_c2_approval_dates = $_POST['t1_c2_approval_date'] ?? [];
        $port_charges_paid_dates = $_POST['port_charges_paid_date'] ?? [];
        $whafage_paid_dates = $_POST['whafage_paid_date'] ?? [];
        $loading_permit_apply_dates = $_POST['loading_permit_apply_date'] ?? [];
        $truck_exit_dates = $_POST['truck_exit_date'] ?? [];
        $truck_at_border_dates = $_POST['truck_at_border_date'] ?? [];
        $border_crossing_dates = $_POST['border_crossing_date'] ?? [];
        $delivery_dates = $_POST['delivery_date'] ?? [];
        $empty_return_dates = $_POST['empty_return_date'] ?? [];
        $container_remarks = $_POST['remarks'] ?? [];
        
        // Count of containers
        $container_count = count($container_codes);
        
        // Prepare statement for container details
        $container_sql = "INSERT INTO container_details (
                            file_number, container_code, container_size, transporter_name,
                            driver_name, driver_phone_number, driver_license,
                            delivery_order_apply_date, delivery_order_received_date,
                            obr_sct_received_date, obr_ti_validation_date,
                            t1_c2_approval_date, port_charges_paid_date,
                            whafage_paid_date, loading_permit_apply_date,
                            truck_exit_date, truck_at_border_date,
                            border_crossing_date, delivery_date,
                            empty_return_date, remarks
                          ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        $container_stmt = $conn->prepare($container_sql);
        
        // Insert each container
        for ($i = 0; $i < $container_count; $i++) {
            // Skip empty container entries
            if (empty($container_codes[$i])) continue;
            
            // Format dates or set to null if empty
            $delivery_order_apply_date = !empty($delivery_order_apply_dates[$i]) ? 
                date('Y-m-d', strtotime($delivery_order_apply_dates[$i])) : null;
                
            $delivery_order_received_date = !empty($delivery_order_received_dates[$i]) ? 
                date('Y-m-d', strtotime($delivery_order_received_dates[$i])) : null;
                
            $obr_sct_received_date = !empty($obr_sct_received_dates[$i]) ? 
                date('Y-m-d', strtotime($obr_sct_received_dates[$i])) : null;
                
            $obr_ti_validation_date = !empty($obr_ti_validation_dates[$i]) ? 
                date('Y-m-d', strtotime($obr_ti_validation_dates[$i])) : null;
                
            $t1_c2_approval_date = !empty($t1_c2_approval_dates[$i]) ? 
                date('Y-m-d', strtotime($t1_c2_approval_dates[$i])) : null;
                
            $port_charges_paid_date = !empty($port_charges_paid_dates[$i]) ? 
                date('Y-m-d', strtotime($port_charges_paid_dates[$i])) : null;
                
            $whafage_paid_date = !empty($whafage_paid_dates[$i]) ? 
                date('Y-m-d', strtotime($whafage_paid_dates[$i])) : null;
                
            $loading_permit_apply_date = !empty($loading_permit_apply_dates[$i]) ? 
                date('Y-m-d', strtotime($loading_permit_apply_dates[$i])) : null;
                
            $truck_exit_date = !empty($truck_exit_dates[$i]) ? 
                date('Y-m-d', strtotime($truck_exit_dates[$i])) : null;
                
            $truck_at_border_date = !empty($truck_at_border_dates[$i]) ? 
                date('Y-m-d', strtotime($truck_at_border_dates[$i])) : null;
                
            $border_crossing_date = !empty($border_crossing_dates[$i]) ? 
                date('Y-m-d', strtotime($border_crossing_dates[$i])) : null;
                
            $delivery_date = !empty($delivery_dates[$i]) ? 
                date('Y-m-d', strtotime($delivery_dates[$i])) : null;
                
            $empty_return_date = !empty($empty_return_dates[$i]) ? 
                date('Y-m-d', strtotime($empty_return_dates[$i])) : null;
            
            // Get transporter name from ID
            $transporter_name = '';
            if (!empty($transporters[$i])) {
                $transporter_query = "SELECT name FROM transporter_info WHERE id = ?";
                $transporter_stmt = $conn->prepare($transporter_query);
                $transporter_stmt->bind_param('i', $transporters[$i]);
                $transporter_stmt->execute();
                $transporter_result = $transporter_stmt->get_result();
                if ($transporter_row = $transporter_result->fetch_assoc()) {
                    $transporter_name = $transporter_row['name'];
                }
                $transporter_stmt->close();
            }
            
            $container_stmt->bind_param(
                'sssssssssssssssssssss',
                $file_number,
                $container_codes[$i],
                $container_sizes[$i],
                $transporter_name,
                $driver_names[$i],
                $driver_phones[$i],
                $driver_licenses[$i],
                $delivery_order_apply_date,
                $delivery_order_received_date,
                $obr_sct_received_date,
                $obr_ti_validation_date,
                $t1_c2_approval_date,
                $port_charges_paid_date,
                $whafage_paid_date,
                $loading_permit_apply_date,
                $truck_exit_date,
                $truck_at_border_date,
                $border_crossing_date,
                $delivery_date,
                $empty_return_date,
                $container_remarks[$i]
            );
            
            if (!$container_stmt->execute()) {
                throw new Exception("Error saving container details: " . $container_stmt->error);
            }
        }
        
        $container_stmt->close();
    }
    
    // Create notification
    $notif_message = "New transit file with file number {$file_number} has been created.";
    $sql_notif = "INSERT INTO notifications (file_id, file_number, notif_message, notif_message_id) 
                  VALUES (?, ?, ?, 1)";
    
    $notif_stmt = $conn->prepare($sql_notif);
    $notif_stmt->bind_param('iss', $file_id, $file_number, $notif_message);
    
    if (!$notif_stmt->execute()) {
        // Log notification error but don't fail the transaction
        error_log("Failed to create notification for file: $file_number");
    }
    
    $notif_stmt->close();
    
    // Insert charge record (empty placeholder for now)
    $charge_sql = "INSERT INTO charges (file_number) VALUES (?)";
    $charge_stmt = $conn->prepare($charge_sql);
    $charge_stmt->bind_param('s', $file_number);
    
    if (!$charge_stmt->execute()) {
        // Log error but don't fail transaction
        error_log("Failed to create charge record for file: $file_number");
    }
    
    $charge_stmt->close();
    
    // Commit transaction
    $conn->commit();
    
    // Store the file number in session for use on the next page
    $_SESSION['created_file_number'] = $file_number;
    $_SESSION['created_file_bl'] = $obl_no; // Pass the BL number to the next screen
    
    // Set the success message
    $_SESSION['success_message'] = "Shipment file created successfully. File Number: $file_number";
    
    // Redirect to the container deposit confirmation page
    header('Location: confirm_container_deposit.php');
    exit();
    
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    
    // Log the error
    error_log("Error saving transit file: " . $e->getMessage());
    
    // Show error message
    $_SESSION['error_message'] = "Error: " . $e->getMessage();
    header('Location: transit_shipment.php');
    exit();
}
?>