<?php
$this->assign('title', 'Shipments');

function shipmentStatusClass(string $status): string {
    return match ($status) {
        'Delivered', 'Arrived' => 'status-arrived',
        'In Transit', 'In Progress', 'Out for Delivery' => 'status-progress',
        'Delayed' => 'status-delayed',
        'Cancelled', 'Returned' => 'status-cancelled',
        default => 'status-draft',
    };
}

function eventStep(string $status): int {
    return match ($status) {
        'Approved', 'Booked', 'Pending' => 1,
        'Picked Up', 'Collected at Depot' => 2,
        'In Transit', 'In Progress', 'Out for Delivery', 'Delayed' => 3,
        'Delivered', 'Arrived' => 4,
        default => 1,
    };
}
?>

<style>
.shipment-shell {
    background:#fff;
    border:1px solid #e5e7eb;
    border-radius:18px;
    overflow:hidden;
    box-shadow:0 8px 26px rgba(15,23,42,.05);
}

.shipment-header {
    padding:22px 26px;
    border-bottom:1px solid #eef2f7;
}

.shipment-title {
    margin:0;
    font-size:1.45rem;
    font-weight:600;
    color:#1e293b;
}

.shipment-subtitle {
    margin-top:6px;
    color:#64748b;
    font-size:.92rem;
    font-weight:400;
}

.shipment-filter {
    padding: 18px 22px;
    border-bottom: 1px solid #eef2f7;
    overflow-x: auto;
}

.filter-line {
    display: flex;
    align-items: center;
    gap: 10px;
    min-width: 1420px;
    flex-wrap: nowrap;
}

.filter-control {
    height:44px;
    border-radius:8px!important;
    border:1px solid #d8dee9!important;
    font-size:.9rem;
    font-weight:400;
    color:#334155;
    box-shadow:none!important;
}

.search-wrap {
    position: relative;
    width: 340px;
    flex: 0 0 340px;
}


.search-wrap input {
    padding-right:42px;
}

.search-wrap i {
    position:absolute;
    right:15px;
    top:50%;
    transform:translateY(-50%);
    color:#64748b;
}

.filter-select { width:160px; flex:0 0 160px; }
.filter-service { width:190px; flex:0 0 190px; }
.filter-airline { width:210px; flex:0 0 210px; }

.date-wrap {
    position:relative;
    width:165px;
    flex:0 0 165px;
}

.date-wrap input[type="date"] {
    color:transparent;
    padding-right:34px;
}

.date-wrap.has-value input[type="date"] {
    color:#334155;
}

.date-placeholder {
    position:absolute;
    left:14px;
    top:50%;
    transform:translateY(-50%);
    color:#64748b;
    font-size:.9rem;
    font-weight:400;
    pointer-events:none;
}

.date-wrap.has-value .date-placeholder {
    display:none;
}

.date-wrap i {
    position:absolute;
    right:13px;
    top:50%;
    transform:translateY(-50%);
    color:#334155;
    pointer-events:none;
}

.icon-btn,
.archive-btn {
    height: 44px;
    border-radius: 8px;
    border: 1px solid #d8dee9;
    background: #fff;
    color: #64748b;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    text-decoration: none;
    font-weight: 500;
    white-space: nowrap;
}

.icon-btn {
    width: 48px;
    flex: 0 0 48px;
    padding: 0;
    font-size: 1rem;
}

.archive-btn {
    height: 44px;
    width: auto;
    flex: 0 0 auto;
    padding: 0 16px;
    gap: 8px;
    font-size: .9rem;
    color: #334155;
}

.shipment-table-wrap {
    overflow-x:auto;
}

.shipment-table {
    margin: 0;
    min-width: 1480px;
    table-layout: fixed;
}

.shipment-table th,
.shipment-table td {
    vertical-align:middle;
    text-align:center;
}

.shipment-table th {
    background: #f8fafc;
    color: #334155;
    font-size: .78rem;
    font-weight: 600;
    padding: 14px 14px;
    white-space: nowrap;
    border-bottom: 1px solid #e5e7eb;
}

.shipment-table td {
    padding: 15px 14px;
    border-bottom: 1px solid #f1f5f9;
    font-size: .87rem;
    font-weight: 400;
    color: #334155;
}

.shipment-table th:nth-child(1),
.shipment-table td:nth-child(1) {
    width: 200px;
    text-align: left;
    padding-left: 22px;
}

