<?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 file ID or file number is provided
if (isset($_GET['file_id']) && !empty($_GET['file_id'])) {
    $file_id = intval($_GET['file_id']);
} elseif (isset($_GET['file_number']) && !empty($_GET['file_number'])) {
    $file_number = $_GET['file_number'];
    // 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_number);
    $file_id_stmt->execute();
    $file_id_result = $file_id_stmt->get_result();
    if ($file_id_result->num_rows === 0) {
        $_SESSION['error_message'] = "File not found";
        header('Location: file_list.php');
        exit();
    }
    $file_id_row = $file_id_result->fetch_assoc();
    $file_id = $file_id_row['id'];
} else {
    $_SESSION['error_message'] = "No file ID provided";
    header('Location: file_list.php');
    exit();
}

// Get file details
$query = "SELECT f.*, c.first_name as customer_name 
          FROM files f 
          LEFT JOIN customers c ON f.customer = c.customer_id 
          WHERE f.id = ?";

$stmt = $conn->prepare($query);
$stmt->bind_param('i', $file_id);
$stmt->execute();
$result = $stmt->get_result();

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

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

// Get container details
$container_query = "SELECT * FROM container_details WHERE file_number = ? ORDER BY id ASC";
$container_stmt = $conn->prepare($container_query);
$container_stmt->bind_param('s', $file_number);
$container_stmt->execute();
$container_result = $container_stmt->get_result();
$containers = [];

if ($container_result->num_rows > 0) {
    while ($row = $container_result->fetch_assoc()) {
        $containers[] = $row;
    }
}

// Get all transporters for dropdown
$transporters_query = "SELECT id, name FROM transporter_info WHERE status = 1 ORDER BY name";
$transporters_result = $conn->query($transporters_query);
$transporters = [];
if ($transporters_result->num_rows > 0) {
    while ($row = $transporters_result->fetch_assoc()) {
        $transporters[] = $row;
    }
}

// Check if shipment data already exists (for pre-filling the form)
$shipment_data_query = "SELECT * FROM shipment_data WHERE file_no = ? ORDER BY id ASC";
$shipment_data_stmt = $conn->prepare($shipment_data_query);
$shipment_data_stmt->bind_param('s', $file_number);
$shipment_data_stmt->execute();
$shipment_data_result = $shipment_data_stmt->get_result();
$existing_assignments = [];

if ($shipment_data_result->num_rows > 0) {
    while ($row = $shipment_data_result->fetch_assoc()) {
        $existing_assignments[] = $row;
    }
}

// Check for truck details
$truck_details_query = "SELECT * FROM truck_details WHERE file_no = ? ORDER BY id ASC";
$truck_details_stmt = $conn->prepare($truck_details_query);
$truck_details_stmt->bind_param('s', $file_number);
$truck_details_stmt->execute();
$truck_details_result = $truck_details_stmt->get_result();
$truck_details = [];

if ($truck_details_result->num_rows > 0) {
    while ($row = $truck_details_result->fetch_assoc()) {
        $truck_details[] = $row;
    }
}

