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

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

// Handle search parameters
$search = $_GET['search'] ?? '';
$file_type = $_GET['file_type'] ?? 'all';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$customer_id = $_GET['customer_id'] ?? '';
$destination = $_GET['destination'] ?? '';

// Build the query
$query = "SELECT f.id, f.file_number, f.created_date, f.customer, f.consignee_name, 
          f.destination, f.obl_no, f.way_bill, f.eta, f.`local/transit` as file_type, 
          c.first_name as customer_name
          FROM files f
          LEFT JOIN customers c ON f.customer = c.customer_id
          WHERE 1=1";

$params = [];
$types = "";

if (!empty($search)) {
    $query .= " AND (f.file_number LIKE ? OR f.consignee_name LIKE ? OR f.obl_no LIKE ?)";
    $search_param = "%$search%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $types .= "sss";
}

if ($file_type !== 'all') {
    $query .= " AND f.`local/transit` = ?";
    $params[] = $file_type;
    $types .= "i";
}

if (!empty($date_from)) {
    $query .= " AND f.created_date >= ?";
    $params[] = $date_from . " 00:00:00";
    $types .= "s";
}

if (!empty($date_to)) {
    $query .= " AND f.created_date <= ?";
    $params[] = $date_to . " 23:59:59";
    $types .= "s";
}

if (!empty($customer_id)) {
    $query .= " AND f.customer = ?";
    $params[] = $customer_id;
    $types .= "i";
}

if (!empty($destination)) {
    $query .= " AND f.destination = ?";
    $params[] = $destination;
    $types .= "s";
}

// Add order by
$query .= " ORDER BY f.created_date DESC";

// Prepare and execute the query
$stmt = $conn->prepare($query);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();

// Fetch customers for filter dropdown
$query_customers = "SELECT customer_id, first_name FROM customers WHERE status = 1 ORDER BY first_name";
$result_customers = $conn->query($query_customers);
$customers = [];
if ($result_customers->num_rows > 0) {
    while ($row = $result_customers->fetch_assoc()) {
        $customers[] = $row;
    }
}

