<?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 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'];
} else {
    header('Location: login.php');
    exit();
}

// Fetch active transporters for dropdown
$transporters_query = "SELECT id, name FROM transporter_info WHERE status = 1 ORDER BY name";
$transporters_result = $conn->query($transporters_query);

// Fetch assigned shipments that can be reassigned
$shipments_query = "
    SELECT 
        f.file_number,
        f.consignee_name,
        f.destination,
        cd.container_code,
        cd.container_size,
        cd.transporter_name,
        cd.driver_name,
        cd.driver_phone_number,
        cd.driver_license
    FROM files f
    LEFT JOIN container_details cd ON f.file_number = cd.file_number
    WHERE cd.transporter_name IS NOT NULL
    ORDER BY f.created_date DESC";

$shipments_result = $conn->query($shipments_query);

// Include the main layout
include 'layouts/main.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Truck Reassignment')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        .status-badge {
            padding: 5px 10px;
            border-radius: 15px;
            font-size: 12px;
        }
        .reassign-btn {
            min-width: 100px;
        }
    </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' => 'Transportation', 'title' => 'Truck Reassignment')); ?>

                    <!-- Alert Messages -->
                    <?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; ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Current Truck Assignments</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-bordered table-hover">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>File Number</th>
                                                    <th>Consignee</th>
                                                    <th>Container</th>
                                                    <th>Current Transporter</th>
                                                    <th>Driver Details</th>
                                                    <th>Destination</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($shipments_result && $shipments_result->num_rows > 0): ?>
                                                    <?php while ($row = $shipments_result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo htmlspecialchars($row['file_number']); ?></td>
                                                            <td><?php echo htmlspecialchars($row['consignee_name']); ?></td>
                                                            <td>
                                                                <?php 
                                                                echo htmlspecialchars($row['container_code']) . '<br>';
                                                                echo '<small class="text-muted">' . htmlspecialchars($row['container_size']) . 'ft</small>';
                                                                ?>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($row['transporter_name']); ?></td>
                                                            <td>
                                                                <?php if ($row['driver_name']): ?>
                                                                    <strong>Name:</strong> <?php echo htmlspecialchars($row['driver_name']); ?><br>
                                                                    <strong>Phone:</strong> <?php echo htmlspecialchars($row['driver_phone_number']); ?><br>
                                                                    <strong>License:</strong> <?php echo htmlspecialchars($row['driver_license']); ?>
                                                                <?php else: ?>
                                                                    <span class="text-muted">No driver assigned</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($row['destination']); ?></td>
                                                            <td>
                                                                <button type="button" 
                                                                        class="btn btn-primary btn-sm reassign-btn"
                                                                        data-bs-toggle="modal"
                                                                        data-bs-target="#reassignModal"
                                                                        data-file="<?php echo htmlspecialchars($row['file_number']); ?>"
                                                                        data-container="<?php echo htmlspecialchars($row['container_code']); ?>">
                                                                    Reassign
                                                                </button>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="7" class="text-center">No assigned shipments found</td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Reassignment Modal -->
    <div class="modal fade" id="reassignModal" tabindex="-1" aria-labelledby="reassignModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="reassignModalLabel">Reassign Truck</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="reassignForm" action="process_reassignment.php" method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="file_number" id="reassignFileNumber">
                        <input type="hidden" name="container_code" id="reassignContainer">
                        
                        <div class="mb-3">
                            <label class="form-label">New Transporter</label>
                            <select class="form-select" name="new_transporter" required>
                                <option value="">Select Transporter</option>
                                <?php 
                                if ($transporters_result) {
                                    while ($transporter = $transporters_result->fetch_assoc()) {
                                        echo '<option value="' . $transporter['id'] . '">' . htmlspecialchars($transporter['name']) . '</option>';
                                    }
                                }
                                ?>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">New Driver Name</label>
                            <input type="text" class="form-control" name="driver_name" required>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Driver Phone</label>
                                    <input type="text" class="form-control" name="driver_phone" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Driver License</label>
                                    <input type="text" class="form-control" name="driver_license" required>
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Reason for Reassignment</label>
                            <textarea class="form-control" name="reason" rows="3" required></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Submit Reassignment</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <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.addEventListener('DOMContentLoaded', function() {
        // Handle reassign button clicks
        const reassignButtons = document.querySelectorAll('.reassign-btn');
        
        reassignButtons.forEach(button => {
            button.addEventListener('click', function() {
                const fileNumber = this.getAttribute('data-file');
                const container = this.getAttribute('data-container');
                
                // Set values in the modal form
                document.getElementById('reassignFileNumber').value = fileNumber;
                document.getElementById('reassignContainer').value = container;
                
                // Update modal title
                document.getElementById('reassignModalLabel').textContent = 
                    `Reassign Truck - ${fileNumber} (${container})`;
                
                // Clear previous form data
                document.getElementById('reassignForm').reset();
                
                // Remove any previous validation states
                const formElements = document.getElementById('reassignForm').elements;
                for (let i = 0; i < formElements.length; i++) {
                    formElements[i].classList.remove('is-invalid');
                }
            });
        });
        
        // Form validation
        const reassignForm = document.getElementById('reassignForm');
        reassignForm.addEventListener('submit', function(e) {
            let isValid = true;
            const requiredFields = reassignForm.querySelectorAll('[required]');
            
            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    isValid = false;
                    field.classList.add('is-invalid');
                } else {
                    field.classList.remove('is-invalid');
                }
            });
            
            if (!isValid) {
                e.preventDefault();
                Swal.fire({
                    icon: 'error',
                    title: 'Validation Error',
                    text: 'Please fill in all required fields',
                    confirmButtonColor: '#3085d6'
                });
                return;
            }
            
            // Confirm before submitting
            e.preventDefault();
            Swal.fire({
                title: 'Confirm Reassignment',
                text: 'Are you sure you want to reassign this shipment?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, reassign',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Show loading state
                    Swal.fire({
                        title: 'Processing...',
                        text: 'Please wait while we process the reassignment',
                        allowOutsideClick: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });
                    
                    // Submit the form
                    reassignForm.submit();
                }
            });
        });
        
        // Input validation handlers
        const driverPhone = document.querySelector('input[name="driver_phone"]');
        if (driverPhone) {
            driverPhone.addEventListener('input', function(e) {
                // Allow only numbers and basic phone formatting characters
                this.value = this.value.replace(/[^\d\s\-+()]/g, '');
            });
        }
        
        const driverLicense = document.querySelector('input[name="driver_license"]');
        if (driverLicense) {
            driverLicense.addEventListener('input', function(e) {
                // Convert to uppercase and remove special characters
                this.value = this.value.toUpperCase().replace(/[^\w\d]/g, '');
            });
        }
    });
</script>
</body>
</html>