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

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

// Get user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email, role_id FROM users WHERE user_id = $user_id";
$result_user_details = $conn->query($sql_user_details);

if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $username = $row_user_details['username'];
    $user_role = $row_user_details['user_role'];
    $full_name = $row_user_details['full_name'];
    $email = $row_user_details['email'];
    $role_id = $row_user_details['role_id'];
} else {
    // Handle the case if user details are not found
    header('Location: login.php');
    exit();
}

// Check if form is submitted for assignment
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['assign_truck'])) {
    $file_number = $_POST['file_number'];
    $container_codes = $_POST['container_code'];
    $transporter_name = $_POST['transporter_name'];
    $load_date = !empty($_POST['load_date']) ? $_POST['load_date'] : null;
    $truck_trailer_no = $_POST['truck_trailer_no'];
    $driver_name = $_POST['driver_name'];
    $driver_phone = $_POST['driver_phone'];
    $driver_license = $_POST['driver_license'];
    
    // Validate file number
    if (empty($file_number)) {
        $_SESSION['error_message'] = "Please select a file number";
    } else {
        // Check if file exists
        $check_file_query = "SELECT id FROM files WHERE file_number = ?";
        $check_file_stmt = $conn->prepare($check_file_query);
        $check_file_stmt->bind_param('s', $file_number);
        $check_file_stmt->execute();
        $check_file_result = $check_file_stmt->get_result();
        
        if ($check_file_result->num_rows === 0) {
            $_SESSION['error_message'] = "Invalid file number selected";
        } else {
            try {
                $conn->begin_transaction();
                
                // Insert truck details for each container
                $success_count = 0;
                $error_messages = [];
                
                foreach ($container_codes as $index => $container_code) {
                    if (empty($container_code)) {
                        continue; // Skip empty containers
                    }
                    
                    // Check if container already has a truck assignment
                    $check_truck_query = "SELECT id FROM truck_details WHERE file_no = ? AND container_code = ?";
                    $check_truck_stmt = $conn->prepare($check_truck_query);
                    $check_truck_stmt->bind_param('ss', $file_number, $container_code);
                    $check_truck_stmt->execute();
                    $check_truck_result = $check_truck_stmt->get_result();
                    
                    if ($check_truck_result->num_rows > 0) {
                        $error_messages[] = "Container $container_code already has a truck assignment";
                        continue;
                    }
                    
                    // Insert new truck assignment
                    $insert_query = "INSERT INTO truck_details (
                        file_no, container_code, transporter_name, load_date,
                        truck_trailer_no, driver_name, driver_phone_number, driver_license,
                        user_id, created_at
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
                    
                    $insert_stmt = $conn->prepare($insert_query);
                    $insert_stmt->bind_param('ssssssssi', 
                        $file_number, 
                        $container_code, 
                        $transporter_name, 
                        $load_date, 
                        $truck_trailer_no, 
                        $driver_name, 
                        $driver_phone, 
                        $driver_license, 
                        $user_id
                    );
                    
                    if ($insert_stmt->execute()) {
                        $success_count++;
                    } else {
                        $error_messages[] = "Error assigning truck for container $container_code: " . $conn->error;
                    }
                }
                
                $conn->commit();
                
                if ($success_count > 0) {
                    $_SESSION['success_message'] = "Successfully assigned truck to $success_count container(s)";
                    if (!empty($error_messages)) {
                        $_SESSION['warning_message'] = implode("<br>", $error_messages);
                    }
                    header("Location: truck_list.php");
                    exit();
                } else {
                    $_SESSION['error_message'] = "Failed to assign any trucks.<br>" . implode("<br>", $error_messages);
                }
            } catch (Exception $e) {
                $conn->rollback();
                $_SESSION['error_message'] = "Error: " . $e->getMessage();
            }
        }
    }
}

// Get available files for dropdown
$files_query = "SELECT f.file_number, f.consignee_name, f.destination
                FROM files f
                WHERE f.`local/transit` = 2 AND f.close_file IS NULL
                ORDER BY f.created_date DESC";
$files_result = $conn->query($files_query);

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

