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

$booking = $shipment->booking ?? null;

$trackingNo = $shipment->tracking_no ?? '-';
$status = $shipment->status ?? 'In Progress';
$airline = $shipment->airline ?? $shipment->carrier ?? 'N/A';

$senderAddress = $booking->shipper_address ?? '-';
$receiverAddress = $booking->delivery_address ?? '-';

$receiverEmail = $booking->receiver_email ?? '';
$receiverName = $booking->receiver_name ?? 'Customer';

$bookingRef = $booking->booking_reference ?? '-';

$createdDate = $booking->created ?? $shipment->created ?? null;
$pickupDate = $shipment->pickup_date ?? $booking->pickup_date ?? null;
$expectedDate = $shipment->expected_arrived ?? $booking->delivery_deadline ?? null;

function thDate($date, $withTime = true) {
    if (empty($date)) return '-';
    if (is_object($date) && method_exists($date, 'format')) {
        return $date->format($withTime ? 'd M Y h:i A' : 'd M Y');
    }
    return h((string)$date);
}

function totalTimeText($start, $end) {
    if (empty($start) || empty($end) || !is_object($start) || !is_object($end)) {
        return '-';
    }

    $seconds = abs($end->getTimestamp() - $start->getTimestamp());
    $days = floor($seconds / 86400);
    $hours = floor(($seconds % 86400) / 3600);

    if ($days > 0) {
        return $days . ' days, ' . $hours . ' hours';
    }

    return $hours . ' hours';
}

$totalTime = totalTimeText($pickupDate, $expectedDate);
$created = thDate($createdDate, false);
$pickup = thDate($pickupDate, true);
$expected = thDate($expectedDate, true);

$lastLocation = trim((string)($shipment->last_location ?? ''));
?>

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>

<style>
.tracking-history-page {
    padding: 32px;
}

.tracking-card {
    background: #fff;
    border: 1px solid #e5eaf3;
    border-radius: 18px;
    overflow: hidden;
    box-shadow: 0 8px 26px rgba(15, 23, 42, 0.05);
    display: grid;
    grid-template-columns: 1.15fr 0.85fr;
    min-height: 760px;
}

.tracking-left {
    padding: 34px 42px;
    background: #fff;
    overflow-y: auto;
}

.tracking-map {
    position: relative;
    background: #eef2f7;
    border-left: 1px solid #e5eaf3;
    min-height: 760px;
}

#realMap {
    width: 100%;
    height: 100%;
    min-height: 760px;
}

.header-row {
    display: flex;
    align-items: center;
    gap: 14px;
    margin-bottom: 8px;
}

.back-circle {
    width: 42px;
    height: 42px;
    border-radius: 50%;
    background: #f1f5f9;
    color: #334155;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    text-decoration: none;
}

.tracking-title {
    margin: 0;
    font-size: 1.55rem;
    font-weight: 650;
    color: #111827;
}

.status-badge {
    padding: 5px 11px;
    border-radius: 8px;
    background: #eef2ff;
    color: #3155c8;
    font-size: 0.78rem;
    font-weight: 500;
}

.meta {
    color: #64748b;
    font-size: 0.9rem;
    margin-left: 56px;
    margin-bottom: 30px;
}

.meta a {
    color: #111827;
    font-weight: 600;
}

.action-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 26px;
}

.cancel-link {
    color: #111827;
    font-weight: 500;
    font-size: 0.88rem;
    text-decoration: underline;
}

.notify-group {
    display: flex;
    gap: 10px;
    align-items: center;
}

.message-btn {
    height: 40px;
    width: 40px;
    border: 1px solid #e5e7eb;
    background: #fff;
    border-radius: 9px;
    color: #334155;
}

.notify-btn {
    height: 40px;
    border: none;
    border-radius: 9px;
    background: #2563eb;
    color: #fff;
    padding: 0 18px;
    font-size: 0.9rem;
    font-weight: 500;
}

.route-card {
    border: 1px solid #e5eaf3;
    border-radius: 14px;
    overflow: hidden;
    margin-bottom: 26px;
}

.route-address {
    padding: 17px 22px;
    background: #f8fafc;
    line-height: 1.8;
}

.route-address div {
    display: flex;
    gap: 12px;
    align-items: center;
    color: #334155;
    font-size: 0.92rem;
    font-weight: 500;
}

.address-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #64748b;
}

