<?php
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

// Get customer ID from URL parameter
$customer_id = isset($_GET['customer']) ? intval($_GET['customer']) : 0;

if ($customer_id <= 0) {
    $_SESSION['error_message'] = "Invalid customer ID";
    header("Location: all_customers.php");
    exit();
}

// Fetch customer data
$query = "SELECT * FROM customers WHERE customer_id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $customer_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_message'] = "Customer not found";
    header("Location: all_customers.php");
    exit();
}

$customer = $result->fetch_assoc();

// Format customer name correctly
$customerName = trim($customer['first_name'] . ' ' . $customer['last_name']);
if (empty($customerName)) {
    $customerName = "Customer #" . $customer_id;
}

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

// Search functionality
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$searchClause = '';
if (!empty($search)) {
    $searchClause = " AND (file_number LIKE ? OR destination LIKE ? OR obl_no LIKE ?)";
}

// Status filter
$status = isset($_GET['status']) ? $_GET['status'] : '';
$statusClause = '';
if ($status === 'active') {
    $statusClause = " AND (close_file IS NULL OR close_file != 'Yes')";
} elseif ($status === 'closed') {
    $statusClause = " AND close_file = 'Yes'";
}

// Type filter
$type = isset($_GET['type']) ? $_GET['type'] : '';
$typeClause = '';
if ($type === 'transit') {
    $typeClause = " AND `local/transit` = 2";
} elseif ($type === 'local') {
    $typeClause = " AND `local/transit` = 1";
}

// Date range filter
$startDate = isset($_GET['start_date']) ? $_GET['start_date'] : '';
$endDate = isset($_GET['end_date']) ? $_GET['end_date'] : '';
$dateClause = '';
if (!empty($startDate) && !empty($endDate)) {
    $dateClause = " AND created_date BETWEEN ? AND ?";
}

// Count total records for pagination
$countQuery = "SELECT COUNT(*) as total FROM files 
               WHERE customer = ?" . $searchClause . $statusClause . $typeClause . $dateClause;
$countStmt = $conn->prepare($countQuery);

// Bind parameters for count query
$paramTypes = "i";
$paramValues = [$customer_id];

if (!empty($search)) {
    $paramTypes .= "sss";
    $searchParam = "%$search%";
    $paramValues[] = $searchParam;
    $paramValues[] = $searchParam;
    $paramValues[] = $searchParam;
}

if (!empty($startDate) && !empty($endDate)) {
    $paramTypes .= "ss";
    $paramValues[] = $startDate . ' 00:00:00';
    $paramValues[] = $endDate . ' 23:59:59';
}

$countStmt->bind_param($paramTypes, ...$paramValues);
$countStmt->execute();
$countResult = $countStmt->get_result();
$countRow = $countResult->fetch_assoc();
$totalRecords = $countRow['total'];
$totalPages = ceil($totalRecords / $recordsPerPage);

// Fetch shipments data
$shipmentsQuery = "SELECT file_number, created_date, destination, obl_no, eta, discharge_date, 
                   `local/transit` as type, close_file, remarks
                   FROM files 
                   WHERE customer = ?" . $searchClause . $statusClause . $typeClause . $dateClause . "
                   ORDER BY created_date DESC
                   LIMIT ? OFFSET ?";

$shipmentsStmt = $conn->prepare($shipmentsQuery);

// Bind parameters for shipments query
$paramTypes .= "ii";
$paramValues[] = $recordsPerPage;
$paramValues[] = $offset;

$shipmentsStmt->bind_param($paramTypes, ...$paramValues);
$shipmentsStmt->execute();
$shipments = $shipmentsStmt->get_result();
?>

