<?php
session_start(); // Start the session
// Include the database connection file
include 'layouts/dbconn.php';

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

// Query to fetch 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'];
}

// Fetch the system name
$sql = "SELECT setting_value FROM settings WHERE setting_key = 'system_name'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $system_name = $row['setting_value'];
} else {
    $system_name = "Royal Freight"; // Fallback if not found
}

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

// Add at the start of the file, after session_start()
if (!isset($_GET['file_number'])) {
    $_SESSION['error_message'] = "No file number provided";
    header('Location: file_list.php');
    exit();
}

$file_number = $_GET['file_number'];

// Add validation for file existence and cargo type
$sql = "SELECT f.*, c.first_name, c.last_name 
        FROM files f
        LEFT JOIN customers c ON f.customer = c.customer_id
        WHERE f.file_number = ? AND f.c_type IN ('Bulk Cargo', 'Loose Cargo')";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $file_number);
$stmt->execute();
$result = $stmt->get_result();

if (!$result->num_rows) {
    $_SESSION['error_message'] = "Invalid file number or file type does not support truck assignment";
    header('Location: file_list.php');
    exit();
}
?>

<div class="main-content">
    <div class="page-content">
        <div class="container-fluid">
            <div class="row">
                <div class="col-12">
                    <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                        <h4 class="mb-sm-0">Update Truck Assignment</h4>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="card-title mb-0">Assign Additional Trucks</h5>
                        </div>
                        <div class="card-body">
                            <?php
                            if (isset($_SESSION['error_message'])) {
                                echo '<div class="alert alert-danger">' . $_SESSION['error_message'] . '</div>';
                                unset($_SESSION['error_message']);
                            }
                            if (isset($_SESSION['success_message'])) {
                                echo '<div class="alert alert-success">' . $_SESSION['success_message'] . '</div>';
                                unset($_SESSION['success_message']);
                            }

                            // Get file details
                            $file_number = $_GET['file_number'] ?? '';
                            $sql = "SELECT f.*, 
                                   COALESCE(f.total_trucks_required, 0) as total_trucks_required,
                                   COALESCE(f.trucks_assigned, 0) as trucks_assigned,
                                   COALESCE(f.trucks_remaining, 0) as trucks_remaining,
                                   c.first_name, c.last_name
                            FROM files f
                            LEFT JOIN customers c ON f.customer = c.customer_id
                            WHERE f.file_number = ?";
                            
                            $stmt = $conn->prepare($sql);
                            $stmt->bind_param('s', $file_number);
                            $stmt->execute();
                            $result = $stmt->get_result();
                            
                            if ($file = $result->fetch_assoc()) {
                            ?>
                                <form id="updateTruckForm" action="process_truck_update.php" method="POST">
                                    <input type="hidden" name="file_number" value="<?php echo htmlspecialchars($file_number); ?>">
                                    
                                    <div class="row mb-3">
                                        <div class="col-md-4">
                                            <label class="form-label">File Number</label>
                                            <input type="text" class="form-control" value="<?php echo htmlspecialchars($file_number); ?>" readonly>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Customer</label>
                                            <input type="text" class="form-control" value="<?php echo htmlspecialchars($file['first_name'] . ' ' . $file['last_name']); ?>" readonly>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Cargo Type</label>
                                            <input type="text" class="form-control" value="<?php echo htmlspecialchars($file['c_type']); ?>" readonly>
                                        </div>
                                    </div>

                                    <div class="row mb-3">
                                        <div class="col-md-4">
                                            <label class="form-label">Total Trucks Required</label>
                                            <input type="text" class="form-control" value="<?php echo htmlspecialchars($file['total_trucks_required']); ?>" readonly>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Currently Assigned</label>
                                            <input type="text" class="form-control" value="<?php echo htmlspecialchars($file['trucks_assigned']); ?>" readonly>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Remaining Trucks</label>
                                            <input type="text" class="form-control" value="<?php echo htmlspecialchars($file['trucks_remaining']); ?>" readonly>
                                        </div>
                                    </div>

                                    <div class="row mb-3">
                                        <div class="col-md-4">
                                            <label class="form-label">Trucks to Assign Now <span class="text-danger">*</span></label>
                                            <input type="number" class="form-control" name="trucks_to_assign" id="trucks_to_assign" 
                                                   min="1" max="<?php echo htmlspecialchars($file['trucks_remaining']); ?>" required>
                                        </div>
                                    </div>

                                    <div class="row mt-4">
                                        <div class="col-md-12">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="ri-truck-line align-middle me-1"></i> Assign Trucks
                                            </button>
                                            <a href="file_list.php" class="btn btn-secondary">
                                                <i class="ri-arrow-left-line align-middle me-1"></i> Back to Files
                                            </a>
                                        </div>
                                    </div>
                                </form>
                            <?php
                            } else {
                                echo '<div class="alert alert-danger">File not found</div>';
                            }
                            ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php include 'layouts/footer.php'; ?>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('updateTruckForm');
    const trucksToAssign = document.getElementById('trucks_to_assign');
    const maxTrucks = parseInt(trucksToAssign.getAttribute('max'));

    form.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const trucks = parseInt(trucksToAssign.value);
        if (!trucks || trucks < 1) {
            Swal.fire({
                icon: 'error',
                title: 'Invalid Input',
                text: 'Please enter a valid number of trucks to assign'
            });
            return;
        }

        if (trucks > maxTrucks) {
            Swal.fire({
                icon: 'error',
                title: 'Too Many Trucks',
                text: 'Cannot assign more trucks than remaining'
            });
            return;
        }

        Swal.fire({
            title: 'Confirm Assignment',
            text: `Are you sure you want to assign ${trucks} trucks?`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, Assign',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                form.submit();
            }
        });
    });
});
</script>

<?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>