.progress-box {
    padding: 24px 18px;
    display: flex;
    justify-content: center;
}

.progress-event {
    display: flex;
    align-items: center;
    width: 100%;
    max-width: 560px;
}

.progress-dot {
    width: 42px;
    height: 42px;
    border-radius: 50%;
    background: #e5e7eb;
    color: #94a3b8;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    flex: 0 0 42px;
    z-index: 2;
}

.progress-dot.active {
    background: #0f172a;
    color: #fff;
}

.progress-track {
    flex: 1;
    height: 4px;
    background: #e5e7eb;
}

.progress-track.active {
    background: #0f172a;
}

.time-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 24px;
    margin-bottom: 26px;
}

.time-label {
    color: #64748b;
    font-size: 0.8rem;
    font-weight: 500;
    margin-bottom: 7px;
}

.time-value {
    color: #111827;
    font-size: 0.95rem;
    font-weight: 600;
    line-height: 1.45;
}

.delay-box {
    background: #fee2e2;
    border-radius: 10px;
    padding: 15px 17px;
    color: #7f1d1d;
    font-size: 0.88rem;
    line-height: 1.5;
    margin-bottom: 34px;
}

.history-title {
    font-size: 1.08rem;
    font-weight: 650;
    color: #111827;
    margin-bottom: 22px;
}

.status-list {
    position: relative;
    padding-left: 28px;
}

.status-item {
    position: relative;
    margin-bottom: 24px;
}

.status-item::before {
    content: "";
    position: absolute;
    left: -21px;
    top: 8px;
    bottom: -28px;
    width: 2px;
    background: #d1d5db;
}

.status-item:last-child::before {
    display: none;
}

.status-item::after {
    content: "";
    position: absolute;
    left: -25px;
    top: 4px;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background: #64748b;
}

.status-main {
    font-weight: 650;
    color: #111827;
    font-size: 0.94rem;
}

.status-date {
    color: #94a3b8;
    margin-left: 10px;
    font-weight: 400;
}

.status-desc {
    color: #64748b;
    margin-top: 5px;
    font-size: 0.88rem;
}

.status-location {
    color: #94a3b8;
    font-size: 0.82rem;
    margin-top: 5px;
}

.notify-overlay {
    position: fixed;
    inset: 0;
    background: rgba(15, 23, 42, 0.65);
    display: none;
    justify-content: flex-end;
    z-index: 9999;
}

.notify-overlay.show {
    display: flex;
}

.notify-panel {
    width: 560px;
    height: 100%;
    background: #fff;
    padding: 24px 28px;
    box-shadow: -20px 0 50px rgba(15, 23, 42, 0.22);
    overflow-y: auto;
}

.notify-head {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20px;
}

.notify-title {
    display: flex;
    gap: 12px;
    align-items: center;
}

.notify-title span:last-child {
    font-size: 1.15rem;
    font-weight: 650;
}

.close-btn {
    border: none;
    background: #fff;
    font-size: 1.35rem;
}

.email-row {
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    overflow: hidden;
    margin-bottom: 12px;
}

.email-line {
    display: grid;
    grid-template-columns: 80px 1fr 80px;
    border-bottom: 1px solid #e5e7eb;
    padding: 10px 14px;
    font-size: 0.88rem;
}

.email-line:last-child {
    border-bottom: none;
}

.template-select {
    width: 100%;
    height: 42px;
    border: 1px solid #111827;
    border-radius: 8px;
    padding: 0 12px;
    margin-bottom: 12px;
}

.email-body {
    width: 100%;
    min-height: 280px;
    border: 1px solid #111827;
    border-radius: 8px;
    padding: 14px;
    font-size: 0.92rem;
}

.email-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 16px;
}

.preview-btn,
.send-btn {
    height: 40px;
    padding: 0 16px;
    border-radius: 8px;
    font-size: 0.9rem;
    font-weight: 500;
}

.preview-btn {
    background: #fff;
    border: 1px solid #d1d5db;
}

.send-btn {
    background: #2563eb;
    color: #fff;
    border: none;
}

@media (max-width: 1200px) {
    .tracking-card {
        grid-template-columns: 1fr;
    }

    .tracking-map,
    #realMap {
        min-height: 420px;
    }
}
</style>