// Fetch destinations for filter dropdown
$query_destinations = "SELECT DISTINCT destination FROM files WHERE destination IS NOT NULL ORDER BY destination";
$result_destinations = $conn->query($query_destinations);
$destinations = [];
if ($result_destinations->num_rows > 0) {
    while ($row = $result_destinations->fetch_assoc()) {
        $destinations[] = $row['destination'];
    }
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Shipment Files')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/datatables/dataTables.bootstrap5.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/datatables/buttons.bootstrap5.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/datatables/responsive.bootstrap5.min.css" rel="stylesheet" type="text/css" />
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <style>
        .search-filters {
            margin-bottom: 1.5rem;
            padding: 1rem;
            background-color: #f8f9fa;
            border-radius: 0.25rem;
        }
        .file-actions .btn {
            margin-right: 5px;
        }
        .badge-transit {
            background-color: #0dcaf0;
        }
        .badge-local {
            background-color: #20c997;
        }
        .dt-buttons {
            margin-bottom: 15px;
        }
    </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' => 'Shipment Management', 'title' => 'Shipment Files')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header d-flex align-items-center">
                                    <h5 class="card-title mb-0 flex-grow-1">All Shipment Files</h5>
                                    <div>
                                        <a href="local_shipment.php" class="btn btn-primary me-2">
                                            <i class="ri-add-line align-bottom"></i> New Local Shipment
                                        </a>
                                        <a href="transit_shipment.php" class="btn btn-info">
                                            <i class="ri-add-line align-bottom"></i> New Transit Shipment
                                        </a>
                                    </div>
                                </div>
                                
                                <div class="card-body">
                                    <!-- Search Filters -->
                                    <div class="search-filters">
                                        <form method="GET" action="file_list.php" id="searchForm">
                                            <div class="row">
                                                <div class="col-md-3 mb-3">
                                                    <label for="search" class="form-label">Search</label>
                                                    <input type="text" class="form-control" id="search" name="search" 
                                                        placeholder="File #, Consignee, BL #..." value="<?php echo htmlspecialchars($search); ?>">
                                                </div>
                                                
                                                <div class="col-md-3 mb-3">
                                                    <label for="file_type" class="form-label">File Type</label>
                                                    <select class="form-select" id="file_type" name="file_type">
                                                        <option value="all" <?php echo $file_type == 'all' ? 'selected' : ''; ?>>All Files</option>
                                                        <option value="1" <?php echo $file_type == '1' ? 'selected' : ''; ?>>Local Shipments</option>
                                                        <option value="2" <?php echo $file_type == '2' ? 'selected' : ''; ?>>Transit Shipments</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-3 mb-3">
                                                    <label for="customer_id" class="form-label">Customer</label>
                                                    <select class="form-select select2" id="customer_id" name="customer_id">
                                                        <option value="">All Customers</option>
                                                        <?php foreach ($customers as $customer): ?>
                                                            <option value="<?php echo $customer['customer_id']; ?>" 
                                                                <?php echo $customer_id == $customer['customer_id'] ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars($customer['first_name']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-3 mb-3">
                                                    <label for="destination" class="form-label">Destination</label>
                                                    <select class="form-select select2" id="destination" name="destination">
                                                        <option value="">All Destinations</option>
                                                        <?php foreach ($destinations as $dest): ?>
                                                            <option value="<?php echo $dest; ?>" 
                                                                <?php echo $destination == $dest ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars($dest); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-3 mb-3">
                                                    <label for="date_from" class="form-label">Date From</label>
                                                    <input type="date" class="form-control" id="date_from" name="date_from" 
                                                        value="<?php echo $date_from; ?>">
                                                </div>
                                                
                                                <div class="col-md-3 mb-3">
                                                    <label for="date_to" class="form-label">Date To</label>
                                                    <input type="date" class="form-control" id="date_to" name="date_to" 
                                                        value="<?php echo $date_to; ?>">
                                                </div>
                                                
                                                <div class="col-md-6 mb-3 d-flex align-items-end">
                                                    <button type="submit" class="btn btn-primary me-2">
                                                        <i class="ri-search-line"></i> Search
                                                    </button>
                                                    <button type="button" class="btn btn-secondary" id="resetFilters">
                                                        <i class="ri-refresh-line"></i> Reset Filters
                                                    </button>
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                    
                                    <!-- Results Table -->
                                    <div class="table-responsive">
                                        <table id="shipment-files-table" class="table table-bordered dt-responsive nowrap table-striped align-middle">
                                            <thead>
                                                <tr>
                                                    <th>File Number</th>
                                                    <th>Date Created</th>
                                                    <th>Customer</th>
                                                    <th>Consignee</th>
                                                    <th>Destination</th>
                                                    <th>BL Number</th>
                                                    <th>ETA</th>
                                                    <th>Type</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result->num_rows > 0): ?>
                                                    <?php while($row = $result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo htmlspecialchars($row['file_number']); ?></td>
                                                            <td>
                                                                <?php 
                                                                    $date = new DateTime($row['created_date']);
                                                                    echo $date->format('Y-m-d'); 
                                                                ?>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($row['customer_name'] ?? 'N/A'); ?></td>
                                                            <td><?php echo htmlspecialchars($row['consignee_name']); ?></td>
                                                            <td><?php echo htmlspecialchars($row['destination'] ?? 'N/A'); ?></td>
                                                            <td><?php echo htmlspecialchars($row['obl_no'] ?? 'N/A'); ?></td>
                                                            <td>
                                                                <?php 
                                                                    if (!empty($row['eta'])) {
                                                                        $eta_date = new DateTime($row['eta']);
                                                                        echo $eta_date->format('Y-m-d');
                                                                    } else {
                                                                        echo 'N/A';
                                                                    }
                                                                ?>
                                                            </td>
                                                            <td>
                                                                <?php if ($row['file_type'] == 1): ?>
                                                                    <span class="badge badge-local">Local</span>
                                                                <?php else: ?>
                                                                    <span class="badge badge-transit">Transit</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td class="file-actions">
                                                                <a href="view_file.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-info">
                                                                    <i class="ri-eye-line"></i>
                                                                </a>
                                                                <a href="edit_file.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-primary">
                                                                    <i class="ri-edit-box-line"></i>
                                                                </a>
                                                                <button type="button" class="btn btn-sm btn-danger delete-file" 
                                                                    data-file-id="<?php echo $row['id']; ?>" 
                                                                    data-file-number="<?php echo htmlspecialchars($row['file_number']); ?>">
                                                                    <i class="ri-delete-bin-line"></i>
                                                                </button>
                                                                <?php if ($row['c_type'] == 'Bulk Cargo' || $row['c_type'] == 'Loose Cargo'): ?>
                                                                    <?php if ($row['trucks_remaining'] > 0): ?>
                                                                        <a href="update_truck_assignment.php?file_number=<?php echo urlencode($row['file_number']); ?>" 
                                                                           class="btn btn-sm btn-primary">
                                                                            <i class="ri-truck-line"></i> Assign Trucks
                                                                        </a>
                                                                    <?php endif; ?>
                                                                <?php endif; ?>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="9" class="text-center">No shipment files found</td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

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

    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteFileModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-light p-3">
                    <h5 class="modal-title">Confirm Delete</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to delete shipment file <strong id="fileNumberToDelete"></strong>?</p>
                    <p class="text-danger"><strong>Warning:</strong> This action cannot be undone.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                    <form id="deleteFileForm" method="POST" action="delete_file.php">
                        <input type="hidden" name="file_id" id="fileIdToDelete">
                        <button type="submit" class="btn btn-danger">Delete File</button>
                    </form>
                </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>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/responsive.bootstrap5.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 DataTable
            var fileTable = $('#shipment-files-table').DataTable({
                dom: 'Bfrtip',
                buttons: [
                    {
                        extend: 'csv',
                        text: '<i class="ri-file-download-line"></i> Export CSV',
                        className: 'btn btn-sm btn-primary'
                    },
                    {
                        extend: 'excel',
                        text: '<i class="ri-file-excel-line"></i> Export Excel',
                        className: 'btn btn-sm btn-success'
                    },
                    {
                        extend: 'print',
                        text: '<i class="ri-printer-line"></i> Print',
                        className: 'btn btn-sm btn-info'
                    },
                ],
                responsive: true,
                lengthChange: true,
                autoWidth: false,
                pageLength: 25
            });
            
            // Initialize Select2
            $('.select2').select2();
            
            // Reset filters
            $('#resetFilters').on('click', function() {
                $('#search').val('');
                $('#file_type').val('all');
                $('#customer_id').val('').trigger('change');
                $('#destination').val('').trigger('change');
                $('#date_from').val('');
                $('#date_to').val('');
                $('#searchForm').submit();
            });
            
            // Handle delete buttons
            $('.delete-file').on('click', function() {
                const fileId = $(this).data('file-id');
                const fileNumber = $(this).data('file-number');
                
                $('#fileIdToDelete').val(fileId);
                $('#fileNumberToDelete').text(fileNumber);
                
                const deleteModal = new bootstrap.Modal(document.getElementById('deleteFileModal'));
                deleteModal.show();
            });
        });
    </script>
</body>
</html>