<?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();
}

// Pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 10;
$offset = ($page - 1) * $perPage;

// Search parameters
$search = isset($_GET['search']) ? $_GET['search'] : '';
$status = isset($_GET['status']) ? $_GET['status'] : '';
$dateFrom = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$dateTo = isset($_GET['date_to']) ? $_GET['date_to'] : '';

// Base query
$baseQuery = "
    SELECT td.*, f.consignee_name, f.destination
    FROM truck_details td
    LEFT JOIN files f ON td.file_no = f.file_number
    WHERE 1=1
";

// Add search filters
if (!empty($search)) {
    $baseQuery .= " AND (td.file_no LIKE '%$search%' OR td.container_code LIKE '%$search%' OR 
                         td.transporter_name LIKE '%$search%' OR td.driver_name LIKE '%$search%' OR 
                         f.consignee_name LIKE '%$search%')";
}

if (!empty($status)) {
    switch ($status) {
        case 'loading':
            $baseQuery .= " AND td.load_date IS NOT NULL AND td.port_date IS NULL";
            break;
        case 'in_transit':
            $baseQuery .= " AND td.port_date IS NOT NULL AND td.delivery_date IS NULL";
            break;
        case 'at_border':
            $baseQuery .= " AND td.border_date IS NOT NULL AND td.border_crossing_date IS NULL";
            break;
        case 'delivered':
            $baseQuery .= " AND td.offload_date IS NOT NULL";
            break;
        case 'completed':
            $baseQuery .= " AND td.empty_return_date IS NOT NULL";
            break;
    }
}

if (!empty($dateFrom)) {
    $baseQuery .= " AND td.load_date >= '$dateFrom'";
}

if (!empty($dateTo)) {
    $baseQuery .= " AND td.load_date <= '$dateTo'";
}

// Count total records for pagination
$countQuery = "SELECT COUNT(*) as total FROM ($baseQuery) as count_table";
$countResult = $conn->query($countQuery);
$totalRecords = $countResult->fetch_assoc()['total'];
$totalPages = ceil($totalRecords / $perPage);

// Get truck details with pagination
$query = $baseQuery . " ORDER BY td.created_at DESC LIMIT $offset, $perPage";
$result = $conn->query($query);