<div class="tracking-history-page">
    <div class="tracking-card">

        <div class="tracking-left">
            <div class="header-row">
                <a class="back-circle" href="<?= $this->Url->build(['action' => 'view', $shipment->id]) ?>">
                    <i class="bi bi-chevron-left"></i>
                </a>

                <h1 class="tracking-title"><?= h($trackingNo) ?></h1>
                <span class="status-badge"><?= h($status) ?></span>
            </div>

            <div class="meta">
                Shipping date <?= h($created) ?> · Order ID
                <a href="#"><?= h($bookingRef) ?></a>
            </div>

            <div class="action-row">
                <a href="<?= $this->Url->build(['prefix' => 'Admin', 'controller' => 'BookingManagement', 'action' => 'view', $booking->id ?? 0]) ?>" class="cancel-link">
                    Cancel Booking
                </a>

                <div class="notify-group">
                    <button class="message-btn"><i class="bi bi-chat-square-dots"></i></button>
                    <button class="notify-btn" type="button" onclick="openNotify()">Notify Customer</button>
                </div>
            </div>

            <div class="route-card">
                <div class="route-address">
                    <div><span class="address-dot"></span> <?= h($senderAddress) ?></div>
                    <div><span class="address-dot"></span> <?= h($receiverAddress) ?></div>
                </div>

                <div class="progress-box">
                    <div class="progress-event">
                        <span class="progress-dot active"><i class="bi bi-calendar-check"></i></span>
                        <span class="progress-track active"></span>
                        <span class="progress-dot active"><i class="bi bi-box-seam"></i></span>
                        <span class="progress-track <?= in_array($status, ['In Transit', 'Out for Delivery', 'Delivered', 'Arrived']) ? 'active' : '' ?>"></span>
                        <span class="progress-dot <?= in_array($status, ['In Transit', 'Out for Delivery', 'Delivered', 'Arrived']) ? 'active' : '' ?>"><i class="bi bi-truck"></i></span>
                        <span class="progress-track <?= in_array($status, ['Delivered', 'Arrived']) ? 'active' : '' ?>"></span>
                        <span class="progress-dot <?= in_array($status, ['Delivered', 'Arrived']) ? 'active' : '' ?>"><i class="bi bi-geo-alt"></i></span>
                    </div>
                </div>
            </div>

            <div class="time-grid">
                <div>
                    <div class="time-label">Total Time</div>
                    <div class="time-value"><?= h($totalTime) ?></div>
                </div>

                <div>
                    <div class="time-label">Departure Time</div>
                    <div class="time-value"><?= h($pickup) ?></div>
                </div>

                <div>
                    <div class="time-label">Expected Arrived</div>
                    <div class="time-value"><?= h($expected) ?></div>
                </div>
            </div>

            <div class="delay-box">
                <i class="bi bi-exclamation-circle me-2"></i>
                High volume. During peak seasons, there can be a significant increase in packages being shipped, leading to delays.
            </div>

            <div class="history-title">Shipment Status</div>

            <div class="status-list">
                <div class="status-item">
                    <div class="status-main">
                        Order Placed
                        <span class="status-date"><?= h(thDate($createdDate, true)) ?></span>
                    </div>
                    <div class="status-desc">Shipment information received by seller</div>
                    <?php if (!empty($senderAddress) && $senderAddress !== '-'): ?>
                        <div class="status-location"><i class="bi bi-geo-alt"></i> <?= h($senderAddress) ?></div>
                    <?php endif; ?>
                </div>

                <div class="status-item">
                    <div class="status-main">
                        Preparing to Ship
                        <span class="status-date"><?= h(thDate($shipment->created ?? null, true)) ?></span>
                    </div>
                    <div class="status-desc">Seller is preparing to ship your order</div>
                </div>

                <div class="status-item">
                    <div class="status-main">
                        Confirm Shipment
                        <span class="status-date"><?= h(thDate($shipment->last_api_sync ?? $shipment->modified ?? null, true)) ?></span>
                    </div>
                    <div class="status-desc"><?= h($shipment->shipment_event ?? 'Shipment information received by carrier') ?></div>
                </div>

                <div class="status-item">
                    <div class="status-main">
                        <?= h($status) ?>
                        <span class="status-date"><?= h($expected) ?></span>
                    </div>
                    <div class="status-desc">Current shipment status updated by admin</div>

                    <?php if ($lastLocation !== ''): ?>
                        <div class="status-location"><i class="bi bi-geo-alt"></i> <?= h($lastLocation) ?></div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div class="tracking-map">
            <div id="realMap"></div>
        </div>

    </div>