.shipment-table th:nth-child(2),
.shipment-table td:nth-child(2) {
    width: 205px;
    text-align: left;
    padding-left: 18px;
}

.shipment-table th:nth-child(3),
.shipment-table td:nth-child(3) {
    width: 170px;
    text-align: left;
    padding-left: 18px;
}

.shipment-table th:nth-child(4),
.shipment-table td:nth-child(4) { width: 210px; }

.shipment-table th:nth-child(5),
.shipment-table td:nth-child(5) { width: 125px; }

.shipment-table th:nth-child(6),
.shipment-table td:nth-child(6) { width: 115px; }

.shipment-table th:nth-child(7),
.shipment-table td:nth-child(7) { width: 140px; }

.shipment-table th:nth-child(8),
.shipment-table td:nth-child(8) { width: 135px; }

.shipment-table th:nth-child(9),
.shipment-table td:nth-child(9) { width: 80px; }


.tracking-link {
    color:#2563eb;
    font-weight:550;
    text-decoration:none;
    white-space:nowrap;
}

.main-text {
    font-weight:500;
    color:#111827;
    line-height:1.35;
    white-space:nowrap;
}

.mini-text {
    color:#64748b;
    font-size:.8rem;
    margin-top:3px;
    font-weight:400;
    line-height:1.3;
    white-space:nowrap;
}

.event-line {
    display:flex;
    align-items:center;
    justify-content:center;
    gap:6px;
}

.event-dot {
    width:21px;
    height:21px;
    border-radius:50%;
    background:#e5e7eb;
    color:#9ca3af;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    font-size:.6rem;
    flex:0 0 21px;
}

.event-track {
    width:44px;
    height:3px;
    background:#e5e7eb;
    border-radius:999px;
}

.event-line.step-1 .dot-1,
.event-line.step-2 .dot-1,
.event-line.step-2 .dot-2,
.event-line.step-3 .dot-1,
.event-line.step-3 .dot-2,
.event-line.step-3 .dot-3,
.event-line.step-4 .dot-1,
.event-line.step-4 .dot-2,
.event-line.step-4 .dot-3,
.event-line.step-4 .dot-4 {
    background:#0f172a;
    color:#fff;
}

.event-line.step-2 .track-1,
.event-line.step-3 .track-1,
.event-line.step-3 .track-2,
.event-line.step-4 .track-1,
.event-line.step-4 .track-2,
.event-line.step-4 .track-3 {
    background:#0f172a;
}

.status-pill {
    display:inline-flex;
    align-items:center;
    justify-content:center;
    padding:5px 12px;
    border-radius:8px;
    font-size:.78rem;
    font-weight:550;
    white-space:nowrap;
}