include 'layouts/main.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Assign Trucks')); ?>
    <?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.3.0/dist/sweetalert2.min.css">
    <style>
        .required {
            color: red;
        }
        .container-card {
            border-left: 3px solid #3498db;
            margin-bottom: 20px;
        }
        .container-details {
            background-color: #f8f9fa;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 5px;
        }
        .select2-container .select2-selection--single {
            height: 38px;
            border-color: #ced4da;
        }
        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 36px;
        }
        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 36px;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Container Transport', 'title' => 'Assign Trucks')); ?>
                    
                    <?php if (isset($_SESSION['success_message'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>
                    
                    <?php if (isset($_SESSION['error_message'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>
                    
                    <?php if (isset($_SESSION['warning_message'])): ?>
                        <div class="alert alert-warning alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['warning_message']; unset($_SESSION['warning_message']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-xl-12">
                            <div class="card">
                                <div class="card-header">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <h4 class="card-title mb-0">Truck Assignment Form</h4>
                                        <div>
                                            <a href="truck_list.php" class="btn btn-primary">
                                                <i class="ri-list-check align-middle me-1"></i> View Assignments
                                            </a>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <form action="" method="POST" id="truckAssignmentForm">
                                        <div class="row mb-4">
                                            <div class="col-md-12">
                                                <label for="file_number" class="form-label">Select File Number <span class="required">*</span></label>
                                                <select class="form-select select2" id="file_number" name="file_number" required>
                                                    <option value="">Select File Number</option>
                                                    <?php if ($files_result && $files_result->num_rows > 0): ?>
                                                        <?php while ($row = $files_result->fetch_assoc()): ?>
                                                            <option value="<?php echo htmlspecialchars($row['file_number']); ?>">
                                                                <?php echo htmlspecialchars($row['file_number']); ?> - 
                                                                <?php echo htmlspecialchars($row['consignee_name']); ?> 
                                                                (<?php echo htmlspecialchars($row['destination']); ?>)
                                                            </option>
                                                        <?php endwhile; ?>
                                                    <?php endif; ?>
                                                </select>
                                            </div>
                                        </div>
                                        
                                        <div id="fileDetails" class="mb-4" style="display: none;">
                                            <div class="container-details">
                                                <div class="row">
                                                    <div class="col-md-4 mb-3">
                                                        <strong>Consignee:</strong> <span id="consignee-name"></span>
                                                    </div>
                                                    <div class="col-md-4 mb-3">
                                                        <strong>Destination:</strong> <span id="destination"></span>
                                                    </div>
                                                    <div class="col-md-4 mb-3">
                                                        <strong>Bill of Lading:</strong> <span id="bl-number"></span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div id="containerSection" style="display: none;">
                                            <h5 class="mb-3">Select Containers for Assignment</h5>
                                            <div id="containerList" class="mb-4">
                                                <!-- Container checkboxes will be added here -->
                                            </div>
                                        </div>
                                        
                                        <div id="truckDetails" style="display: none;">
                                            <h5 class="mb-3">Truck and Driver Details</h5>
                                            
                                            <div class="row mb-3">
                                                <div class="col-md-6">
                                                    <label for="transporter_name" class="form-label">Transporter <span class="required">*</span></label>
                                                    <select class="form-select select2" id="transporter_name" name="transporter_name" required>
                                                        <option value="">Select Transporter</option>
                                                        <?php foreach ($transporters as $transporter): ?>
                                                            <option value="<?php echo htmlspecialchars($transporter['name']); ?>">
                                                                <?php echo htmlspecialchars($transporter['name']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-6">
                                                    <label for="load_date" class="form-label">Load Date</label>
                                                    <input type="date" class="form-control" id="load_date" name="load_date">
                                                </div>
                                            </div>
                                            
                                            <div class="row mb-3">
                                                <div class="col-md-6">
                                                    <label for="truck_trailer_no" class="form-label">Truck/Trailer Number</label>
                                                    <input type="text" class="form-control" id="truck_trailer_no" name="truck_trailer_no">
                                                </div>
                                                
                                                <div class="col-md-6">
                                                    <label for="driver_name" class="form-label">Driver Name</label>
                                                    <input type="text" class="form-control" id="driver_name" name="driver_name">
                                                </div>
                                            </div>
                                            
                                            <div class="row mb-3">
                                                <div class="col-md-6">
                                                    <label for="driver_phone" class="form-label">Driver Phone Number</label>
                                                    <input type="text" class="form-control" id="driver_phone" name="driver_phone">
                                                </div>
                                                
                                                <div class="col-md-6">
                                                    <label for="driver_license" class="form-label">Driver License</label>
                                                    <input type="text" class="form-control" id="driver_license" name="driver_license">
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="row mt-4">
                                            <div class="col-12 text-end">
                                                <a href="truck_list.php" class="btn btn-light me-2">Cancel</a>
                                                <button type="submit" name="assign_truck" id="assignButton" class="btn btn-primary" style="display: none;">
                                                    Assign Truck
                                                </button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
        $(document).ready(function() {
            // Initialize Select2
            $('.select2').select2({
                width: '100%',
                placeholder: 'Select an option'
            });
            
            // File number change
            $('#file_number').on('change', function() {
                const fileNumber = $(this).val();
                if (fileNumber) {
                    // Fetch file details and containers
                    fetch('get_file_containers.php?file_number=' + encodeURIComponent(fileNumber))
                        .then(response => response.json())
                        .then(data => {
                            if (data.error) {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Error',
                                    text: data.error
                                });
                                return;
                            }
                            
                            // Update file details
                            $('#consignee-name').text(data.file_details.consignee_name || 'N/A');
                            $('#destination').text(data.file_details.destination || 'N/A');
                            $('#bl-number').text(data.file_details.obl_no || 'N/A');
                            $('#fileDetails').show();
                            
                            // Populate container list
                            if (data.containers && data.containers.length > 0) {
                                const containerList = $('#containerList');
                                containerList.empty();
                                
                                data.containers.forEach((container, index) => {
                                    const hasAssignment = container.has_assignment === true;
                                    
                                    const containerHtml = `
                                        <div class="container-card card mb-3">
                                            <div class="card-body">
                                                <div class="form-check mb-2">
                                                    <input class="form-check-input container-checkbox" type="checkbox" 
                                                           name="container_code[]" value="${container.container_code}" 
                                                           id="container-${index}" ${hasAssignment ? 'disabled' : ''}>
                                                    <label class="form-check-label" for="container-${index}">
                                                        ${container.container_code} (${container.container_size}ft)
                                                        ${hasAssignment ? '<span class="badge bg-info ms-2">Already Assigned</span>' : ''}
                                                    </label>
                                                </div>
                                            </div>
                                        </div>
                                    `;
                                    
                                    containerList.append(containerHtml);
                                });
                                
                                // Show container section and enable checkbox change events
                                $('#containerSection').show();
                                
                                // Check for container selection to show/hide truck details
                                $('.container-checkbox').on('change', function() {
                                    const anyChecked = $('.container-checkbox:checked').length > 0;
                                    $('#truckDetails').toggle(anyChecked);
                                    $('#assignButton').toggle(anyChecked);
                                });
                            } else {
                                $('#containerSection').hide();
                                $('#truckDetails').hide();
                                $('#assignButton').hide();
                                
                                Swal.fire({
                                    icon: 'warning',
                                    title: 'No Containers',
                                    text: 'No containers found for this file or all containers are already assigned'
                                });
                            }
                        })
                        .catch(error => {
                            console.error('Error fetching file details:', error);
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: 'Failed to load file details. Please try again.'
                            });
                        });
                } else {
                    // Hide sections if no file selected
                    $('#fileDetails').hide();
                    $('#containerSection').hide();
                    $('#truckDetails').hide();
                    $('#assignButton').hide();
                }
            });
            
            // Form validation
            $('#truckAssignmentForm').on('submit', function(e) {
                const fileNumber = $('#file_number').val();
                const transporter = $('#transporter_name').val();
                const containersChecked = $('.container-checkbox:checked').length;
                
                if (!fileNumber || !transporter || containersChecked === 0) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'error',
                        title: 'Validation Error',
                        text: 'Please select file, transporter, and at least one container'
                    });
                    return false;
                }
                
                // Add loading indicator
                Swal.fire({
                    title: 'Processing',
                    text: 'Assigning truck...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
                
                return true;
            });
        });
    </script>
</body>
</html>