</div>

<div id="notifyOverlay" class="notify-overlay">
    <div class="notify-panel">
        <div class="notify-head">
            <div>
                <div class="notify-title">
                    <span>✉️</span>
                    <span>Notify Email</span>
                </div>
                <div style="color:#64748b; margin-left:42px; font-size:.88rem;">
                    We have an update on your recent shipment.
                </div>
            </div>

            <button class="close-btn" onclick="closeNotify()">×</button>
        </div>

        <div class="email-row">
            <div class="email-line">
                <div>To</div>
                <div><?= h($receiverEmail) ?></div>
                <div style="color:#94a3b8;">Cc Bcc</div>
            </div>

            <div class="email-line">
                <div>Subject</div>
                <div>Quick Update on Your Shipment <?= h($trackingNo) ?></div>
                <div style="color:#94a3b8;">120</div>
            </div>
        </div>

        <select class="template-select" onchange="applyTemplate(this.value)">
            <option value="">Template email</option>
            <option value="important">Important Update Regarding Your Order</option>
            <option value="delayed">Order delayed</option>
            <option value="delay_notice">Notification of Delay</option>
            <option value="arrival">Order Arrival Notification</option>
        </select>

        <textarea id="emailBody" class="email-body">Hi <?= h($receiverName) ?>,

Your shipment <?= h($trackingNo) ?> is currently marked as "<?= h($status) ?>".

Latest update: <?= h($shipment->shipment_event ?? 'Shipment status has been updated.') ?>

Thank you,
Impeccable Courier</textarea>

        <div class="email-actions">
            <button class="preview-btn" type="button">Preview Email</button>
            <button class="send-btn" type="button">Send Email</button>
        </div>
    </div>
</div>

<script>
const senderAddress = <?= json_encode($senderAddress) ?>;
const receiverAddress = <?= json_encode($receiverAddress) ?>;

const map = L.map('realMap', {
    zoomControl: true
}).setView([-25.2744, 133.7751], 4);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: ''
}).addTo(map);

async function geocode(address) {
    if (!address || address === '-') return null;

    const url = 'https://nominatim.openstreetmap.org/search?format=json&limit=1&q=' + encodeURIComponent(address);

    try {
        const res = await fetch(url);
        const data = await res.json();

        if (data && data.length > 0) {
            return [parseFloat(data[0].lat), parseFloat(data[0].lon)];
        }
    } catch (e) {
        console.log(e);
    }

    return null;
}

(async function drawRoute() {
    const from = await geocode(senderAddress);
    const to = await geocode(receiverAddress);

    if (from) {
        L.marker(from).addTo(map).bindPopup('Origin: ' + senderAddress);
    }

    if (to) {
        L.marker(to).addTo(map).bindPopup('Destination: ' + receiverAddress);
    }

    if (from && to) {
        const route = L.polyline([from, to], {
            color: '#f97316',
            weight: 3,
            dashArray: '8, 8'
        }).addTo(map);

        map.fitBounds(route.getBounds(), {
            padding: [60, 60]
        });
    } else if (from) {
        map.setView(from, 11);
    } else if (to) {
        map.setView(to, 11);
    }
})();

function openNotify() {
    document.getElementById('notifyOverlay').classList.add('show');
}

function closeNotify() {
    document.getElementById('notifyOverlay').classList.remove('show');
}

function applyTemplate(value) {
    const body = document.getElementById('emailBody');

    if (value === 'delayed') {
        body.value = `Hi <?= h($receiverName) ?>,

We want to let you know that your shipment <?= h($trackingNo) ?> may be delayed.

We apologise for the inconvenience and will update you as soon as there is a new tracking update.

Thank you,
Impeccable Courier`;
    }

    if (value === 'arrival') {
        body.value = `Hi <?= h($receiverName) ?>,

Good news. Your shipment <?= h($trackingNo) ?> is expected to arrive soon.

Please keep your phone available for delivery contact.

Thank you,
Impeccable Courier`;
    }

    if (value === 'important') {
        body.value = `Hi <?= h($receiverName) ?>,

There is an important update for your shipment <?= h($trackingNo) ?>.

Current status: <?= h($status) ?>

Thank you,
Impeccable Courier`;
    }
}
</script>

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