// Format date helper function
function formatDate($date) {
    if (empty($date) || $date == '0000-00-00' || $date == '0000-00-00 00:00:00') {
        return '';
    }
    return date('Y-m-d', strtotime($date));
}
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Truck Assignment')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.12/dist/sweetalert2.min.css">
    <style>
        .truck-assignment-card {
            margin-bottom: 2rem;
            border-left: 3px solid #2ab57d;
        }
        .container-header {
            background-color: #f8f9fa;
            padding: 1rem;
            border-bottom: 1px solid #e9e9ef;
            font-weight: 600;
        }
        .select2-container {
            width: 100% !important;
        }
        .date-group {
            background-color: #f9f9f9;
            padding: 15px;
            border-radius: 5px;
            margin-top: 15px;
        }
        .date-group h6 {
            color: #495057;
            margin-bottom: 15px;
            border-bottom: 1px dashed #ccc;
            padding-bottom: 8px;
        }
    </style>
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Container Management', 'title' => 'Truck Assignment')); ?>

                    <?php if (isset($_SESSION['error_message'])): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?php echo $_SESSION['error_message']; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php unset($_SESSION['error_message']); ?>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-xl-12">
                            <div class="card">
                                <div class="card-header">
                                    <div class="d-flex align-items-center">
                                        <h4 class="card-title mb-0 flex-grow-1">
                                            Truck Assignment for #<?php echo htmlspecialchars($file['file_number']); ?>
                                        </h4>
                                        <div class="flex-shrink-0">
                                            <a href="view_file.php?id=<?php echo $file_id; ?>" class="btn btn-light btn-sm">
                                                <i class="ri-arrow-left-line align-bottom"></i> Back to File
                                            </a>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="row mb-4">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <span class="fw-medium text-muted">Customer:</span>
                                                <span class="ms-2"><?php echo htmlspecialchars($file['customer_name']); ?></span>
                                            </div>
                                            <div class="mb-3">
                                                <span class="fw-medium text-muted">Consignee:</span>
                                                <span class="ms-2"><?php echo htmlspecialchars($file['consignee_name']); ?></span>
                                            </div>
                                            <div class="mb-3">
                                                <span class="fw-medium text-muted">Destination:</span>
                                                <span class="ms-2"><?php echo htmlspecialchars($file['destination']); ?></span>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <span class="fw-medium text-muted">BL Number:</span>
                                                <span class="ms-2"><?php echo htmlspecialchars($file['obl_no']); ?></span>
                                            </div>
                                            <div class="mb-3">
                                                <span class="fw-medium text-muted">ETA:</span>
                                                <span class="ms-2"><?php echo formatDate($file['eta']); ?></span>
                                            </div>
                                            <div class="mb-3">
                                                <span class="fw-medium text-muted">Containers:</span>
                                                <span class="ms-2 badge bg-info"><?php echo count($containers); ?> container(s)</span>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Truck Assignment Form -->
                                    <form method="POST" action="save_truck_assignment.php" id="truckAssignmentForm">
                                        <input type="hidden" name="file_no" value="<?php echo htmlspecialchars($file_number); ?>">
                                        
                                        <?php if (empty($containers)): ?>
                                        <div class="alert alert-warning" role="alert">
                                            <i class="ri-alert-line me-2"></i>
                                            No containers found for this shipment. Please add containers before assigning trucks.
                                        </div>
                                        <?php else: ?>
                                        
                                        <?php foreach ($containers as $index => $container): 
                                            // Check if there's existing truck detail data for this container
                                            $truck_detail = null;
                                            foreach ($truck_details as $detail) {
                                                if ($detail['container_code'] == $container['container_code']) {
                                                    $truck_detail = $detail;
                                                    break;
                                                }
                                            }
                                            
                                            // If no specific truck detail, use existing assignment if available
                                            $assignment = null;
                                            if (!$truck_detail && !empty($existing_assignments)) {
                                                $assignment = $existing_assignments[0]; // Use first assignment
                                            }
                                        ?>
                                        <div class="card truck-assignment-card mb-4">
                                            <div class="card-header container-header">
                                                Container #<?php echo ($index + 1); ?>: 
                                                <?php echo htmlspecialchars($container['container_code']); ?>
                                                <span class="badge bg-secondary ms-2"><?php echo htmlspecialchars($container['container_size']); ?>ft</span>
                                            </div>
                                            <div class="card-body">
                                                <input type="hidden" name="containers[]" value="<?php echo htmlspecialchars($container['container_code']); ?>">
                                                
                                                <div class="row mb-3">
                                                    <div class="col-md-6">
                                                        <label class="form-label">Transporter</label>
                                                        <select class="form-select select2-transporter" name="transporter_name[]">
                                                            <option value="">Select Transporter</option>
                                                            <?php foreach ($transporters as $transporter): ?>
                                                            <option value="<?php echo htmlspecialchars($transporter['name']); ?>" 
                                                                <?php echo ($truck_detail && $truck_detail['transporter_name'] == $transporter['name']) || 
                                                                        (!$truck_detail && $container['transporter_name'] == $transporter['name']) ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars($transporter['name']); ?>
                                                            </option>
                                                            <?php endforeach; ?>
                                                        </select>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label class="form-label">Truck/Trailer Number</label>
                                                        <input type="text" class="form-control" name="truck_trailer_no[]" placeholder="e.g. T123ABC/T456DEF" 
                                                            value="<?php echo htmlspecialchars($truck_detail['truck_trailer_no'] ?? ''); ?>">
                                                    </div>
                                                </div>
                                                
                                                <div class="row mb-3">
                                                    <div class="col-md-4">
                                                        <label class="form-label">Driver Name</label>
                                                        <input type="text" class="form-control" name="driver_name[]" 
                                                            value="<?php echo htmlspecialchars($truck_detail['driver_name'] ?? $container['driver_name'] ?? ''); ?>">
                                                    </div>
                                                    <div class="col-md-4">
                                                        <label class="form-label">Driver Phone</label>
                                                        <input type="text" class="form-control" name="driver_phone_number[]" 
                                                            value="<?php echo htmlspecialchars($truck_detail['driver_phone_number'] ?? $container['driver_phone_number'] ?? ''); ?>">
                                                    </div>
                                                    <div class="col-md-4">
                                                        <label class="form-label">Driver License</label>
                                                        <input type="text" class="form-control" name="driver_license[]" 
                                                            value="<?php echo htmlspecialchars($truck_detail['driver_license'] ?? $container['driver_license'] ?? ''); ?>">
                                                    </div>
                                                </div>
                                                
                                                <div class="date-group">
                                                    <h6><i class="ri-time-line me-1"></i> Shipping Timeline</h6>
                                                    <div class="row mb-3">
                                                        <div class="col-md-3">
                                                            <label class="form-label">Load Date</label>
                                                            <input type="date" class="form-control" name="load_date[]" 
                                                                value="<?php echo formatDate($truck_detail['load_date'] ?? $container['load_date'] ?? ''); ?>">
                                                        </div>
                                                        <div class="col-md-3">
                                                            <label class="form-label">Port Date</label>
                                                            <input type="date" class="form-control" name="port_date[]" 
                                                                value="<?php echo formatDate($truck_detail['port_date'] ?? ''); ?>">
                                                        </div>
                                                        <div class="col-md-3">
                                                            <label class="form-label">Border Date</label>
                                                            <input type="date" class="form-control" name="border_date[]" 
                                                                value="<?php echo formatDate($truck_detail['border_date'] ?? $container['truck_at_border_date'] ?? ''); ?>">
                                                        </div>
                                                        <div class="col-md-3">
                                                            <label class="form-label">Border Crossing Date</label>
                                                            <input type="date" class="form-control" name="border_crossing_date[]" 
                                                                value="<?php echo formatDate($truck_detail['border_crossing_date'] ?? $container['border_crossing_date'] ?? ''); ?>">
                                                        </div>
                                                    </div>
                                                    
                                                    <div class="row mb-3">
                                                        <div class="col-md-4">
                                                            <label class="form-label">Destination Date</label>
                                                            <input type="date" class="form-control" name="dest_date[]" 
                                                                value="<?php echo formatDate($truck_detail['dest_date'] ?? $container['delivery_date'] ?? ''); ?>">
                                                        </div>
                                                        <div class="col-md-4">
                                                            <label class="form-label">Offload Date</label>
                                                            <input type="date" class="form-control" name="offload_date[]" 
                                                                value="<?php echo formatDate($truck_detail['offload_date'] ?? ''); ?>">
                                                        </div>
                                                        <div class="col-md-4">
                                                            <label class="form-label">Empty Return Date</label>
                                                            <input type="date" class="form-control" name="empty_return_date[]" 
                                                                value="<?php echo formatDate($truck_detail['empty_return_date'] ?? $container['empty_return_date'] ?? ''); ?>">
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <?php endforeach; ?>
                                        
                                        <div class="mt-4 mb-3 text-end">
                                            <a href="view_file.php?id=<?php echo $file_id; ?>" class="btn btn-light me-2">
                                                <i class="ri-arrow-left-line align-bottom me-1"></i> Cancel
                                            </a>
                                            <button type="submit" class="btn btn-primary" id="submitBtn">
                                                <i class="ri-truck-line align-bottom me-1"></i> Save Truck Assignments
                                            </button>
                                        </div>
                                        
                                        <?php endif; ?>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.12/dist/sweetalert2.all.min.js"></script>
    <script>
        $(document).ready(function() {
            // Initialize Select2
            $('.select2-transporter').select2({
                width: '100%',
                placeholder: 'Select a transporter'
            });
            
            // Auto-copy transporter to other fields if they have the same container code
            $('.select2-transporter').on('change', function() {
                const selectedTransporter = $(this).val();
                const containerCode = $(this).closest('.truck-assignment-card').find('input[name="containers[]"]').val();
                
                // Find all other cards with the same container code and update them
                $('input[name="containers[]"]').each(function() {
                    if ($(this).val() === containerCode) {
                        $(this).closest('.truck-assignment-card').find('.select2-transporter')
                            .val(selectedTransporter)
                            .trigger('change');
                    }
                });
            });
            
            // Handle form submission with SweetAlert confirmation
            $('#truckAssignmentForm').on('submit', function(e) {
                e.preventDefault();
                
                Swal.fire({
                    title: 'Confirm Assignment',
                    text: "Are you sure you want to save these truck assignments?",
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Yes, save it!'
                }).then((result) => {
                    if (result.isConfirmed) {
                        // Show loading state
                        Swal.fire({
                            title: 'Saving...',
                            text: 'Please wait while we save the truck assignments',
                            allowOutsideClick: false,
                            didOpen: () => {
                                Swal.showLoading();
                            }
                        });
                        
                        // Submit the form
                        this.submit();
                    }
                });
            });
            
            // Show SweetAlert for errors if present
            <?php if (isset($_SESSION['swal_error'])): ?>
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: '<?php echo $_SESSION['swal_error']; ?>',
                confirmButtonColor: '#3085d6'
            });
            <?php unset($_SESSION['swal_error']); ?>
            <?php endif; ?>
        });
    </script>
</body>
</html>