include 'layouts/main.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Truck Assignment List')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
    <style>
        .truck-status {
            display: inline-block;
            width: 15px;
            height: 15px;
            border-radius: 50%;
            margin-right: 5px;
        }
        .status-loading {
            background-color: #6c757d;
        }
        .status-in-transit {
            background-color: #ffc107;
        }
        .status-at-border {
            background-color: #0dcaf0;
        }
        .status-border-crossed {
            background-color: #0d6efd;
        }
        .status-delivered {
            background-color: #198754;
        }
        .status-completed {
            background-color: #20c997;
        }
        .custom-dropdown-menu {
            min-width: 300px;
            padding: 15px;
        }
    </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' => 'Truck Assignment List')); ?>
                    
                    <?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" id="invoiceList">
                                <div class="card-header border-0">
                                    <div class="d-flex align-items-center">
                                        <h5 class="card-title mb-0 flex-grow-1">Truck Assignments</h5>
                                        <div class="flex-shrink-0">
                                            <div class="d-flex gap-2 flex-wrap">
                                                <button class="btn btn-primary" id="addTruck" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                                                    <i class="ri-truck-line align-bottom me-1"></i> New Truck Assignment
                                                </button>
                                                <div class="dropdown">
                                                    <button class="btn btn-soft-secondary" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                                                        <i class="ri-filter-2-line align-bottom me-1"></i> Filters
                                                    </button>
                                                    <div class="dropdown-menu custom-dropdown-menu">
                                                        <form action="" method="GET" id="searchForm">
                                                            <div class="mb-3">
                                                                <label for="search" class="form-label">Search</label>
                                                                <input type="text" class="form-control" id="search" name="search" value="<?php echo htmlspecialchars($search); ?>" placeholder="File number, container, transporter...">
                                                            </div>
                                                            <div class="mb-3">
                                                                <label for="status" class="form-label">Status</label>
                                                                <select class="form-select" id="status" name="status">
                                                                    <option value="">All Statuses</option>
                                                                    <option value="loading" <?php echo $status === 'loading' ? 'selected' : ''; ?>>Loading</option>
                                                                    <option value="in_transit" <?php echo $status === 'in_transit' ? 'selected' : ''; ?>>In Transit</option>
                                                                    <option value="at_border" <?php echo $status === 'at_border' ? 'selected' : ''; ?>>At Border</option>
                                                                    <option value="delivered" <?php echo $status === 'delivered' ? 'selected' : ''; ?>>Delivered</option>
                                                                    <option value="completed" <?php echo $status === 'completed' ? 'selected' : ''; ?>>Completed</option>
                                                                </select>
                                                            </div>
                                                            <div class="row mb-3">
                                                                <div class="col-sm-6">
                                                                    <label for="date_from" class="form-label">From Date</label>
                                                                    <input type="date" class="form-control" id="date_from" name="date_from" value="<?php echo htmlspecialchars($dateFrom); ?>">
                                                                </div>
                                                                <div class="col-sm-6">
                                                                    <label for="date_to" class="form-label">To Date</label>
                                                                    <input type="date" class="form-control" id="date_to" name="date_to" value="<?php echo htmlspecialchars($dateTo); ?>">
                                                                </div>
                                                            </div>
                                                            <div class="d-flex gap-2">
                                                                <button type="submit" class="btn btn-primary w-100">Apply Filters</button>
                                                                <a href="truck_list.php" class="btn btn-light w-100">Reset</a>
                                                            </div>
                                                        </form>
                                                    </div>
                                                </div>
                                                <button class="btn btn-soft-secondary" onclick="window.print()">
                                                    <i class="ri-printer-line align-bottom me-1"></i> Print
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table align-middle table-nowrap mb-0" id="truckTable">
                                            <thead class="table-light">
                                                <tr>
                                                    <th scope="col">ID</th>
                                                    <th scope="col">File Number</th>
                                                    <th scope="col">Container</th>
                                                    <th scope="col">Transporter</th>
                                                    <th scope="col">Driver</th>
                                                    <th scope="col">Destination</th>
                                                    <th scope="col">Load Date</th>
                                                    <th scope="col">Status</th>
                                                    <th scope="col">Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php while ($row = $result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo $row['id']; ?></td>
                                                            <td>
                                                                <a href="view_file.php?file_number=<?php echo htmlspecialchars($row['file_no']); ?>" class="fw-medium">
                                                                    <?php echo htmlspecialchars($row['file_no']); ?>
                                                                </a>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($row['container_code']); ?></td>
                                                            <td><?php echo htmlspecialchars($row['transporter_name']); ?></td>
                                                            <td><?php echo htmlspecialchars($row['driver_name'] ?? 'N/A'); ?></td>
                                                            <td><?php echo htmlspecialchars($row['destination'] ?? 'N/A'); ?></td>
                                                            <td>
                                                                <?php 
                                                                    echo !empty($row['load_date']) ? 
                                                                        date('d M Y', strtotime($row['load_date'])) : 
                                                                        'Not loaded';
                                                                ?>
                                                            </td>
                                                            <td>
                                                                <?php
                                                                    if (!empty($row['empty_return_date'])) {
                                                                        echo '<span><span class="truck-status status-completed"></span>Completed</span>';
                                                                    } elseif (!empty($row['offload_date'])) {
                                                                        echo '<span><span class="truck-status status-delivered"></span>Delivered</span>';
                                                                    } elseif (!empty($row['border_crossing_date'])) {
                                                                        echo '<span><span class="truck-status status-border-crossed"></span>Border Crossed</span>';
                                                                    } elseif (!empty($row['border_date'])) {
                                                                        echo '<span><span class="truck-status status-at-border"></span>At Border</span>';
                                                                    } elseif (!empty($row['port_date'])) {
                                                                        echo '<span><span class="truck-status status-in-transit"></span>In Transit</span>';
                                                                    } elseif (!empty($row['load_date'])) {
                                                                        echo '<span><span class="truck-status status-loading"></span>Loading</span>';
                                                                    } else {
                                                                        echo '<span class="badge bg-secondary">Pending</span>';
                                                                    }
                                                                ?>
                                                            </td>
                                                            <td>
                                                                <div class="d-flex gap-2">
                                                                    <a href="truck_details.php?id=<?php echo $row['id']; ?>&action=edit" class="btn btn-sm btn-primary">
                                                                        <i class="ri-pencil-line"></i>
                                                                    </a>
                                                                    <button type="button" class="btn btn-sm btn-info view-details" 
                                                                            data-id="<?php echo $row['id']; ?>"
                                                                            data-file="<?php echo htmlspecialchars($row['file_no']); ?>"
                                                                            data-container="<?php echo htmlspecialchars($row['container_code']); ?>"
                                                                            data-transporter="<?php echo htmlspecialchars($row['transporter_name']); ?>"
                                                                            data-driver="<?php echo htmlspecialchars($row['driver_name'] ?? 'N/A'); ?>"
                                                                            data-phone="<?php echo htmlspecialchars($row['driver_phone_number'] ?? 'N/A'); ?>"
                                                                            data-load="<?php echo !empty($row['load_date']) ? date('d M Y', strtotime($row['load_date'])) : 'N/A'; ?>"
                                                                            data-port="<?php echo !empty($row['port_date']) ? date('d M Y', strtotime($row['port_date'])) : 'N/A'; ?>"
                                                                            data-border="<?php echo !empty($row['border_date']) ? date('d M Y', strtotime($row['border_date'])) : 'N/A'; ?>"
                                                                            data-crossing="<?php echo !empty($row['border_crossing_date']) ? date('d M Y', strtotime($row['border_crossing_date'])) : 'N/A'; ?>"
                                                                            data-dest="<?php echo !empty($row['dest_date']) ? date('d M Y', strtotime($row['dest_date'])) : 'N/A'; ?>"
                                                                            data-offload="<?php echo !empty($row['offload_date']) ? date('d M Y', strtotime($row['offload_date'])) : 'N/A'; ?>"
                                                                            data-return="<?php echo !empty($row['empty_return_date']) ? date('d M Y', strtotime($row['empty_return_date'])) : 'N/A'; ?>">
                                                                        <i class="ri-eye-line"></i>
                                                                    </button>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="9" class="text-center">No truck assignments found</td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    
                                    <!-- Pagination -->
                                    <?php if ($totalPages > 1): ?>
                                        <div class="d-flex justify-content-end mt-3">
                                            <ul class="pagination">
                                                <?php if ($page > 1): ?>
                                                    <li class="page-item">
                                                        <a class="page-link" href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>&date_from=<?php echo urlencode($dateFrom); ?>&date_to=<?php echo urlencode($dateTo); ?>" aria-label="Previous">
                                                            <span aria-hidden="true">&laquo;</span>
                                                        </a>
                                                    </li>
                                                <?php endif; ?>
                                                
                                                <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                                                    <li class="page-item <?php echo $page == $i ? 'active' : ''; ?>">
                                                        <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>&date_from=<?php echo urlencode($dateFrom); ?>&date_to=<?php echo urlencode($dateTo); ?>">
                                                            <?php echo $i; ?>
                                                        </a>
                                                    </li>
                                                <?php endfor; ?>
                                                
                                                <?php if ($page < $totalPages): ?>
                                                    <li class="page-item">
                                                        <a class="page-link" href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>&date_from=<?php echo urlencode($dateFrom); ?>&date_to=<?php echo urlencode($dateTo); ?>" aria-label="Next">
                                                            <span aria-hidden="true">&raquo;</span>
                                                        </a>
                                                    </li>
                                                <?php endif; ?>
                                            </ul>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- File Number Modal -->
    <div class="modal fade" id="fileNumberModal" tabindex="-1" aria-labelledby="fileNumberModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="fileNumberModalLabel">Select File Number</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form action="truck_details.php" method="GET" id="fileNumberForm">
                        <div class="mb-3">
                            <label for="file_number" class="form-label">Enter or Search File Number</label>
                            <input type="text" class="form-control" id="file_number" name="file_number" required>
                        </div>
                        <button type="submit" class="btn btn-primary">Proceed</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- View Details Modal -->
    <div class="modal fade" id="viewDetailsModal" tabindex="-1" aria-labelledby="viewDetailsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="viewDetailsModalLabel">Truck Assignment Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <table class="table table-bordered">
                                <tr>
                                    <th>File Number</th>
                                    <td id="modal-file"></td>
                                </tr>
                                <tr>
                                    <th>Container</th>
                                    <td id="modal-container"></td>
                                </tr>
                                <tr>
                                    <th>Transporter</th>
                                    <td id="modal-transporter"></td>
                                </tr>
                                <tr>
                                    <th>Driver</th>
                                    <td id="modal-driver"></td>
                                </tr>
                                <tr>
                                    <th>Driver Phone</th>
                                    <td id="modal-phone"></td>
                                </tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <table class="table table-bordered">
                                <tr>
                                    <th>Load Date</th>
                                    <td id="modal-load"></td>
                                </tr>
                                <tr>
                                    <th>Port Exit</th>
                                    <td id="modal-port"></td>
                                </tr>
                                <tr>
                                    <th>At Border</th>
                                    <td id="modal-border"></td>
                                </tr>
                                <tr>
                                    <th>Border Crossing</th>
                                    <td id="modal-crossing"></td>
                                </tr>
                                <tr>
                                    <th>Arrival Date</th>
                                    <td id="modal-dest"></td>
                                </tr>
                                <tr>
                                    <th>Offload Date</th>
                                    <td id="modal-offload"></td>
                                </tr>
                                <tr>
                                    <th>Empty Return</th>
                                    <td id="modal-return"></td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <a href="#" class="btn btn-primary" id="editDetailsBtn">Edit Details</a>
                </div>
            </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>
        // Initialize file number modal
        document.getElementById('addTruck').addEventListener('click', function() {
            var fileNumberModal = new bootstrap.Modal(document.getElementById('fileNumberModal'));
            fileNumberModal.show();
        });
        
        // View details modal handling
        document.querySelectorAll('.view-details').forEach(function(button) {
            button.addEventListener('click', function() {
                const id = this.getAttribute('data-id');
                const file = this.getAttribute('data-file');
                const container = this.getAttribute('data-container');
                const transporter = this.getAttribute('data-transporter');
                const driver = this.getAttribute('data-driver');
                const phone = this.getAttribute('data-phone');
                const load = this.getAttribute('data-load');
                const port = this.getAttribute('data-port');
                const border = this.getAttribute('data-border');
                const crossing = this.getAttribute('data-crossing');
                const dest = this.getAttribute('data-dest');
                const offload = this.getAttribute('data-offload');
                const returnDate = this.getAttribute('data-return');
                
                // Update modal content
                document.getElementById('modal-file').textContent = file;
                document.getElementById('modal-container').textContent = container;
                document.getElementById('modal-transporter').textContent = transporter;
                document.getElementById('modal-driver').textContent = driver;
                document.getElementById('modal-phone').textContent = phone;
                document.getElementById('modal-load').textContent = load;
                document.getElementById('modal-port').textContent = port;
                document.getElementById('modal-border').textContent = border;
                document.getElementById('modal-crossing').textContent = crossing;
                document.getElementById('modal-dest').textContent = dest;
                document.getElementById('modal-offload').textContent = offload;
                document.getElementById('modal-return').textContent = returnDate;
                
                // Update edit button href
                document.getElementById('editDetailsBtn').href = 'truck_details.php?id=' + id + '&action=edit';
                
                // Show modal
                const viewModal = new bootstrap.Modal(document.getElementById('viewDetailsModal'));
                viewModal.show();
            });
        });
        
        // File number autocomplete for the modal
        document.addEventListener('DOMContentLoaded', function() {
            const fileInput = document.getElementById('file_number');
            
            fileInput.addEventListener('keyup', function() {
                const searchTerm = this.value.trim();
                if (searchTerm.length < 3) return;
                
                // Fetch file numbers that match
                fetch('get_file_numbers.php?term=' + encodeURIComponent(searchTerm))
                    .then(response => response.json())
                    .then(data => {
                        // Create and display dropdown if we have matches
                        if (data.length > 0) {
                            // Implementation depends on whether you want to use a custom dropdown or a library like Select2
                            console.log("Matches:", data);
                        }
                    })
                    .catch(error => console.error('Error fetching file numbers:', error));
            });
        });
    </script>
</body>
</html>