.status-progress { background:#eef2ff; color:#3155c8; }
.status-arrived { background:#dcfce7; color:#15803d; }
.status-delayed { background:#ffedd5; color:#c2410c; }
.status-cancelled { background:#fee2e2; color:#b91c1c; }
.status-draft { background:#f1f5f9; color:#64748b; }

.action-dropdown {
    position:relative;
    display:inline-block;
}

.action-toggle {
    width:36px;
    height:34px;
    border:1px solid #d8dee9;
    background:#fff;
    border-radius:8px;
    color:#334155;
}

.action-menu {
    position:absolute;
    right:0;
    top:40px;
    width:165px;
    background:#fff;
    border:1px solid #e5e7eb;
    border-radius:14px;
    box-shadow:0 16px 36px rgba(15,23,42,.12);
    padding:8px;
    display:none;
    z-index:99;
    text-align:left;
}

.action-menu.show {
    display:block;
}

.action-menu a,
.action-menu button {
    width:100%;
    border:0;
    background:transparent;
    display:flex;
    gap:9px;
    align-items:center;
    padding:10px 11px;
    border-radius:10px;
    text-decoration:none;
    color:#334155;
    font-size:.88rem;
    font-weight:500;
}

.action-menu a:hover,
.action-menu button:hover {
    background:#f8fafc;
}

.delete-item {
    color:#dc2626!important;
}

.empty-state {
    padding:45px;
    text-align:center;
    color:#64748b;
}

.tracking-link {
    color: #2563eb; /* normal blue */
    font-weight: 600;
    text-decoration: none;
    transition: all 0.2s ease;
}

/* HOVER EFFECT */
.tracking-link:hover {
    color: #1e40af; /* darker blue */
    text-decoration: underline;
}

</style>

<div class="shipment-shell">
    <div class="shipment-header">
        <h1 class="shipment-title">
            <?= $showArchived ? 'Archived Shipments' : 'Shipment List' ?>
        </h1>
        <div class="shipment-subtitle">View and manage all shipments.</div>
    </div>

    <div class="shipment-filter">
        <?= $this->Form->create(null, ['type' => 'get']) ?>

        <?php if ($showArchived): ?>
            <?= $this->Form->hidden('archived', ['value' => 1]) ?>
        <?php endif; ?>

        <div class="filter-line">
            <div class="search-wrap">
                <?= $this->Form->control('q', [
                    'label' => false,
                    'value' => $search,
                    'placeholder' => 'Search by Tracking No., Booking ID, Customer...',
                    'class' => 'form-control filter-control'
                ]) ?>
                <i class="bi bi-search"></i>
            </div>

            <?= $this->Form->control('status', [
                'label' => false,
                'empty' => 'All Status',
                'options' => array_combine($statusOptions, $statusOptions),
                'value' => $status,
                'class' => 'form-select filter-control filter-select'
            ]) ?>

            <?= $this->Form->control('service', [
                'label' => false,
                'empty' => 'All Services',
                'options' => $serviceOptions,
                'value' => $service,
                'class' => 'form-select filter-control filter-service'
            ]) ?>

            <?= $this->Form->control('airline', [
                'label' => false,
                'empty' => 'All Airlines',
                'options' => array_combine($airlineOptions, $airlineOptions),
                'value' => $airline,
                'class' => 'form-select filter-control filter-airline'
            ]) ?>

            <div class="date-wrap <?= !empty($fromDate) ? 'has-value' : '' ?>">
                <?= $this->Form->control('from_date', [
                    'label' => false,
                    'type' => 'date',
                    'value' => $fromDate,
                    'class' => 'form-control filter-control js-date-input'
                ]) ?>
                <span class="date-placeholder">From Date</span>
                <i class="bi bi-calendar3"></i>
            </div>

            <div class="date-wrap <?= !empty($toDate) ? 'has-value' : '' ?>">
                <?= $this->Form->control('to_date', [
                    'label' => false,
                    'type' => 'date',
                    'value' => $toDate,
                    'class' => 'form-control filter-control js-date-input'
                ]) ?>
                <span class="date-placeholder">To Date</span>
                <i class="bi bi-calendar3"></i>
            </div>

            <button class="icon-btn" type="submit" title="Filter">
                <i class="bi bi-sliders"></i>
            </button>

            <a class="icon-btn" href="<?= $this->Url->build(['action' => 'index']) ?>" title="Reset">
                <i class="bi bi-arrow-clockwise"></i>
            </a>

            <a class="archive-btn" href="<?= $this->Url->build(['action' => 'index', '?' => ['archived' => 1]]) ?>">
                <i class="bi bi-archive"></i>
                Archived Shipments
            </a>
        </div>

        <?= $this->Form->end() ?>
    </div>

    <div class="shipment-table-wrap">
        <table class="table shipment-table align-middle">
            <thead>
                <tr>
                    <th>Tracking No</th>
                    <th>Booking ID</th>
                    <th>Customer</th>
                    <th>Shipment Event</th>
                    <th>Status</th>
                    <th>Airline</th>
                    <th>Expected Arrived</th>
                    <th>Pickup Date</th>
                    <th>Action</th>
                </tr>
            </thead>

            <tbody>
            <?php if (!$shipments->isEmpty()): ?>
                <?php foreach ($shipments as $shipment): ?>
                    <?php
                    $pickupDate = $shipment->pickup_date ?? $shipment->booking->pickup_date ?? null;
                    $expectedArrived = $shipment->expected_arrived ?? $shipment->booking->delivery_deadline ?? null;
                    $step = eventStep((string)($shipment->status ?? 'Approved'));
                    ?>
                    <tr>
                        <td>
                            <a class="tracking-link" href="<?= $this->Url->build(['action' => 'trackingHistory', $shipment->id]) ?>">
    <?= h($shipment->tracking_no) ?>
</a>
                        </td>

                        <td>
                            <div class="main-text"><?= h($shipment->booking->booking_reference ?? '-') ?></div>
                        </td>

                        <td>
                            <div class="main-text"><?= h($shipment->booking->shipper_name ?? '-') ?></div>
                            <div class="mini-text"><?= h($shipment->booking->shipper_phone ?? '-') ?></div>
                        </td>

                        <td>
                            <div class="event-line step-<?= $step ?>">
                                <span class="event-dot dot-1"><i class="bi bi-box-seam"></i></span>
                                <span class="event-track track-1"></span>
                                <span class="event-dot dot-2"><i class="bi bi-building"></i></span>
                                <span class="event-track track-2"></span>
                                <span class="event-dot dot-3"><i class="bi bi-truck"></i></span>
                                <span class="event-track track-3"></span>
                                <span class="event-dot dot-4"><i class="bi bi-geo-alt"></i></span>
                            </div>
                        </td>

                        <td>
                            <span class="status-pill <?= shipmentStatusClass((string)$shipment->status) ?>">
                                <?= h($shipment->status) ?>
                            </span>
                        </td>

                        <td><?= h($shipment->airline ?? $shipment->carrier ?? 'N/A') ?></td>

                        <td>
                            <?= !empty($expectedArrived) ? h($expectedArrived->format('d M Y')) : '-' ?>
                        </td>

                        <td>
                            <?= !empty($pickupDate) ? h($pickupDate->format('d M Y')) : '-' ?>
                        </td>

                        <td>
                            <div class="action-dropdown">
                                <button type="button" class="action-toggle js-action-toggle">
                                    <i class="bi bi-three-dots"></i>
                                </button>

                                <div class="action-menu js-action-menu">
                                    <a href="<?= $this->Url->build(['action' => 'view', $shipment->id]) ?>">
                                        <i class="bi bi-eye"></i> View
                                    </a>

                            

                                    <?php if ($showArchived): ?>
                                        <?= $this->Form->postLink(
                                            '<i class="bi bi-arrow-counterclockwise"></i> Undo Archive',
                                            ['action' => 'unarchive', $shipment->id],
                                            ['escape' => false]
                                        ) ?>
                                    <?php else: ?>
                                        <?= $this->Form->postLink(
                                            '<i class="bi bi-archive"></i> Archive',
                                            ['action' => 'archive', $shipment->id],
                                            ['escape' => false, 'confirm' => 'Archive this shipment?']
                                        ) ?>
                                    <?php endif; ?>

                                    <?= $this->Form->postLink(
                                        '<i class="bi bi-trash"></i> Delete',
                                        ['action' => 'delete', $shipment->id],
                                        [
                                            'escape' => false,
                                            'class' => 'delete-item',
                                            'confirm' => 'Delete this shipment permanently?'
                                        ]
                                    ) ?>
                                </div>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr>
                    <td colspan="9">
                        <div class="empty-state">No shipments found.</div>
                    </td>
                </tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const filterForm = document.querySelector('.shipment-filter form');
    let searchTimer = null;

    function submitFilter() {
        if (filterForm) {
            filterForm.submit();
        }
    }

    document.querySelectorAll('.js-action-toggle').forEach(function (btn) {
        btn.addEventListener('click', function (e) {
            e.stopPropagation();

            const menu = this.parentElement.querySelector('.js-action-menu');

            document.querySelectorAll('.js-action-menu').forEach(function (m) {
                if (m !== menu) {
                    m.classList.remove('show');
                }
            });

            menu.classList.toggle('show');
        });
    });

    document.addEventListener('click', function () {
        document.querySelectorAll('.js-action-menu').forEach(function (menu) {
            menu.classList.remove('show');
        });
    });

    document.querySelectorAll('.shipment-filter select, .shipment-filter input[type="date"]').forEach(function (field) {
        field.addEventListener('change', function () {
            const wrap = this.closest('.date-wrap');

            if (wrap) {
                if (this.value) {
                    wrap.classList.add('has-value');
                } else {
                    wrap.classList.remove('has-value');
                }
            }

            submitFilter();
        });
    });

    const searchInput = document.querySelector('.shipment-filter input[name="q"]');

    if (searchInput) {
        searchInput.addEventListener('input', function () {
            clearTimeout(searchTimer);

            searchTimer = setTimeout(function () {
                submitFilter();
            }, 600);
        });
    }
});
</script>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">