<!doctype html>
<html lang="en" data-layout="vertical" data-topbar="light" data-sidebar="dark" data-sidebar-size="lg" data-sidebar-image="none" data-preloader="disable">

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Customer Shipments')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Flatpickr -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <style>
        .customer-avatar {
            width: 64px;
            height: 64px;
            background-color: #5156be;
            color: #fff;
            font-size: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            margin-right: 15px;
        }
        
        .shipment-status {
            height: 10px;
            width: 10px;
            display: inline-block;
            border-radius: 50%;
            margin-right: 5px;
        }
        
        .file-card {
            border-left: 4px solid transparent;
            transition: all 0.3s ease;
        }
        
        .file-card:hover {
            transform: translateX(5px);
            border-left: 4px solid #5156be;
        }
        
        .file-card-transit {
            border-left-color: #299cdb;
        }
        
        .file-card-local {
            border-left-color: #0ab39c;
        }
        
        .file-card-closed {
            border-left-color: #f06548;
        }
    </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' => 'Customer', 'title' => 'Customer Shipments')); ?>

                    <!-- Display success/error messages if they exist -->
                    <?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-12">
                            <div class="card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center mb-4">
                                        <div class="customer-avatar">
                                            <?php echo strtoupper(substr($customerName, 0, 1)); ?>
                                        </div>
                                        <div>
                                            <h4 class="mb-1"><?php echo htmlspecialchars($customerName); ?></h4>
                                            <p class="text-muted mb-0">
                                                <i class="ri-map-pin-line me-1"></i> <?php echo htmlspecialchars($customer['city'] ? $customer['city'] . ', ' : ''); ?><?php echo htmlspecialchars($customer['country'] ?: 'No location specified'); ?>
                                            </p>
                                        </div>
                                        <div class="ms-auto">
                                            <a href="customer_view.php?id=<?php echo $customer_id; ?>" class="btn btn-soft-primary btn-sm">
                                                <i class="ri-user-3-line align-middle me-1"></i> View Profile
                                            </a>
                                            <a href="file_list.php" class="btn btn-primary btn-sm ms-2">
                                                <i class="ri-add-line align-middle me-1"></i> All Shipments
                                            </a>
                                        </div>
                                    </div>

                                    <!-- Filter and Search -->
                                    <div class="row mb-4">
                                        <div class="col-md-12">
                                            <form action="" method="GET" class="row g-3">
                                                <input type="hidden" name="customer" value="<?php echo $customer_id; ?>">
                                                
                                                <div class="col-md-2">
                                                    <div class="search-box">
                                                        <input type="text" name="search" class="form-control search" placeholder="Search..." value="<?php echo htmlspecialchars($search); ?>">
                                                        <i class="ri-search-line search-icon"></i>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-md-2">
                                                    <select class="form-select" name="status">
                                                        <option value="" <?php echo $status === '' ? 'selected' : ''; ?>>All Status</option>
                                                        <option value="active" <?php echo $status === 'active' ? 'selected' : ''; ?>>Active</option>
                                                        <option value="closed" <?php echo $status === 'closed' ? 'selected' : ''; ?>>Closed</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-2">
                                                    <select class="form-select" name="type">
                                                        <option value="" <?php echo $type === '' ? 'selected' : ''; ?>>All Types</option>
                                                        <option value="transit" <?php echo $type === 'transit' ? 'selected' : ''; ?>>Transit</option>
                                                        <option value="local" <?php echo $type === 'local' ? 'selected' : ''; ?>>Local</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-2">
                                                    <input type="text" class="form-control flatpickr-input" name="start_date" id="start_date" placeholder="Start Date" value="<?php echo htmlspecialchars($startDate); ?>">
                                                </div>
                                                
                                                <div class="col-md-2">
                                                    <input type="text" class="form-control flatpickr-input" name="end_date" id="end_date" placeholder="End Date" value="<?php echo htmlspecialchars($endDate); ?>">
                                                </div>
                                                
                                                <div class="col-md-2">
                                                    <button type="submit" class="btn btn-primary w-100">
                                                        <i class="ri-filter-3-line align-bottom me-1"></i> Filter
                                                    </button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>

                                    <?php if ($shipments->num_rows > 0): ?>
                                    <div class="table-responsive">
                                        <table class="table table-hover table-centered align-middle table-nowrap mb-0">
                                            <thead>
                                                <tr>
                                                    <th scope="col">File Number</th>
                                                    <th scope="col">Created Date</th>
                                                    <th scope="col">Destination</th>
                                                    <th scope="col">OBL Number</th>
                                                    <th scope="col">ETA</th>
                                                    <th scope="col">Discharge Date</th>
                                                    <th scope="col">Type</th>
                                                    <th scope="col">Status</th>
                                                    <th scope="col">Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($shipment = $shipments->fetch_assoc()): 
                                                    // Determine shipment type and status
                                                    $shipmentType = ($shipment['type'] == 1) ? "Local" : "Transit";
                                                    $typeClass = ($shipment['type'] == 1) ? "badge-soft-success" : "badge-soft-primary";
                                                    
                                                    // Check if shipment is closed
                                                    $statusClass = ($shipment['close_file'] == 'Yes') ? "badge-soft-danger" : "badge-soft-success";
                                                    $statusText = ($shipment['close_file'] == 'Yes') ? "Closed" : "Active";
                                                    
                                                    // Format the dates
                                                    $createdDate = new DateTime($shipment['created_date']);
                                                    $formattedCreatedDate = $createdDate->format('M d, Y');
                                                    
                                                    $etaDate = !empty($shipment['eta']) ? new DateTime($shipment['eta']) : null;
                                                    $formattedEta = $etaDate ? $etaDate->format('M d, Y') : '-';
                                                    
                                                    $dischargeDate = !empty($shipment['discharge_date']) ? new DateTime($shipment['discharge_date']) : null;
                                                    $formattedDischargeDate = $dischargeDate ? $dischargeDate->format('M d, Y') : '-';
                                                ?>
                                                <tr>
                                                    <td>
                                                        <a href="view_shipment.php?file_number=<?php echo urlencode($shipment['file_number']); ?>" class="fw-medium text-primary">
                                                            <?php echo htmlspecialchars($shipment['file_number']); ?>
                                                        </a>
                                                    </td>
                                                    <td><?php echo $formattedCreatedDate; ?></td>
                                                    <td><?php echo htmlspecialchars($shipment['destination']); ?></td>
                                                    <td><?php echo htmlspecialchars($shipment['obl_no'] ?: '-'); ?></td>
                                                    <td><?php echo $formattedEta; ?></td>
                                                    <td><?php echo $formattedDischargeDate; ?></td>
                                                    <td><span class="badge <?php echo $typeClass; ?>"><?php echo $shipmentType; ?></span></td>
                                                    <td><span class="badge <?php echo $statusClass; ?>"><?php echo $statusText; ?></span></td>
                                                    <td>
                                                        <div class="dropdown">
                                                            <a href="#" class="dropdown-toggle btn btn-light btn-sm" data-bs-toggle="dropdown" aria-expanded="false">
                                                                <i class="ri-more-fill align-middle"></i>
                                                            </a>
                                                            <ul class="dropdown-menu dropdown-menu-end">
                                                                <li>
                                                                    <a class="dropdown-item" href="view_shipment.php?file_number=<?php echo urlencode($shipment['file_number']); ?>">
                                                                        <i class="ri-eye-line align-middle me-1"></i> View Details
                                                                    </a>
                                                                </li>
                                                                <?php if ($shipment['close_file'] != 'Yes'): ?>
                                                                <li>
                                                                    <a class="dropdown-item" href="edit_shipment.php?file_number=<?php echo urlencode($shipment['file_number']); ?>">
                                                                        <i class="ri-pencil-line align-middle me-1"></i> Edit
                                                                    </a>
                                                                </li>
                                                                <li>
                                                                    <a class="dropdown-item" href="close_shipment.php?file_number=<?php echo urlencode($shipment['file_number']); ?>">
                                                                        <i class="ri-check-double-line align-middle me-1"></i> Close Shipment
                                                                    </a>
                                                                </li>
                                                                <?php endif; ?>
                                                                <li>
                                                                    <a class="dropdown-item" href="generate_invoice.php?file_number=<?php echo urlencode($shipment['file_number']); ?>">
                                                                        <i class="ri-file-list-3-line align-middle me-1"></i> Generate Invoice
                                                                    </a>
                                                                </li>
                                                                <li>
                                                                    <a class="dropdown-item" href="print_shipment.php?file_number=<?php echo urlencode($shipment['file_number']); ?>" target="_blank">
                                                                        <i class="ri-printer-line align-middle me-1"></i> Print
                                                                    </a>
                                                                </li>
                                                            </ul>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    
                                    <!-- Pagination -->
                                    <?php if ($totalPages > 1): ?>
                                    <div class="d-flex justify-content-end mt-4">
                                        <nav aria-label="Page navigation">
                                            <ul class="pagination">
                                                <?php if ($page > 1): ?>
                                                <li class="page-item">
                                                    <a class="page-link" href="?customer=<?php echo $customer_id; ?>&page=<?php echo ($page - 1); ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>&type=<?php echo urlencode($type); ?>&start_date=<?php echo urlencode($startDate); ?>&end_date=<?php echo urlencode($endDate); ?>" 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 ($i == $page) ? 'active' : ''; ?>">
                                                    <a class="page-link" href="?customer=<?php echo $customer_id; ?>&page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>&type=<?php echo urlencode($type); ?>&start_date=<?php echo urlencode($startDate); ?>&end_date=<?php echo urlencode($endDate); ?>"><?php echo $i; ?></a>
                                                </li>
                                                <?php endfor; ?>
                                                
                                                <?php if ($page < $totalPages): ?>
                                                <li class="page-item">
                                                    <a class="page-link" href="?customer=<?php echo $customer_id; ?>&page=<?php echo ($page + 1); ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>&type=<?php echo urlencode($type); ?>&start_date=<?php echo urlencode($startDate); ?>&end_date=<?php echo urlencode($endDate); ?>" aria-label="Next">
                                                        <span aria-hidden="true">&raquo;</span>
                                                    </a>
                                                </li>
                                                <?php endif; ?>
                                            </ul>
                                        </nav>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php else: ?>
                                    <div class="text-center p-4">
                                        <div class="avatar-md mx-auto mb-4">
                                            <div class="avatar-title bg-light text-primary rounded-circle">
                                                <i class="ri-file-search-line fs-24"></i>
                                            </div>
                                        </div>
                                        <h5 class="text-primary">No Shipments Found</h5>
                                        <p class="text-muted mb-4">No shipment records found for this customer with the current filters.</p>
                                        
                                        <?php if (!empty($search) || !empty($status) || !empty($type) || !empty($startDate) || !empty($endDate)): ?>
                                        <a href="customer_shipments.php?customer=<?php echo $customer_id; ?>" class="btn btn-soft-primary btn-sm">
                                            <i class="ri-delete-bin-line align-middle me-1"></i> Clear Filters
                                        </a>
                                        <?php endif; ?>
                                        
                                        <a href="file_list.php" class="btn btn-primary btn-sm ms-2">
                                            <i class="ri-add-line align-middle me-1"></i> All Shipments
                                        </a>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </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>
    <!-- Plugins -->
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Initialize date pickers
        flatpickr("#start_date", {
            dateFormat: "Y-m-d",
            maxDate: "today"
        });
        
        flatpickr("#end_date", {
            dateFormat: "Y-m-d",
            maxDate: "today"
        });
    });
    </script>

</body>
</html>