<div class="content-wrapper">
<section class="content pt-3">
<?php
use Core\App\Services\Shipping\EcotrackStatusMapper;
use Core\App\Services\Shipping\ShippingStatusPresenter;
?>
<div class="container-fluid pb-5">

<div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4">
    <div>
        <h3 class="mb-1 fw-bold"><i class="bi bi-truck me-2 text-primary"></i><?= __('shipments.title','My Shipments') ?></h3>
        <p class="text-muted mb-0 small"><?= __('shipments.subtitle','Track all your shipments in one place') ?></p>
    </div>
</div>

<?php if (!empty($stats)): ?>
<div class="row g-3 mb-4">
    <?php
    $sCards=[
        ['val'=>(int)$stats['total'],                              'label'=>__('shipments.stats.total','Total'),       'icon'=>'bi-box-seam',           'color'=>'primary'],
        ['val'=>(int)$stats['in_progress'],                        'label'=>__('shipments.stats.in_progress','In Transit'),'icon'=>'bi-truck',          'color'=>'info'],
        ['val'=>(int)$stats['delivered'],                          'label'=>__('shipments.stats.delivered','Delivered'),'icon'=>'bi-check-circle',      'color'=>'success'],
        ['val'=>(int)($stats['returned']+$stats['cancelled']),     'label'=>__('shipments.stats.issues','Returned/Cancelled'),'icon'=>'bi-exclamation-triangle','color'=>'warning'],
    ];
    foreach($sCards as $c):
    ?>
    <div class="col-6 col-md-3">
        <div class="card border-0 shadow-sm h-100" style="border-top:3px solid var(--bs-<?= $c['color'] ?>) !important">
            <div class="card-body d-flex align-items-center gap-3">
                <div class="rounded-circle d-flex align-items-center justify-content-center flex-shrink-0"
                     style="width:46px;height:46px;background:var(--bs-<?= $c['color'] ?>-bg-subtle,rgba(13,110,253,.1))">
                    <i class="bi <?= $c['icon'] ?> text-<?= $c['color'] ?>"></i>
                </div>
                <div>
                    <div class="fw-bold fs-3 lh-1"><?= $c['val'] ?></div>
                    <div class="text-muted small mt-1"><?= $c['label'] ?></div>
                </div>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<div class="card border-0 shadow-sm">
    <div class="card-header bg-white border-bottom d-flex justify-content-between align-items-center py-3">
        <h6 class="mb-0 fw-semibold"><i class="bi bi-list-ul me-2 text-muted"></i><?= __('shipments.list_title','Shipments List') ?></h6>
        <span class="badge bg-secondary rounded-pill"><?= count($orders??[]) ?></span>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light">
                    <tr>
                        <th class="ps-3"><?= __('shipments.table.order_id','Order') ?></th>
                        <th><?= __('shipments.table.provider','Carrier') ?></th>
                        <th><?= __('shipments.table.tracking','Tracking') ?></th>
                        <th><?= __('shipments.table.status','Status') ?></th>
                        <th><?= __('shipments.table.updated_at','Last Update') ?></th>
                        <th class="text-center pe-3"><?= __('shipments.table.actions','Actions') ?></th>
                    </tr>
                </thead>
                <tbody>
                <?php if(empty($orders)): ?>
                    <tr><td colspan="6" class="text-center py-5">
                        <i class="bi bi-inbox display-4 d-block mb-2 text-muted opacity-50"></i>
                        <p class="text-muted mb-0"><?= __('shipments.empty_title','No shipments yet') ?></p>
                    </td></tr>
                <?php else: foreach($orders as $order):
                    $shipping=$order['extra']['shipping']??[];
                    $status=$shipping['status']??'not_sent';
                    $provider=strtolower($shipping['provider']??'');
                    $tracking=$shipping['tracking']??null;
                    if ($provider === 'maystro') {
                        $meta = ShippingStatusPresenter::meta($provider, $status, isset($shipping['status_code']) ? (int)$shipping['status_code'] : null);
                        $labelFile = $tracking ? ROOT_PATH.'/storage/labels/maystro/'.$tracking.'.pdf' : null;
                    } else {
                        $meta = EcotrackStatusMapper::meta($status);
                        $labelFile = $tracking ? ROOT_PATH.'/storage/labels/ecotrack/'.$tracking.'.pdf' : null;
                    }
                    $badgeCls=$meta['badge'];
                    $labelReady=$labelFile&&file_exists($labelFile);
                    $pvBadge=['ecotrack'=>'bg-primary','zr_express'=>'bg-warning text-dark','yalidine'=>'bg-success','maystro'=>'bg-info text-dark','dhd'=>'bg-secondary'][$provider]??'bg-secondary';
                ?>
                <tr>
                    <td class="ps-3 fw-bold">
                        <a href="/admin/orders/view/<?= (int)$order['id'] ?>" class="text-decoration-none text-primary">#<?= (int)$order['id'] ?></a>
                        <?php if(!empty($order['full_name'])): ?>
                        <div class="text-muted small fw-normal"><?= htmlspecialchars($order['full_name']) ?></div>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if($provider): ?><span class="badge <?= $pvBadge ?>"><?= strtoupper($provider) ?></span>
                        <?php else: ?><span class="text-muted">—</span><?php endif; ?>
                    </td>
                    <td>
                        <?php if($tracking): ?><code class="small bg-light px-2 py-1 rounded"><?= htmlspecialchars($tracking) ?></code>
                        <?php else: ?><span class="text-muted">—</span><?php endif; ?>
                    </td>
                    <td><span class="badge <?= $badgeCls ?>"><?= __($meta['label_key'],$meta['fallback']) ?></span></td>
                    <td class="text-muted small"><?= htmlspecialchars($shipping['last_update_at']??'—') ?></td>
                    <td class="text-center pe-3">
                        <div class="d-flex gap-1 justify-content-center">
                            <?php if($tracking): ?>
                            <a href="/admin/order/tracking?tracking=<?= urlencode($tracking) ?>" class="btn btn-sm btn-outline-primary" title="<?= __('actions.track','Track') ?>"><i class="bi bi-search"></i></a>
                            <?php endif; ?>
                            <?php if($provider==='ecotrack'&&$tracking): ?>
                            <?php if($labelReady): ?>
                            <!-- Cached label: serve directly -->
                            <a href="/admin/orders/ecotrack/label?tracking=<?= urlencode($tracking) ?>" target="_blank" class="btn btn-sm btn-success" title="<?= __('shipping.label_download','Print Label') ?>"><i class="bi bi-printer"></i></a>
                            <?php else: ?>
                            <!-- Fetch live label from Ecotrack API -->
                            <a href="/admin/orders/ecotrack/label?tracking=<?= urlencode($tracking) ?>" target="_blank" class="btn btn-sm btn-outline-success" title="<?= __('shipping.label_fetch','Fetch & Print Label') ?>"><i class="bi bi-printer"></i></a>
                            <?php endif; ?>
                            <button type="button" class="btn btn-sm btn-outline-info" onclick="refreshStatus('<?= htmlspecialchars($tracking) ?>',this)" title="<?= __('actions.refresh','Refresh') ?>"><i class="bi bi-arrow-clockwise"></i></button>
                            <?php endif; ?>
                            <?php if($provider==='maystro'&&$tracking): ?>
                            <a href="/admin/orders/maystro/label/<?= (int)$order['id'] ?>" target="_blank" class="btn btn-sm <?= $labelReady ? 'btn-info' : 'btn-outline-info' ?>" title="<?= __('shipping.print_label','Print Label') ?>"><i class="bi bi-printer"></i></a>
                            <?php endif; ?>
                            <?php if($provider==='zr_express'&&$tracking): ?>
                            <a href="/admin/orders/zr-label/<?= (int)$order['id'] ?>" target="_blank" class="btn btn-sm btn-outline-warning"><i class="bi bi-printer"></i></a>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

</div></section></div>

<script>
function refreshStatus(t,btn){
    btn.disabled=true; btn.innerHTML='<span class="spinner-border spinner-border-sm"></span>';
    fetch('/admin/orders/ecotrack/track?tracking='+encodeURIComponent(t),{headers:{'Accept':'application/json'}})
    .then(r=>r.json()).then(res=>{
        if(res&&res.success){location.reload();}
        else{alert(res.message||'<?= __('shipping.refresh_failed','Failed to refresh') ?>');btn.disabled=false;btn.innerHTML='<i class="bi bi-arrow-clockwise"></i>';}
    }).catch(()=>{alert('<?= __('errors.network','Network error') ?>');btn.disabled=false;btn.innerHTML='<i class="bi bi-arrow-clockwise"></i>';});
}
</script>