<?php
use Core\App\Services\Shipping\EcotrackStatusMapper;
use Core\App\Services\Shipping\ShippingStatusPresenter;
use Core\App\Support\OrderPricing;

/* ── Data extraction ─────────────────────────────────────── */
$extra        = is_array($order['extra'] ?? null) ? $order['extra'] : [];
$productSnap  = $extra['product']  ?? [];
$variants     = $extra['variants'] ?? [];
$selectedOffer = $extra['selected_offer'] ?? [];
$quantity     = (int)($extra['quantity'] ?? 1);
$pricing      = OrderPricing::pricing($order);
$currency     = $pricing['currency']       ?? '';
$productPrice = $productSnap['price']      ?? 0;
$productsTotal= $pricing['products_total'] ?? 0;
$shippingPrice= $pricing['shipping_price'] ?? 0;
$total        = $pricing['total']          ?? OrderPricing::effectiveTotal($order);
$shipping     = $extra['shipping'] ?? [];
$shippingType = $shipping['type']  ?? null;
$stateCode    = $shipping['destination']['state_code'] ?? '';
$cityName     = $shipping['destination']['city_name']  ?? '';
$shippingProvider = strtolower((string)($shipping['provider'] ?? ''));
$shippingMeta = $shippingProvider === 'maystro'
    ? ShippingStatusPresenter::meta($shippingProvider, $shipping['status'] ?? null, isset($shipping['status_code']) ? (int)$shipping['status_code'] : null)
    : EcotrackStatusMapper::meta($shipping['status'] ?? null);
$orderQty     = max(1, (int)($extra['quantity'] ?? 1));
$actionLog    = $extra['action_log'] ?? [];
$inventoryLog = $extra['inventory_log'] ?? [];

$dzWilayas = [
    1 => ['fr'=>'Adrar','ar'=>'أدرار'],
    2 => ['fr'=>'Chlef','ar'=>'الشلف'],
    3 => ['fr'=>'Laghouat','ar'=>'الأغواط'],
    4 => ['fr'=>'Oum El Bouaghi','ar'=>'أم البواقي'],
    5 => ['fr'=>'Batna','ar'=>'باتنة'],
    6 => ['fr'=>'Béjaïa','ar'=>'بجاية'],
    7 => ['fr'=>'Biskra','ar'=>'بسكرة'],
    8 => ['fr'=>'Bechar','ar'=>'بشار'],
    9 => ['fr'=>'Blida','ar'=>'البليدة'],
    10 => ['fr'=>'Bouira','ar'=>'البويرة'],
    11 => ['fr'=>'Tamanrasset','ar'=>'تمنراست'],
    12 => ['fr'=>'Tbessa','ar'=>'تبسة'],
    13 => ['fr'=>'Tlemcen','ar'=>'تلمسان'],
    14 => ['fr'=>'Tiaret','ar'=>'تيارت'],
    15 => ['fr'=>'Tizi Ouzou','ar'=>'تيزي وزو'],
    16 => ['fr'=>'Alger','ar'=>'الجزائر'],
    17 => ['fr'=>'Djelfa','ar'=>'الجلفة'],
    18 => ['fr'=>'Jijel','ar'=>'جيجل'],
    19 => ['fr'=>'Setif','ar'=>'سطيف'],
    20 => ['fr'=>'Saida','ar'=>'سعيدة'],
    21 => ['fr'=>'Skikda','ar'=>'سكيكدة'],
    22 => ['fr'=>'Sidi Bel Abbes','ar'=>'سيدي بلعباس'],
    23 => ['fr'=>'Annaba','ar'=>'عنابة'],
    24 => ['fr'=>'Guelma','ar'=>'قالمة'],
    25 => ['fr'=>'Constantine','ar'=>'قسنطينة'],
    26 => ['fr'=>'Medea','ar'=>'المدية'],
    27 => ['fr'=>'Mostaganem','ar'=>'مستغانم'],
    28 => ['fr'=>'M\'Sila','ar'=>'المسيلة'],
    29 => ['fr'=>'Mascara','ar'=>'معسكر'],
    30 => ['fr'=>'Ouargla','ar'=>'ورقلة'],
    31 => ['fr'=>'Oran','ar'=>'وهران'],
    32 => ['fr'=>'El Bayadh','ar'=>'البيض'],
    33 => ['fr'=>'Illizi','ar'=>'إليزي'],
    34 => ['fr'=>'Bordj Bou Arreridj','ar'=>'برج بوعريريج'],
    35 => ['fr'=>'Boumerdes','ar'=>'بومرداس'],
    36 => ['fr'=>'El Tarf','ar'=>'الطارف'],
    37 => ['fr'=>'Tindouf','ar'=>'تندوف'],
    38 => ['fr'=>'Tissemsilt','ar'=>'تيسمسيلت'],
    39 => ['fr'=>'El Oued','ar'=>'الوادي'],
    40 => ['fr'=>'Khenchela','ar'=>'خنشلة'],
    41 => ['fr'=>'Souk Ahras','ar'=>'سوق أهراس'],
    42 => ['fr'=>'Tipaza','ar'=>'تيبازة'],
    43 => ['fr'=>'Mila','ar'=>'ميلة'],
    44 => ['fr'=>'Ain Defla','ar'=>'عين الدفلى'],
    45 => ['fr'=>'Naama','ar'=>'النعامة'],
    46 => ['fr'=>'Ain Temouchent','ar'=>'عين تموشنت'],
    47 => ['fr'=>'Ghardaia','ar'=>'غرداية'],
    48 => ['fr'=>'Relizane','ar'=>'غليزان'],
    49 => ['fr'=>'El M\'ghair','ar'=>'المغير'],
    50 => ['fr'=>'El Menia','ar'=>'المنيعة'],
    51 => ['fr'=>'Ouled Djellal','ar'=>'أولاد جلال'],
    52 => ['fr'=>'Bordj Baji Mokhtar','ar'=>'برج باجي مختار'],
    53 => ['fr'=>'Béni Abbès','ar'=>'بني عباس'],
    54 => ['fr'=>'Timimoun','ar'=>'تيميمون'],
    55 => ['fr'=>'Touggourt','ar'=>'تقرت'],
    56 => ['fr'=>'Djanet','ar'=>'جانت'],
    57 => ['fr'=>'In Salah','ar'=>'عين صالح'],
    58 => ['fr'=>'In Guezzam','ar'=>'عين قزام'],
    59 => ['fr'=>'Aflou','ar'=>'آفلو'],
    60 => ['fr'=>'Barika','ar'=>'بريكة'],
    61 => ['fr'=>'El Kantara','ar'=>'القنطرة'],
    62 => ['fr'=>'Bir El Ater','ar'=>'بئر العاتر'],
    63 => ['fr'=>'El Aricha','ar'=>'العريشة'],
    64 => ['fr'=>'Ksar Chellala','ar'=>'قصر الشلالة'],
    65 => ['fr'=>'Ain Oussera','ar'=>'عين وسارة'],
    66 => ['fr'=>'Messad','ar'=>'مسعد'],
    67 => ['fr'=>'Ksar El Boukhari','ar'=>'قصر البخاري'],
    68 => ['fr'=>'Bou Saada','ar'=>'بوسعادة'],
    69 => ['fr'=>'El Abiodh Sidi Cheikh','ar'=>'الأبيض سيدي الشيخ']
];
$stateCodeInt = (int) ltrim((string)$stateCode, '0');
$stateInfo = $dzWilayas[$stateCodeInt] ?? null;
$stateCodeDisplay = $stateCode !== '' ? str_pad((string)$stateCodeInt, 2, '0', STR_PAD_LEFT) : '';
$stateNameFr = $stateInfo['fr'] ?? (string)$stateCode;
$stateName = $stateInfo['ar'] ?? (string)$stateCode;

/* ── Returns (loaded by OrderController::view) ──────────── */
$existingReturns = $existingReturns ?? [];

$orderStatus   = $order['order_status'];
$isConfirmed   = $orderStatus === 'confirmed';
$isReturned    = $orderStatus === 'returned';
/* إرجاع مسموح به فقط إذا: مؤكد ولم يُرجَع بعد */
$alreadyReturned = !empty($existingReturns);
$canReturn       = $isConfirmed && !$alreadyReturned;
$canAddReturn    = $isConfirmed && !$alreadyReturned;

/* ── Status config ───────────────────────────────────────── */
$statusCfg = [
    'pending'   => ['color'=>'#f59e0b','bg'=>'#fffbeb','label'=>__('orders.status_pending','Pending'),   'icon'=>'bi-clock-fill'],
    'confirmed' => ['color'=>'#10b981','bg'=>'#f0fdf4','label'=>__('orders.status_confirmed','Confirmed'),'icon'=>'bi-check-circle-fill'],
    'rejected'  => ['color'=>'#ef4444','bg'=>'#fff1f2','label'=>__('orders.status_rejected','Rejected'), 'icon'=>'bi-x-circle-fill'],
    'returned'  => ['color'=>'#8b5cf6','bg'=>'#f5f3ff','label'=>__('orders.status_returned','Returned'), 'icon'=>'bi-arrow-return-left'],
];
$sc = $statusCfg[$orderStatus] ?? ['color'=>'#6b7280','bg'=>'#f9fafb','label'=>$orderStatus,'icon'=>'bi-question-circle'];

/* ── Call attempts ───────────────────────────────────────── */
$callAttempts      = $callAttempts      ?? [];
$callAttemptsCount = $callAttemptsCount ?? 0;
$currentAssignment = $currentAssignment ?? null;
$workflowTimeline = $workflowTimeline ?? [];
$assignableMembers = $assignableMembers ?? [];
$workflowMeta = is_array($extra['workflow'] ?? null) ? $extra['workflow'] : [];
$workflowAssignedHistory = is_array($workflowMeta['assigned_history'] ?? null) ? $workflowMeta['assigned_history'] : [];
$assignableMap = [];
foreach ($assignableMembers as $_wfMember) {
    $assignableMap[(int)($_wfMember['id'] ?? 0)] = (string)($_wfMember['username'] ?? '');
}
$currentAdminId = (int)($currentAdminId ?? ($_SESSION['admin_id'] ?? 0));
$currentAdminRole = (string)($currentAdminRole ?? ($_SESSION['admin_role'] ?? ''));
$isWorkflowManager = in_array($currentAdminRole, ['owner', 'manager'], true);
$isAssignedConfirmer = $currentAssignment && (int)($currentAssignment['admin_id'] ?? 0) === $currentAdminId;
$resultColors = ['no_answer'=>'secondary','busy'=>'warning','wrong_number'=>'danger','callback_later'=>'info','interested'=>'primary','not_interested'=>'danger','confirmed'=>'success','rejected'=>'danger'];
$resultIcons  = ['no_answer'=>'bi-telephone-x','busy'=>'bi-telephone-minus','wrong_number'=>'bi-telephone-x','callback_later'=>'bi-clock','interested'=>'bi-hand-thumbs-up','not_interested'=>'bi-hand-thumbs-down','confirmed'=>'bi-check-circle-fill','rejected'=>'bi-x-circle-fill'];
?>

<style>
/* ── Order View ────────────────────────────────────────────── */
.ov-page { max-width:1080px; margin:0 auto; padding:24px 16px 48px; }

/* Header */
.ov-header { display:flex; align-items:flex-start; justify-content:space-between; gap:16px; margin-bottom:28px; flex-wrap:wrap; }
.ov-title  { font-size:26px; font-weight:800; color:#111827; margin:0; line-height:1.25; }
.ov-title small { font-size:18px; font-weight:600; color:#9ca3af; }
.ov-header-actions { display:flex; gap:8px; flex-wrap:wrap; }

/* Status badge — big */
.ov-status-badge {
    display:inline-flex; align-items:center; gap:8px;
    padding:9px 18px; border-radius:99px;
    font-size:15px; font-weight:700; letter-spacing:.3px;
}

/* Layout grid */
.ov-grid { display:grid; grid-template-columns:1fr 320px; gap:20px; align-items:start; }
@media(max-width:768px){ .ov-grid{ grid-template-columns:1fr; } }

/* Cards */
.ov-card {
    background:#fff; border:1.5px solid #e5e7eb;
    border-radius:16px; overflow:hidden; margin-bottom:20px;
}
.ov-card-head {
    padding:15px 20px; border-bottom:1px solid #f3f4f6;
    display:flex; align-items:center; gap:10px;
    font-size:15px; font-weight:700; color:#374151;
    text-transform:none; letter-spacing:0;
}
.ov-card-head i { font-size:16px; }
.ov-card-body { padding:22px; }

/* Info rows */
.ov-info-row { display:flex; justify-content:space-between; align-items:center; padding:12px 0; border-bottom:1px solid #f3f4f6; gap:20px; }
.ov-info-row:last-child { border-bottom:none; }
.ov-info-label { font-size:14px; color:#9ca3af; font-weight:600; flex:0 0 120px; }
.ov-info-val   { font-size:16px; color:#111827; font-weight:600; text-align:end; flex:1 1 auto; }

/* Product row */
.ov-product { display:flex; gap:16px; align-items:center; }
.ov-product-img { width:78px; height:78px; border-radius:12px; object-fit:cover; border:1px solid #e5e7eb; flex-shrink:0; }
.ov-product-img-placeholder { width:78px; height:78px; border-radius:12px; background:#f3f4f6; display:flex; align-items:center; justify-content:center; font-size:24px; flex-shrink:0; }
.ov-product-name { font-size:19px; font-weight:800; color:#111827; margin-bottom:8px; line-height:1.4; }

/* Pricing summary */
.ov-price-row { display:flex; justify-content:space-between; padding:10px 0; border-bottom:1px solid #f3f4f6; font-size:15px; }
.ov-price-row:last-child { border-bottom:none; padding-top:14px; margin-top:4px; font-size:20px; font-weight:800; }
.ov-price-row span:first-child { color:#6b7280; }
.ov-price-row:last-child span { color:#111827; }

/* Call attempt */
.ov-call-item { display:flex; gap:12px; align-items:flex-start; padding:12px; border-radius:10px; background:#f9fafb; margin-bottom:10px; }
.ov-call-item:last-child { margin-bottom:0; }

/* Timeline / action log */
.ov-timeline { position:relative; padding-inline-start:28px; }
.ov-timeline::before { content:''; position:absolute; inset-inline-start:9px; top:0; bottom:0; width:2px; background:#e5e7eb; border-radius:99px; }
.ov-tl-item { position:relative; margin-bottom:16px; }
.ov-tl-item:last-child { margin-bottom:0; }
.ov-tl-dot { position:absolute; inset-inline-start:-28px; top:2px; width:18px; height:18px; border-radius:50%; border:2.5px solid #fff; box-shadow:0 0 0 2px #e5e7eb; display:flex; align-items:center; justify-content:center; font-size:9px; color:#fff; }
.ov-tl-dot.confirmed { background:#10b981; box-shadow:0 0 0 2px #10b981; }
.ov-tl-dot.rejected  { background:#ef4444; box-shadow:0 0 0 2px #ef4444; }
.ov-tl-dot.pending   { background:#f59e0b; box-shadow:0 0 0 2px #f59e0b; }
.ov-tl-body { font-size:14px; }
.ov-tl-action { font-weight:700; color:#111827; font-size:15px; }
.ov-tl-meta   { color:#9ca3af; font-size:13px; margin-top:4px; }

/* Returns table */
.ov-returns-table { width:100%; border-collapse:collapse; font-size:14px; }
.ov-returns-table th { padding:10px 12px; background:#f9fafb; color:#6b7280; font-weight:700; font-size:12px; text-transform:uppercase; letter-spacing:.4px; text-align:start; border-bottom:1.5px solid #e5e7eb; }
.ov-returns-table td { padding:12px 12px; border-bottom:1px solid #f3f4f6; color:#374151; vertical-align:middle; }
.ov-returns-table tr:last-child td { border-bottom:none; }

/* Return form */
.ov-return-form { background:#fafafa; border:1.5px dashed #e5e7eb; border-radius:14px; padding:22px; }

/* Sticky sidebar */
.ov-sidebar { position:sticky; top:80px; }

/* Variant pills */
.ov-variant-pill { display:inline-flex; align-items:center; gap:6px; padding:5px 10px; background:#f3f4f6; border-radius:99px; font-size:13px; font-weight:600; color:#374151; }
.ov-color-dot { width:14px; height:14px; border-radius:50%; border:1.5px solid rgba(0,0,0,.15); display:inline-block; }

/* Alerts */
.ov-alert-success { background:#f0fdf4; border:1.5px solid #bbf7d0; border-radius:12px; padding:14px 18px; display:flex; gap:10px; align-items:center; margin-bottom:20px; color:#065f46; font-size:15px; font-weight:600; }
.ov-alert-warning { background:#fffbeb; border:1.5px solid #fde68a; border-radius:12px; padding:14px 16px; display:flex; gap:10px; align-items:flex-start; color:#92400e; font-size:14px; }
.ov-already-badge { display:inline-flex; align-items:center; gap:6px; background:#f5f3ff; color:#6d28d9; border:1.5px solid #ddd6fe; padding:8px 16px; border-radius:10px; font-size:14px; font-weight:600; }
</style>

<?php if (!empty($_GET['returned'])): ?>
<div class="ov-alert-success" style="margin:16px auto;max-width:1080px;padding:0 16px">
    <i class="bi bi-check-circle-fill fs-5"></i>
    <?= __('returns.success_msg', 'تم تسجيل المرتجع وإعادة المخزون بنجاح.') ?>
</div>
<?php endif; ?>

<div class="ov-page">

    <!-- ── HEADER ── -->
    <div class="ov-header">
        <div>
            <h1 class="ov-title">
                <?= __('orders.view_title','Order Details') ?>
                <small>#<?= (int)$order['id'] ?></small>
            </h1>
            <div class="mt-2">
                <span class="ov-status-badge"
                      style="background:<?= $sc['bg'] ?>;color:<?= $sc['color'] ?>;border:1.5px solid <?= $sc['color'] ?>30">
                    <i class="bi <?= $sc['icon'] ?>"></i>
                    <?= $sc['label'] ?>
                </span>
                <span class="text-muted small ms-2">
                    <?= date('d/m/Y H:i', strtotime($order['created_at'])) ?>
                </span>
            </div>
        </div>
        <div class="ov-header-actions">
            <a href="/admin/orders" class="btn btn-outline-secondary btn-sm">
                <i class="bi bi-arrow-right me-1"></i><?= __('actions.back','Back') ?>
            </a>
            <a href="/admin/orders/view/<?= (int)$order['id'] ?>"
               class="btn btn-outline-primary btn-sm">
                <i class="bi bi-arrow-clockwise me-1"></i><?= __('actions.refresh','Refresh') ?>
            </a>
        </div>
    </div>

    <!-- ── TWO-COLUMN LAYOUT ── -->
    <div class="ov-grid">

        <!-- ══ LEFT COLUMN ══ -->
        <div>

            <!-- Customer -->
            <div class="ov-card">
                <div class="ov-card-head">
                    <i class="bi bi-person-fill text-primary"></i>
                    <?= __('orders.customer_info','Customer Information') ?>
                </div>
                <div class="ov-card-body">
                    <div class="ov-info-row">
                        <span class="ov-info-label"><?= __('orders.full_name','Full Name') ?></span>
                        <span class="ov-info-val fw-bold"><?= htmlspecialchars($order['full_name']) ?></span>
                    </div>
                    <div class="ov-info-row">
                        <span class="ov-info-label"><?= __('orders.phone','Phone') ?></span>
                        <span class="ov-info-val">
                            <a href="tel:<?= htmlspecialchars($order['phone']) ?>" class="text-decoration-none fw-bold">
                                <i class="bi bi-telephone me-1 text-success"></i>
                                <?= htmlspecialchars($order['phone']) ?>
                            </a>
                        </span>
                    </div>
                    <div class="ov-info-row">
                        <span class="ov-info-label"><?= __('orders.location','Location') ?></span>
                        <span class="ov-info-val">
                            <i class="bi bi-geo-alt me-1 text-danger"></i>
                            <?= htmlspecialchars(trim($stateCodeDisplay . ' ' . $stateNameFr)) ?>
                            <?php if ($cityName): ?> / <?= htmlspecialchars($cityName) ?><?php endif; ?>
                        </span>
                    </div>
                    <?php if ($shippingType): ?>
                    <div class="ov-info-row">
                        <span class="ov-info-label"><?= __('orders.shipping_type','Shipping Type') ?></span>
                        <span class="ov-info-val">
                            <?php if ($shippingType === 'home'): ?>
                                <i class="bi bi-house me-1"></i><?= __('shipping.home','Home Delivery') ?>
                            <?php else: ?>
                                <i class="bi bi-building me-1"></i><?= __('shipping.desk','Office Delivery') ?>
                            <?php endif; ?>
                        </span>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Product -->
            <div class="ov-card">
                <div class="ov-card-head">
                    <i class="bi bi-box-seam-fill text-warning"></i>
                    <?= __('orders.product_info','Product Information') ?>
                </div>
                <div class="ov-card-body">
                    <?php if (!empty($productSnap)): ?>
                    <div class="ov-product mb-4">
                        <?php if (!empty($productSnap['image'])): ?>
                            <img src="<?= htmlspecialchars($productSnap['image']) ?>"
                                 alt="<?= htmlspecialchars($productSnap['name']) ?>"
                                 class="ov-product-img">
                        <?php else: ?>
                            <div class="ov-product-img-placeholder">📦</div>
                        <?php endif; ?>
                        <div>
                            <div class="ov-product-name">
                                <?= htmlspecialchars($productSnap['name']) ?>
                            </div>
                            <?php if (!empty($variants['size']) || !empty($variants['color'])): ?>
                            <div class="d-flex gap-2 flex-wrap mt-1">
                                <?php if (!empty($variants['size'])): ?>
                                    <span class="ov-variant-pill">
                                        <i class="bi bi-rulers"></i>
                                        <?= __('product.size','Size') ?>: <?= htmlspecialchars($variants['size']) ?>
                                    </span>
                                <?php endif; ?>
                                <?php if (!empty($variants['color'])): ?>
                                    <span class="ov-variant-pill">
                                        <span class="ov-color-dot" style="background:<?= htmlspecialchars($variants['color']) ?>"></span>
                                        <?= __('product.color','Color') ?>: <?= htmlspecialchars($variants['color']) ?>
                                    </span>
                                <?php endif; ?>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="ov-info-row">
                        <span class="ov-info-label"><?= __('orders.product_price','Unit Price') ?></span>
                        <span class="ov-info-val"><?= number_format($productPrice, 2) ?> <?= htmlspecialchars($currency) ?></span>
                    </div>
                    <div class="ov-info-row">
                        <span class="ov-info-label"><?= __('orders.quantity','Quantity') ?></span>
                        <span class="ov-info-val">
                            <span class="badge bg-light text-dark border fs-6 px-3 py-2"><?= $quantity ?></span>
                        </span>
                    </div>
                    <?php if (!empty($selectedOffer['type'])): ?>
                    <div class="ov-info-row">
                        <span class="ov-info-label"><?= __('orders.selected_offer','Selected Offer') ?></span>
                        <span class="ov-info-val">
                            <span class="ov-variant-pill"><i class="bi bi-stars"></i><?= htmlspecialchars((string)($selectedOffer['label'] ?? ($selectedOffer['type'] ?? ''))) ?></span>
                            <?php if (isset($selectedOffer['paid_qty'])): ?><span class="ov-variant-pill"><?= __('orders.offer_qty_paid','Paid Qty') ?>: <?= (int)$selectedOffer['paid_qty'] ?></span><?php endif; ?>
                            <?php if (isset($selectedOffer['free_qty']) && (int)$selectedOffer['free_qty'] > 0): ?><span class="ov-variant-pill"><?= __('orders.offer_free_qty','Free Qty') ?>: <?= (int)$selectedOffer['free_qty'] ?></span><?php endif; ?>
                            <?php if (isset($selectedOffer['received_qty'])): ?><span class="ov-variant-pill"><?= __('orders.offer_qty_received','Received Qty') ?>: <?= (int)$selectedOffer['received_qty'] ?></span><?php endif; ?>
                        </span>
                    </div>
                    <?php endif; ?>
                    <div class="ov-info-row">
                        <span class="ov-info-label"><?= __('orders.subtotal','Subtotal') ?></span>
                        <span class="ov-info-val"><?= number_format($productsTotal, 2) ?> <?= htmlspecialchars($currency) ?></span>
                    </div>
                    <?php else: ?>
                    <div class="ov-alert-warning">
                        <i class="bi bi-exclamation-triangle-fill flex-shrink-0"></i>
                        <?= __('orders.product_deleted','This product was deleted after the order was placed.') ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Shipping -->
            <?php if (!empty($shipping['provider']) || !empty($shipping['status'])): ?>
            <div class="ov-card">
                <div class="ov-card-head">
                    <i class="bi bi-truck text-info"></i>
                    <?= __('orders.shipping_info','Shipping Information') ?>
                    <?php if (($shipping['provider'] ?? '') === 'maystro' && !empty($shipping['tracking'])): ?>
                        <span class="ms-auto d-flex gap-1">
                            <a href="/admin/orders/maystro/label/<?= (int)$order['id'] ?>"
                               class="btn btn-outline-secondary btn-sm py-0 px-2"
                               target="_blank" title="<?= __('shipping.print_label','Print Label (Bordereau)') ?>">
                                <i class="bi bi-printer"></i>
                            </a>
                        </span>
                    <?php endif; ?>
                    <?php if (($shipping['provider'] ?? '') === 'ecotrack' && !empty($shipping['tracking'])): ?>
                        <span class="ms-auto d-flex gap-1">
                            <a href="/admin/orders/ecotrack/label?tracking=<?= urlencode($shipping['tracking']) ?>"
                               class="btn btn-outline-secondary btn-sm py-0 px-2"
                               target="_blank" title="<?= __('shipping.print_label','Print Label (Bordereau)') ?>">
                                <i class="bi bi-printer"></i>
                            </a>
                            <?php if (!$alreadyReturned): ?>
                            <form method="POST" action="/admin/orders/return-provider/<?= (int)$order['id'] ?>" class="d-inline">
                                <?= \Core\System\Csrf::field() ?>
                                <button type="submit"
                                        class="btn btn-outline-warning btn-sm py-0 px-2"
                                        onclick="return confirm('<?= __('returns.provider_return_confirm','Send a return request to the shipping provider?') ?>')"
                                        title="<?= __('returns.provider_return_request','Request Return from Provider') ?>">
                                    <i class="bi bi-arrow-counterclockwise"></i>
                                </button>
                            </form>
                            <?php endif; ?>
                        </span>
                    <?php endif; ?>
                </div>
                <div class="ov-card-body">
                    <?php if (!empty($shipping['provider'])): ?>
                    <div class="ov-info-row">
                        <span class="ov-info-label"><?= __('orders.shipping_company','Company') ?></span>
                        <span class="ov-info-val d-flex align-items-center gap-2">
                            <?php if ($shipping['provider'] === 'maystro'): ?>
                                <img src="/admin/assets/img/maystro.png" height="18" alt="Maystro">
                            <?php elseif ($shipping['provider'] === 'ecotrack'): ?>
                                <img src="/admin/assets/img/ecotrack.png" height="18" alt="Ecotrack">
                            <?php elseif ($shipping['provider'] === 'zr_express'): ?>
                                <img src="/admin/assets/img/zr_express.png" height="18" alt="ZR">
                            <?php elseif ($shipping['provider'] === 'yalidine'): ?>
                                <img src="/admin/assets/img/yalidine.png" height="18" alt="Yalidine">
                            <?php endif; ?>
                            <?= htmlspecialchars($shipping['provider']) ?>
                        </span>
                    </div>
                    <?php endif; ?>

                    <?php if (!empty($shipping['status'])): ?>
                    <div class="ov-info-row">
                        <span class="ov-info-label"><?= __('orders.shipping_status','Status') ?></span>
                        <span class="ov-info-val">
                            <span class="badge <?= $shippingMeta['badge'] ?>">
                                <?= __($shippingMeta['label_key'], $shippingMeta['fallback']) ?>
                            </span>
                            <?php if (!empty($shipping['last_update_at'])): ?>
                                <small class="text-muted ms-1"><?= date('d/m H:i', strtotime($shipping['last_update_at'])) ?></small>
                            <?php endif; ?>
                        </span>
                    </div>
                    <?php endif; ?>

                    <?php if (!empty($shipping['tracking'])): ?>
                    <div class="ov-info-row">
                        <span class="ov-info-label"><?= __('orders.tracking_number','Tracking') ?></span>
                        <span class="ov-info-val">
                            <code class="bg-light px-2 py-1 rounded"><?= htmlspecialchars($shipping['tracking']) ?></code>
                        </span>
                    </div>
                    <?php endif; ?>

                    <?php /* Maystro-specific fields */ ?>
                    <?php if (($shipping['provider'] ?? '') === 'maystro'): ?>

                        <?php if (!empty($shipping['delivery_price'])): ?>
                        <div class="ov-info-row">
                            <span class="ov-info-label"><?= __('shipping.delivery_price','Delivery Price') ?></span>
                            <span class="ov-info-val"><?= number_format((float)$shipping['delivery_price'], 0) ?> DA</span>
                        </div>
                        <?php endif; ?>

                        <?php if (!empty($shipping['maystro_id'])): ?>
                        <div class="ov-info-row">
                            <span class="ov-info-label">Maystro ID</span>
                            <span class="ov-info-val"><small class="text-muted font-monospace"><?= htmlspecialchars($shipping['maystro_id']) ?></small></span>
                        </div>
                        <?php endif; ?>

                        <?php if (!empty($shipping['status_code'])): ?>
                        <div class="ov-info-row">
                            <span class="ov-info-label"><?= __('orders.shipping_status','Status') ?></span>
                            <span class="ov-info-val">
                                <span class="badge bg-info text-dark"><?= (int)$shipping['status_code'] ?></span>
                                <small class="ms-1 text-muted"><?= htmlspecialchars($shipping['status'] ?? '') ?></small>
                            </span>
                        </div>
                        <?php endif; ?>

                        <?php if (!empty($shipping['error_msgs'])): ?>
                        <div class="ov-info-row">
                            <span class="ov-info-label text-danger"><?= __('shipping.errors','Errors') ?></span>
                            <span class="ov-info-val">
                                <?php foreach ((array)$shipping['error_msgs'] as $err): ?>
                                    <div class="text-danger small"><i class="bi bi-exclamation-triangle me-1"></i><?= htmlspecialchars($err) ?></div>
                                <?php endforeach; ?>
                            </span>
                        </div>
                        <?php endif; ?>

                        <?php if (($shipping['status'] ?? '') === 'error'): ?>
                        <?php if (!empty($shipping['response'])): ?>
                        <div class="ov-info-row">
                            <span class="ov-info-label text-muted" style="font-size:11px">API Response</span>
                            <span class="ov-info-val">
                                <pre class="small bg-light p-2 rounded mb-0" style="font-size:11px;max-height:150px;overflow:auto;white-space:pre-wrap"><?= htmlspecialchars(json_encode($shipping['response'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) ?></pre>
                            </span>
                        </div>
                        <?php endif; ?>
                        <?php if (!empty($shipping['debug_payload'])): ?>
                        <div class="ov-info-row">
                            <span class="ov-info-label text-muted" style="font-size:11px">Payload Sent</span>
                            <span class="ov-info-val">
                                <pre class="small bg-light p-2 rounded mb-0" style="font-size:11px;max-height:150px;overflow:auto;white-space:pre-wrap"><?= htmlspecialchars(json_encode($shipping['debug_payload'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) ?></pre>
                            </span>
                        </div>
                        <?php endif; ?>
                        <?php if (!empty($shipping['raw_body'])): ?>
                        <div class="ov-info-row">
                            <span class="ov-info-label text-muted" style="font-size:11px">Raw Body (500)</span>
                            <span class="ov-info-val">
                                <pre class="small bg-light p-2 rounded mb-0 text-danger" style="font-size:10px;max-height:120px;overflow:auto;white-space:pre-wrap"><?= htmlspecialchars($shipping['raw_body']) ?></pre>
                            </span>
                        </div>
                        <?php endif; ?>
                        <?php endif; ?>

                    <?php endif; /* maystro */ ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- Call attempts (pending only) -->
            <?php if ($orderStatus === 'pending'): ?>
            <div class="ov-card">
                <div class="ov-card-head">
                    <i class="bi bi-telephone-fill text-primary"></i>
                    <?= __('calls.log_title','Log Call Attempt') ?>
                    <?php if ($callAttemptsCount > 0): ?>
                        <span class="badge bg-primary ms-auto"><?= $callAttemptsCount ?></span>
                    <?php endif; ?>
                </div>
                <div class="ov-card-body">
                    <div class="row g-2 align-items-end mb-3">
                        <div class="col-md-5">
                            <label class="form-label fw-semibold small"><?= __('calls.result','Call Result') ?> *</label>
                            <select id="callResult" class="form-select form-select-sm">
                                <option value=""><?= __('calls.select_result','Select result...') ?></option>
                                <option value="no_answer"><?= __('calls.no_answer','No Answer') ?></option>
                                <option value="busy"><?= __('calls.busy','Busy') ?></option>
                                <option value="wrong_number"><?= __('calls.wrong_number','Wrong Number') ?></option>
                                <option value="callback_later"><?= __('calls.callback_later','Call Back Later') ?></option>
                                <option value="interested"><?= __('calls.interested','Interested') ?></option>
                                <option value="not_interested"><?= __('calls.not_interested','Not Interested') ?></option>
                                <option value="confirmed" class="fw-bold"><?= __('calls.confirmed','✅ Confirmed') ?></option>
                                <option value="rejected"  class="fw-bold"><?= __('calls.rejected','❌ Rejected') ?></option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-semibold small"><?= __('calls.note','Note') ?></label>
                            <input type="text" id="callNote" class="form-control form-control-sm"
                                   placeholder="<?= __('calls.note_placeholder','e.g. Will call back at 3pm...') ?>">
                        </div>
                        <div class="col-md-3">
                            <button type="button" class="btn btn-primary btn-sm w-100"
                                    onclick="logCall(<?= (int)$order['id'] ?>)">
                                <i class="bi bi-telephone-plus me-1"></i><?= __('calls.log_btn','Log Call') ?>
                            </button>
                        </div>
                    </div>
                    <div id="callMsg" class="d-none"></div>

                    <?php if (!empty($callAttempts)): ?>
                    <div class="border-top pt-3 mt-1">
                        <div class="small fw-semibold text-muted mb-3">
                            <i class="bi bi-clock-history me-1"></i>
                            <?= __('calls.history','Call History') ?> (<?= $callAttemptsCount ?>)
                        </div>
                        <?php foreach (array_reverse($callAttempts) as $ca): ?>
                        <div class="ov-call-item">
                            <span class="badge bg-<?= $resultColors[$ca['result']] ?? 'secondary' ?> flex-shrink-0 mt-1">
                                <i class="bi <?= $resultIcons[$ca['result']] ?? 'bi-telephone' ?> me-1"></i>
                                <?= __('calls.' . $ca['result'], $ca['result']) ?>
                            </span>
                            <div>
                                <?php if (!empty($ca['note'])): ?>
                                    <div class="small text-dark"><?= htmlspecialchars($ca['note']) ?></div>
                                <?php endif; ?>
                                <div class="text-muted" style="font-size:.85rem">
                                    <i class="bi bi-person me-1"></i><?= htmlspecialchars($ca['admin_name']) ?>
                                    &nbsp;·&nbsp;
                                    <i class="bi bi-clock me-1"></i><?= date('d/m/Y H:i', strtotime($ca['called_at'])) ?>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>


            <?php if (!empty($inventoryLog)): ?>
            <div class="ov-card">
                <div class="ov-card-head">
                    <i class="bi bi-box-seam text-warning"></i>
                    <?= __('orders.inventory_log','Inventory Log') ?>
                </div>
                <div class="ov-card-body">
                    <div class="ov-timeline">
                        <?php foreach (array_reverse($inventoryLog) as $log): ?>
                        <div class="ov-tl-item">
                            <div class="ov-tl-dot <?= ($log['action'] ?? '') === 'deducted' ? 'confirmed' : 'rejected' ?>">
                                <i class="bi <?= ($log['action'] ?? '') === 'deducted' ? 'bi-dash-circle' : 'bi-plus-circle' ?>"></i>
                            </div>
                            <div class="ov-tl-body">
                                <span class="ov-tl-action">
                                    <?= ($log['action'] ?? '') === 'deducted' ? __('orders.inventory_deducted','Stock deducted') : __('orders.inventory_restored','Stock restored') ?>
                                </span>
                                <div class="ov-tl-meta">
                                    <i class="bi bi-hash me-1"></i><?= (int)($log['quantity'] ?? 0) ?>
                                    <?php if (!empty($log['size'])): ?>&nbsp;·&nbsp;<i class="bi bi-aspect-ratio me-1"></i><?= htmlspecialchars($log['size']) ?><?php endif; ?>
                                    <?php if (!empty($log['color'])): ?>&nbsp;·&nbsp;<i class="bi bi-palette me-1"></i><?= htmlspecialchars($log['color']) ?><?php endif; ?>
                                    <?php if (!empty($log['provider'])): ?>&nbsp;·&nbsp;<i class="bi bi-truck me-1"></i><?= htmlspecialchars($log['provider']) ?><?php endif; ?>
                                    <?php if (!empty($log['tracking'])): ?>&nbsp;·&nbsp;<i class="bi bi-upc-scan me-1"></i><?= htmlspecialchars($log['tracking']) ?><?php endif; ?>
                                    &nbsp;·&nbsp;<i class="bi bi-clock me-1"></i><?= !empty($log['at']) ? date('d/m/Y H:i', strtotime($log['at'])) : '—' ?>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <!-- Action log -->
            <?php if (!empty($actionLog)): ?>
            <div class="ov-card">
                <div class="ov-card-head">
                    <i class="bi bi-clock-history text-secondary"></i>
                    <?= __('orders.action_log','Action Log') ?>
                </div>
                <div class="ov-card-body">
                    <div class="ov-timeline">
                        <?php foreach (array_reverse($actionLog) as $log):
                            $ac = $log['action'] ?? '';
                            $dotColors = ['confirmed'=>'confirmed','rejected'=>'rejected','pending'=>'pending'];
                            $dcls = $dotColors[$ac] ?? '';
                            $acLabels = ['confirmed'=>__('orders.status_confirmed','Confirmed'),'rejected'=>__('orders.status_rejected','Rejected'),'pending'=>__('orders.status_pending','Pending')];
                        ?>
                        <div class="ov-tl-item">
                            <div class="ov-tl-dot <?= $dcls ?>">
                                <i class="bi <?= ['confirmed'=>'bi-check','rejected'=>'bi-x','pending'=>'bi-dash'][$ac] ?? 'bi-dot' ?>"></i>
                            </div>
                            <div class="ov-tl-body">
                                <span class="ov-tl-action"><?= $acLabels[$ac] ?? htmlspecialchars($ac) ?></span>
                                <div class="ov-tl-meta">
                                    <i class="bi bi-person me-1"></i><?= htmlspecialchars($log['admin_name'] ?? '—') ?>
                                    <?php if (!empty($log['admin_role'])): ?>
                                        · <?php
                                            if (class_exists('\Core\App\Models\TeamMemberModel')) echo \Core\App\Models\TeamMemberModel::roleLabel($log['admin_role']);
                                            else echo htmlspecialchars($log['admin_role']);
                                        ?>
                                    <?php endif; ?>
                                    · <?= htmlspecialchars($log['at'] ?? '') ?>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <!-- ══ RETURN SECTION ══ -->
            <?php if ($isConfirmed || $isReturned || $alreadyReturned): ?>
            <div class="ov-card" style="border-color:<?= $alreadyReturned ? '#ddd6fe' : '#fde68a' ?>">
                <div class="ov-card-head" style="background:<?= $alreadyReturned ? '#f5f3ff' : '#fffbeb' ?>">
                    <i class="bi bi-arrow-return-left" style="color:<?= $alreadyReturned ? '#7c3aed' : '#d97706' ?>"></i>
                    <span style="color:<?= $alreadyReturned ? '#5b21b6' : '#92400e' ?>">
                        <?= __('returns.title','Return') ?>
                    </span>
                    <?php if ($alreadyReturned): ?>
                    <span class="ms-auto badge" style="background:#ede9fe;color:#6d28d9;border:1px solid #ddd6fe">
                        <i class="bi bi-check-circle me-1"></i><?= __('returns.already_done','Already Returned') ?>
                    </span>
                    <?php endif; ?>
                </div>
                <div class="ov-card-body">

                    <?php $shippingProvider = (string)($extra['shipping']['provider'] ?? ''); $hasTracking = !empty($extra['shipping']['tracking']); ?>

                    <?php if (!$alreadyReturned && $hasTracking): ?>
                    <div class="mb-3 d-flex justify-content-end gap-2 flex-wrap">

                        <?php if ($shippingProvider === 'ecotrack'): ?>
                        <form method="POST" action="/admin/orders/return-provider/<?= (int)$order['id'] ?>">
                            <?= \Core\System\Csrf::field() ?>
                            <button type="submit" class="btn btn-outline-warning btn-sm"
                                    onclick="return confirm('<?= __('returns.provider_return_confirm','Send a return request to the shipping provider?') ?>')">
                                <i class="bi bi-arrow-counterclockwise me-1"></i>
                                <?= __('returns.provider_return_request','Request Return from Provider') ?>
                                (Ecotrack)
                            </button>
                        </form>
                        <?php endif; ?>

                        <?php if ($shippingProvider === 'maystro'): ?>
                        <button type="button" class="btn btn-outline-warning btn-sm"
                                onclick="requestMaystroRefund(<?= (int)$order['id'] ?>)">
                            <i class="bi bi-arrow-counterclockwise me-1"></i>
                            <?= __('returns.provider_return_request','Request Return from Provider') ?>
                            (Maystro)
                        </button>
                        <?php endif; ?>

                    </div>
                    <?php endif; ?>

                    <?php if ($alreadyReturned): ?>
                    <!-- ── إرجاع موجود: نعرض التفاصيل فقط بدون فورم ── -->
                    <div class="ov-already-badge mb-4">
                        <i class="bi bi-shield-check"></i>
                        <?= __('returns.already_returned_msg','This order has already been returned. You cannot add another return.') ?>
                    </div>
                    <?php endif; ?>

                    <!-- جدول المرتجعات الموجودة -->
                    <?php if (!empty($existingReturns)): ?>
                    <div class="mb-4" style="overflow-x:auto">
                        <table class="ov-returns-table">
                            <thead>
                                <tr>
                                    <th><?= __('returns.col_type','Type') ?></th>
                                    <th><?= __('returns.col_qty','Qty') ?></th>
                                    <th><?= __('returns.col_reason','Reason') ?></th>
                                    <th><?= __('returns.col_notes','Notes') ?></th>
                                    <th><?= __('returns.col_received','Received') ?></th>
                                    <th><?= __('returns.col_stock','Stock') ?></th>
                                    <th><?= __('returns.col_date','Date') ?></th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php foreach ($existingReturns as $ret):
                                $typeLabels = [
                                    'shipping_refused' => __('returns.type_shipping','رفض الزبون'),
                                    'admin_request'    => __('returns.type_admin','مشكلة منتج'),
                                    'partial'          => __('returns.type_partial','جزئي'),
                                ];
                            ?>
                            <tr>
                                <td>
                                    <span class="badge bg-secondary bg-opacity-10 text-secondary border">
                                        <?= htmlspecialchars($typeLabels[$ret['type']] ?? $ret['type']) ?>
                                    </span>
                                </td>
                                <td><strong><?= (int)$ret['quantity'] ?></strong></td>
                                <td><?= htmlspecialchars($ret['reason'] ?? '—') ?></td>
                                <td class="text-muted"><?= htmlspecialchars($ret['admin_notes'] ?? '—') ?></td>
                                <td><?= $ret['received_at'] ? date('d/m/Y', strtotime($ret['received_at'])) : '—' ?></td>
                                <td>
                                    <?php if ($ret['stock_restored']): ?>
                                        <span class="badge bg-success-subtle text-success border border-success-subtle">
                                            <i class="bi bi-check2 me-1"></i><?= __('returns.stock_yes','Restored') ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="badge bg-danger-subtle text-danger border border-danger-subtle">
                                            <i class="bi bi-x me-1"></i><?= __('returns.stock_no','Not Restored') ?>
                                        </span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-muted"><?= date('d/m/Y H:i', strtotime($ret['created_at'])) ?></td>
                            </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>

                    <!-- ── فورم الإرجاع: فقط إذا لم يُرجَع بعد ── -->
                    <?php if ($canAddReturn): ?>

                    <!-- زر الإرجاع — يظهر فقط في البداية -->
                    <div class="text-end mb-2" id="ov-return-btn-wrap">
                        <button type="button"
                                class="btn btn-warning btn-sm px-4"
                                id="ov-return-toggle"
                                onclick="document.getElementById('ov-return-collapse').style.display='';this.closest('#ov-return-btn-wrap').style.display='none'">
                            <i class="bi bi-arrow-return-left me-1"></i>
                            <?= __('returns.add_new','تسجيل المرتجع') ?>
                        </button>
                    </div>

                    <!-- فورم الإرجاع — مخفي في البداية -->
                    <div id="ov-return-collapse" style="display:none">
                        <div class="ov-return-form">
                            <div class="ov-alert-warning mb-4">
                                <i class="bi bi-info-circle-fill flex-shrink-0 mt-1"></i>
                                <div>
                                    <?= __('returns.stock_note','The specified quantity will be restored to stock automatically.') ?>
                                    <strong class="d-block mt-1"><?= __('returns.one_time_warning','⚠ You can only process one return per order.') ?></strong>
                                </div>
                            </div>
                            <form method="POST" action="/admin/orders/return/<?= (int)$order['id'] ?>">
                                <?= \Core\System\Csrf::field() ?>
                                <div class="row g-3">

                                    <!-- سطر 1: نوع الإرجاع + الكمية + تاريخ الاستلام -->
                                    <div class="col-5">
                                        <label class="form-label fw-semibold small"><?= __('returns.type','Return Type') ?> *</label>
                                        <select name="return_type" class="form-select form-select-sm" required>
                                            <option value=""><?= __('actions.choose','Choose') ?></option>
                                            <option value="shipping_refused"><?= __('returns.type_shipping','Customer Refused') ?></option>
                                            <option value="admin_request"><?= __('returns.type_admin','Product Issue') ?></option>
                                            <option value="partial"><?= __('returns.type_partial','Partial Return') ?></option>
                                        </select>
                                    </div>
                                    <div class="col-2">
                                        <label class="form-label fw-semibold small"><?= __('returns.qty','Qty') ?> *</label>
                                        <input type="number" name="return_qty" class="form-control form-control-sm"
                                               min="1" max="<?= $orderQty ?>" value="<?= $orderQty ?>" required>
                                        <div class="text-muted" style="font-size:12px;margin-top:4px">
                                            <?= __('returns.max_qty','Max') ?>: <?= $orderQty ?>
                                        </div>
                                    </div>
                                    <div class="col-3">
                                        <label class="form-label fw-semibold small"><?= __('returns.received_at','Received Date') ?></label>
                                        <input type="date" name="received_at" class="form-control form-control-sm"
                                               value="<?= date('Y-m-d') ?>">
                                    </div>

                                    <!-- سطر 2: السبب + الملاحظات -->
                                    <div class="col-6">
                                        <label class="form-label fw-semibold small"><?= __('returns.reason','Reason') ?> *</label>
                                        <input type="text" name="return_reason" class="form-control form-control-sm"
                                               placeholder="<?= __('returns.reason_placeholder','e.g. Customer refused delivery') ?>" required>
                                    </div>
                                    <div class="col-6">
                                        <label class="form-label fw-semibold small"><?= __('returns.admin_notes','Notes') ?></label>
                                        <input type="text" name="admin_notes" class="form-control form-control-sm"
                                               placeholder="<?= __('returns.notes_placeholder','Additional notes...') ?>">
                                    </div>

                                    <!-- سطر 3: أزرار -->
                                    <div class="col-12 d-flex gap-2">
                                        <button type="submit" class="btn btn-warning btn-sm px-4"
                                                onclick="return confirm('<?= __('returns.confirm_msg','Confirm return?') ?>')">
                                            <i class="bi bi-arrow-return-left me-1"></i>
                                            <?= __('returns.submit','Process Return') ?>
                                        </button>
                                        <button type="button" class="btn btn-outline-secondary btn-sm"
                                                onclick="document.getElementById('ov-return-collapse').style.display='none';document.getElementById('ov-return-btn-wrap').style.display=''">
                                            <?= __('actions.cancel','Cancel') ?>
                                        </button>
                                    </div>

                                </div>
                            </form>
                        </div>
                    </div>
                    <?php endif; ?>

                </div>
            </div>
            <?php endif; ?>

        </div><!-- /left column -->

        <!-- ══ RIGHT SIDEBAR ══ -->
        <div class="ov-sidebar">

            <!-- Pricing summary -->
            <div class="ov-card">
                <div class="ov-card-head">
                    <i class="bi bi-receipt text-success"></i>
                    <?= __('orders.pricing','Pricing') ?>
                </div>
                <div class="ov-card-body">
                    <div class="ov-price-row">
                        <span><?= __('orders.product_price','Products') ?></span>
                        <span><?= number_format($productsTotal, 2) ?> <?= htmlspecialchars($currency) ?></span>
                    </div>
                    <div class="ov-price-row">
                        <span><?= __('orders.shipping_price','Shipping') ?></span>
                        <span><?= number_format($shippingPrice, 2) ?> <?= htmlspecialchars($currency) ?></span>
                    </div>
                    <div class="ov-price-row">
                        <span><?= __('orders.total','Total') ?></span>
                        <span style="color:#111827"><?= number_format($total, 2) ?> <?= htmlspecialchars($currency) ?></span>
                    </div>
                </div>
            </div>

            <!-- Order status -->
            <div class="ov-card">
                <div class="ov-card-head">
                    <i class="bi bi-info-circle text-secondary"></i>
                    <?= __('orders.status_info','Order Status') ?>
                </div>
                <div class="ov-card-body">
                    <div class="ov-info-row">
                        <span class="ov-info-label"><?= __('orders.order_status','Status') ?></span>
                        <span class="ov-status-badge" style="font-size:13px;padding:6px 12px;background:<?= $sc['bg'] ?>;color:<?= $sc['color'] ?>;border:1.5px solid <?= $sc['color'] ?>30">
                            <i class="bi <?= $sc['icon'] ?>"></i>
                            <?= $sc['label'] ?>
                        </span>
                    </div>
                    <div class="ov-info-row">
                        <span class="ov-info-label"><?= __('orders.payment_method','Payment') ?></span>
                        <span class="ov-info-val"><?= htmlspecialchars($order['payment_method'] ?? '—') ?></span>
                    </div>
                    <div class="ov-info-row">
                        <span class="ov-info-label"><?= __('orders.created_at','Created') ?></span>
                        <span class="ov-info-val"><?= date('d/m/Y H:i', strtotime($order['created_at'])) ?></span>
                    </div>
                    <?php if (!empty($callAttemptsCount)): ?>
                    <div class="ov-info-row">
                        <span class="ov-info-label"><?= __('calls.attempts','Call Attempts') ?></span>
                        <span class="ov-info-val">
                            <span class="badge bg-primary"><?= $callAttemptsCount ?></span>
                        </span>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="ov-card">
                <div class="ov-card-head">
                    <i class="bi bi-person-workspace text-primary"></i>
                    <?= __('team.workflow_assignment_card','Assignment & Workflow') ?>
                </div>
                <div class="ov-card-body d-grid gap-3">
                    <div class="rounded-3 border p-3">
                        <div class="text-muted small mb-1"><?= __('team.workflow_current_owner','Current owner') ?></div>
                        <?php if ($currentAssignment && !empty($currentAssignment['username'])): ?>
                        <div class="fw-bold"><?= htmlspecialchars($currentAssignment['username']) ?></div>
                        <div class="small text-muted">
                            <?= \Core\App\Models\TeamMemberModel::roleLabel($currentAssignment['role'] ?? 'confirmer') ?>
                            · <?= __('team.workflow_assigned_at','Assigned at') ?> <?= htmlspecialchars((string)($currentAssignment['assigned_at'] ?? '')) ?>
                        </div>
                        <?php else: ?>
                        <div class="text-muted"><?= __('team.workflow_unassigned','No active assignee yet') ?></div>
                        <?php endif; ?>
                    </div>

                    <?php if ($currentAssignment && !empty($currentAssignment['username'])): ?>
                    <div class="rounded-3 border p-3">
                        <div class="small text-muted">
                            <?= __('team.workflow_opened_status','Opened') ?>:
                            <?= !empty($workflowMeta['first_opened_at']) ? htmlspecialchars((string)$workflowMeta['first_opened_at']) : __('team.workflow_not_opened_yet','Not opened yet') ?>
                        </div>
                        <div class="small text-muted mt-1">
                            <?= __('team.workflow_reassignments_count','Reassignments') ?>: <?= (int)($workflowMeta['reassign_count'] ?? 0) ?>
                            · <?= __('team.workflow_last_action','Last action') ?>: <?= htmlspecialchars((string)($workflowMeta['last_action'] ?? '—')) ?>
                        </div>
                    </div>
                    <?php endif; ?>

                    <?php if ($isWorkflowManager): ?>
                    <form method="POST" action="/admin/team/assign-order" class="rounded-3 border p-3 d-grid gap-2">
                        <?= \Core\System\Csrf::field() ?>
                        <input type="hidden" name="order_id" value="<?= (int)$order['id'] ?>">
                        <label class="form-label fw-semibold mb-0"><?= __('team.workflow_manager_assign','Manager assignment') ?></label>
                        <select name="admin_id" class="form-select form-select-sm">
                            <option value=""><?= __('team.workflow_choose_agent','Choose agent') ?></option>
                            <?php foreach ($assignableMembers as $member): ?>
                            <option value="<?= (int)$member['id'] ?>" <?= $currentAssignment && (int)$currentAssignment['admin_id'] === (int)$member['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($member['username']) ?> · <?= __('team.workflow_current_load','Current load') ?>: <?= (int)($member['pending_count'] ?? 0) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                        <input type="text" name="assign_note" class="form-control form-control-sm" placeholder="<?= __('team.workflow_assign_note_ph','Optional note for this assignment') ?>">
                        <button type="submit" class="btn btn-outline-primary btn-sm">
                            <i class="bi bi-person-check me-1"></i><?= __('team.workflow_assign_now','Assign now') ?>
                        </button>
                    </form>

                    <form method="POST" action="/admin/team/assign-order" class="rounded-3 border p-3 d-grid gap-2">
                        <?= \Core\System\Csrf::field() ?>
                        <input type="hidden" name="order_id" value="<?= (int)$order['id'] ?>">
                        <input type="hidden" name="assign_mode" value="auto">
                        <input type="text" name="assign_note" class="form-control form-control-sm" placeholder="<?= __('team.workflow_auto_note_ph','Why should the order be redistributed?') ?>">
                        <button type="submit" class="btn btn-outline-secondary btn-sm">
                            <i class="bi bi-shuffle me-1"></i><?= __('team.workflow_auto_redistribute','Auto redistribute') ?>
                        </button>
                    </form>
                    <?php endif; ?>

                    <?php if ($orderStatus === 'pending' && ($isAssignedConfirmer || $isWorkflowManager)): ?>
                    <form method="POST" action="/admin/orders/workflow-action/<?= (int)$order['id'] ?>" class="rounded-3 border p-3 d-grid gap-2">
                        <?= \Core\System\Csrf::field() ?>
                        <label class="form-label fw-semibold mb-0"><?= __('team.workflow_agent_actions','Handling actions') ?></label>
                        <select name="workflow_action" class="form-select form-select-sm" required>
                            <option value=""><?= __('team.workflow_select_action','Choose action') ?></option>
                            <option value="call_made"><?= __('team.workflow_action_call','Call made') ?></option>
                            <option value="no_answer"><?= __('team.workflow_action_no_answer','No answer') ?></option>
                            <option value="closed"><?= __('team.workflow_action_closed','Closed') ?></option>
                            <option value="deferred"><?= __('team.workflow_action_deferred','Deferred') ?></option>
                            <option value="callback_requested"><?= __('team.workflow_action_callback','Callback requested') ?></option>
                            <option value="cancelled"><?= __('team.workflow_action_cancelled','Cancelled') ?></option>
                            <option value="address_issue"><?= __('team.workflow_action_address','Address issue') ?></option>
                            <option value="wrong_number"><?= __('team.workflow_action_wrong_number','Wrong number') ?></option>
                            <option value="needs_manager"><?= __('team.workflow_action_manager','Escalate to manager') ?></option>
                            <option value="note_added"><?= __('team.workflow_action_note','Internal note') ?></option>
                            <option value="decline_processing"><?= __('team.workflow_action_decline','Decline processing and reassign') ?></option>
                        </select>
                        <textarea name="workflow_note" rows="3" class="form-control form-control-sm" placeholder="<?= __('team.workflow_note_ph','Write what happened with the customer or why the order needs follow-up') ?>"></textarea>
                        <button type="submit" class="btn btn-outline-dark btn-sm">
                            <i class="bi bi-save me-1"></i><?= __('team.workflow_save_action','Save workflow action') ?>
                        </button>
                    </form>
                    <?php endif; ?>
                </div>
            </div>

            <?php if (!empty($workflowTimeline)): ?>
            <div class="ov-card">
                <div class="ov-card-head">
                    <i class="bi bi-activity text-info"></i>
                    <?= __('team.workflow_timeline','Workflow Timeline') ?>
                </div>
                <div class="ov-card-body">
                    <div class="ov-timeline">
                        <?php foreach ($workflowTimeline as $log): ?>
                        <div class="ov-tl-item">
                            <div class="ov-tl-dot pending">
                                <i class="bi bi-dot"></i>
                            </div>
                            <div class="ov-tl-body">
                                <span class="ov-tl-action"><?= htmlspecialchars((string)__('team.workflow_event_'.$log['event_type'], str_replace('_', ' ', (string)$log['event_type']))) ?></span>
                                <div class="ov-tl-meta">
                                    <i class="bi bi-person me-1"></i><?= htmlspecialchars((string)($log['admin_name'] ?? 'System')) ?>
                                    <?php if (!empty($log['target_admin_name'])): ?>
                                        · <?= __('team.workflow_to_agent','to') ?> <?= htmlspecialchars((string)$log['target_admin_name']) ?>
                                    <?php endif; ?>
                                    · <?= htmlspecialchars((string)($log['created_at'] ?? '')) ?>
                                </div>
                                <?php if (!empty($log['note'])): ?>
                                <div class="small text-muted mt-1"><?= nl2br(htmlspecialchars((string)$log['note'])) ?></div>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <?php if (!empty($workflowAssignedHistory)): ?>
            <div class="ov-card">
                <div class="ov-card-head">
                    <i class="bi bi-diagram-2 text-secondary"></i>
                    <?= __('team.workflow_assignment_history','Assignment History') ?>
                </div>
                <div class="ov-card-body">
                    <div class="ov-timeline">
                        <?php foreach (array_reverse($workflowAssignedHistory) as $history): ?>
                        <div class="ov-tl-item">
                            <div class="ov-tl-dot pending">
                                <i class="bi bi-person-badge"></i>
                            </div>
                            <div class="ov-tl-body">
                                <?php $historyAdminId = (int)($history['admin_id'] ?? 0); ?>
                                <span class="ov-tl-action"><?= __('team.workflow_assigned_to_agent','Assigned to agent') ?> <?= htmlspecialchars($assignableMap[$historyAdminId] ?? ('#' . $historyAdminId)) ?></span>
                                <div class="ov-tl-meta"><?= htmlspecialchars((string)($history['assigned_at'] ?? '')) ?></div>
                                <?php if (!empty($history['reason'])): ?>
                                <div class="small text-muted mt-1"><?= htmlspecialchars((string)$history['reason']) ?></div>
                                <?php endif; ?>
                                <?php if (!empty($history['note'])): ?>
                                <div class="small text-muted mt-1"><?= nl2br(htmlspecialchars((string)$history['note'])) ?></div>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <!-- Quick actions (pending) -->
            <?php if ($orderStatus === 'pending' && ($isWorkflowManager || !$currentAssignment || $isAssignedConfirmer || $currentAdminRole !== 'confirmer')): ?>
            <div class="ov-card">
                <div class="ov-card-head">
                    <i class="bi bi-lightning-fill text-warning"></i>
                    <?= __('orders.quick_actions','Quick Actions') ?>
                </div>
                <div class="ov-card-body d-grid gap-2">
                    <!-- CONFIRM: opens mandatory call-log modal first -->
                    <button type="button" class="btn btn-success w-100"
                            onclick="openConfirmModal()">
                        <i class="bi bi-check-lg me-1"></i><?= __('orders.status_confirmed','Confirm') ?>
                    </button>
                    <form method="POST" action="/admin/orders/status/<?= (int)$order['id'] ?>">
                        <?= \Core\System\Csrf::field() ?>
                        <input type="hidden" name="status" value="rejected">
                        <button type="submit" class="btn btn-outline-danger w-100"
                                onclick="return confirm('<?= __('orders.reject_action','Reject this order?') ?>')">
                            <i class="bi bi-x-lg me-1"></i><?= __('orders.status_rejected','Reject') ?>
                        </button>
                    </form>
                </div>
            </div>
            <?php endif; ?>

            <?php if ($orderStatus === 'pending' && $currentAdminRole === 'confirmer' && $currentAssignment && !$isAssignedConfirmer): ?>
            <div class="alert alert-warning small">
                <i class="bi bi-lock me-1"></i><?= __('team.workflow_locked_other_agent','This order is currently assigned to another agent. You can view it, but processing is locked for you.') ?>
            </div>
            <?php endif; ?>

            <!-- Shipping actions -->
            <?php if ($orderStatus === 'confirmed' && empty($shipping['tracking'])): ?>
            <div class="ov-card">
                <div class="ov-card-head">
                    <i class="bi bi-truck text-info"></i>
                    <?= __('shipping.actions','Shipping Actions') ?>
                </div>
                <div class="ov-card-body d-grid gap-2">
                    <a href="/admin/orders/prepare-shipping/<?= (int)$order['id'] ?>"
                       class="btn btn-outline-info w-100">
                        <i class="bi bi-box-seam me-1"></i>
                        <?= __('shipping.prepare','Prepare Shipment') ?>
                    </a>
                </div>
            </div>
            <?php endif; ?>

            <!-- Maystro actions (when already shipped via Maystro) -->
            <?php if (($shipping['provider'] ?? '') === 'maystro' && !empty($shipping['tracking'])): ?>
            <div class="ov-card" style="border-color:#3b82f6">
                <div class="ov-card-head" style="background:#eff6ff">
                    <img src="/admin/assets/img/maystro.png" height="18" alt=""> Maystro
                </div>
                <div class="ov-card-body d-grid gap-2">
                    <a href="/admin/orders/maystro/label/<?= (int)$order['id'] ?>"
                       class="btn btn-outline-primary btn-sm w-100" target="_blank">
                        <i class="bi bi-printer me-1"></i>
                        <?= __('shipping.print_label','Print Label (Bordereau)') ?>
                    </a>
                    <?php if (!$alreadyReturned): ?>
                    <button type="button"
                            class="btn btn-outline-warning btn-sm w-100"
                            onclick="requestMaystroRefund(<?= (int)$order['id'] ?>)">
                        <i class="bi bi-arrow-counterclockwise me-1"></i>
                        <?= __('returns.provider_return_request','Request Return') ?>
                    </button>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- Ecotrack actions (when already shipped via Ecotrack) -->
            <?php if (($shipping['provider'] ?? '') === 'ecotrack' && !empty($shipping['tracking'])): ?>
            <div class="ov-card" style="border-color:#3b82f6">
                <div class="ov-card-head" style="background:#eff6ff">
                    <img src="/admin/assets/img/ecotrack.png" height="18" alt=""> Ecotrack
                </div>
                <div class="ov-card-body d-grid gap-2">
                    <a href="/admin/orders/ecotrack/label?tracking=<?= urlencode($shipping['tracking']) ?>"
                       class="btn btn-outline-primary btn-sm w-100" target="_blank">
                        <i class="bi bi-printer me-1"></i>
                        <?= __('shipping.print_label','Print Label (Bordereau)') ?>
                    </a>
                    <?php if (!$alreadyReturned): ?>
                    <form method="POST" action="/admin/orders/return-provider/<?= (int)$order['id'] ?>">
                        <?= \Core\System\Csrf::field() ?>
                        <button type="submit"
                                class="btn btn-outline-warning btn-sm w-100"
                                onclick="return confirm('<?= __('returns.provider_return_confirm','Send a return request to the shipping provider?') ?>')">
                            <i class="bi bi-arrow-counterclockwise me-1"></i>
                            <?= __('returns.provider_return_request','Request Return') ?>
                        </button>
                    </form>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- ── Processed By ── -->
            <?php
            $processorEntry = null;
            foreach (array_reverse($actionLog) as $_logEntry) {
                if (in_array($_logEntry['action'] ?? '', ['confirmed','rejected'], true)) {
                    $processorEntry = $_logEntry;
                    break;
                }
            }
            $phoneEntry = null;
            foreach (array_reverse($actionLog) as $_logEntry) {
                if (($_logEntry['action'] ?? '') === 'call' || !empty($_logEntry['call_result'])) {
                    $phoneEntry = $_logEntry;
                    break;
                }
            }
            if ($processorEntry || $phoneEntry):
            ?>
            <div class="ov-card">
                <div class="ov-card-head">
                    <i class="bi bi-person-badge text-primary"></i>
                    <?= __('orders.processed_by','Processed By') ?>
                </div>
                <div class="ov-card-body" style="padding:16px 20px;">
                    <?php if ($processorEntry): ?>
                    <div style="display:flex;align-items:center;gap:10px;margin-bottom:<?= $phoneEntry ? '14px' : '0' ?>">
                        <div style="width:38px;height:38px;border-radius:50%;background:<?= ($processorEntry['action'] ?? '') === 'confirmed' ? '#d1fae5' : '#fee2e2' ?>;display:flex;align-items:center;justify-content:center;flex-shrink:0">
                            <i class="bi <?= ($processorEntry['action'] ?? '') === 'confirmed' ? 'bi-check-lg' : 'bi-x-lg' ?>"
                               style="color:<?= ($processorEntry['action'] ?? '') === 'confirmed' ? '#059669' : '#dc2626' ?>;font-size:16px"></i>
                        </div>
                        <div style="min-width:0;flex:1">
                            <div style="font-size:14px;font-weight:700;color:#111827;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">
                                <?= htmlspecialchars($processorEntry['admin_name'] ?? '—') ?>
                            </div>
                            <?php if (!empty($processorEntry['admin_role'])): ?>
                            <div style="font-size:12px;color:#6b7280">
                                <?php
                                if (class_exists('\Core\App\Models\TeamMemberModel'))
                                    echo \Core\App\Models\TeamMemberModel::roleLabel($processorEntry['admin_role']);
                                else echo htmlspecialchars($processorEntry['admin_role']);
                                ?>
                            </div>
                            <?php endif; ?>
                            <div style="font-size:11px;color:#9ca3af;margin-top:2px">
                                <?= __('orders.order_'.($processorEntry['action'] ?? 'confirmed'),$processorEntry['action'] ?? '') ?>
                                · <?= htmlspecialchars($processorEntry['at'] ?? '') ?>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    <?php if ($phoneEntry): ?>
                    <div style="border-top:1px solid #f3f4f6;padding-top:12px;display:flex;align-items:center;gap:10px">
                        <div style="width:38px;height:38px;border-radius:50%;background:#eff6ff;display:flex;align-items:center;justify-content:center;flex-shrink:0">
                            <i class="bi bi-telephone-fill" style="color:#3b82f6;font-size:15px"></i>
                        </div>
                        <div style="min-width:0;flex:1">
                            <div style="font-size:14px;font-weight:700;color:#111827;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">
                                <?= htmlspecialchars($phoneEntry['admin_name'] ?? '—') ?>
                            </div>
                            <?php if (!empty($phoneEntry['admin_role'])): ?>
                            <div style="font-size:12px;color:#6b7280">
                                <?php
                                if (class_exists('\Core\App\Models\TeamMemberModel'))
                                    echo \Core\App\Models\TeamMemberModel::roleLabel($phoneEntry['admin_role']);
                                else echo htmlspecialchars($phoneEntry['admin_role']);
                                ?>
                            </div>
                            <?php endif; ?>
                            <div style="font-size:11px;color:#9ca3af;margin-top:2px">
                                <?= __('orders.phone_confirmed','Phone Confirmation') ?>
                                · <?= htmlspecialchars($phoneEntry['at'] ?? '') ?>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>

        </div><!-- /sidebar -->

    </div><!-- /ov-grid -->
</div><!-- /ov-page -->

<!-- ═══ CONFIRM ORDER MODAL (mandatory call log) ══════════════════════════ -->
<?php if ($orderStatus === 'pending'): ?>
<div class="modal fade" id="confirmOrderModal" tabindex="-1" aria-labelledby="confirmOrderModalLabel" aria-modal="true" role="dialog">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title fw-bold" id="confirmOrderModalLabel">
                    <i class="bi bi-telephone-fill me-2"></i>
                    <?= __('orders.confirm_modal_title', 'Confirm Order — Log Call') ?>
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <div class="alert alert-info py-2 small mb-3">
                    <i class="bi bi-info-circle me-1"></i>
                    <?= __('orders.confirm_modal_info', 'Before confirming, you must log the phone call result. This is recorded in your statistics.') ?>
                </div>

                <!-- Call result — required -->
                <div class="mb-3">
                    <label class="form-label fw-semibold">
                        <?= __('calls.result', 'Call Result') ?>
                        <span class="text-danger">*</span>
                    </label>
                    <select id="confirmCallResult" class="form-select" required>
                        <option value="">— <?= __('calls.select_result', 'Select result') ?> —</option>
                        <option value="confirmed"><?= __('calls.confirmed', '✅ Confirmed by phone') ?></option>
                        <option value="interested"><?= __('calls.interested', '👍 Interested') ?></option>
                        <option value="no_answer"><?= __('calls.no_answer', '📵 No answer') ?></option>
                        <option value="busy"><?= __('calls.busy', '📞 Busy') ?></option>
                        <option value="callback_later"><?= __('calls.callback_later', '🕐 Callback later') ?></option>
                    </select>
                </div>

                <!-- Note — optional -->
                <div class="mb-3">
                    <label class="form-label fw-semibold"><?= __('calls.note', 'Note') ?> <span class="text-muted small">(<?= __('actions.optional','optional') ?>)</span></label>
                    <textarea id="confirmCallNote" class="form-control" rows="2"
                              placeholder="<?= __('calls.note_placeholder', 'Customer confirmed by phone, address verified...') ?>"></textarea>
                </div>

                <div id="confirmModalMsg" class="d-none"></div>
            </div>
            <div class="modal-footer border-top-0 gap-2">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                    <?= __('actions.cancel', 'Cancel') ?>
                </button>
                <button type="button" id="btnConfirmWithCall" class="btn btn-success px-4 fw-bold"
                        onclick="submitConfirmWithCall(<?= (int)$order['id'] ?>)">
                    <i class="bi bi-check-circle me-1"></i>
                    <?= __('orders.confirm_and_log', 'Confirm & Log Call') ?>
                </button>
            </div>
        </div>
    </div>
</div>

<script>
function openConfirmModal() {
    document.getElementById('confirmCallResult').value = '';
    document.getElementById('confirmCallNote').value   = '';
    document.getElementById('confirmModalMsg').className = 'd-none';
    document.getElementById('btnConfirmWithCall').disabled = false;
    new bootstrap.Modal(document.getElementById('confirmOrderModal')).show();
}

async function submitConfirmWithCall(orderId) {
    const result = document.getElementById('confirmCallResult').value;
    const note   = document.getElementById('confirmCallNote').value.trim();
    const msgEl  = document.getElementById('confirmModalMsg');
    const btn    = document.getElementById('btnConfirmWithCall');

    if (!result) {
        msgEl.className = 'alert alert-warning py-2 small';
        msgEl.textContent = '<?= __('calls.select_result_required', 'Please select a call result.') ?>';
        msgEl.classList.remove('d-none');
        return;
    }

    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span><?= __('actions.saving','Saving...') ?>';

    try {
        /* Step 1 — log the call attempt */
        const fd1 = new FormData();
        fd1.append('_csrf',  '<?= \Core\System\Csrf::token() ?>');
        fd1.append('result', result);
        fd1.append('note',   note);

        const r1   = await fetch('/admin/orders/call-attempt/' + orderId, { method: 'POST', body: fd1, credentials: 'same-origin' });
        const res1 = await r1.json();

        if (!res1.success) {
            throw new Error(res1.error || 'Call log failed');
        }

        /* Step 2 — confirm the order */
        const fd2 = new FormData();
        fd2.append('_csrf',  '<?= \Core\System\Csrf::token() ?>');
        fd2.append('status', 'confirmed');
        fd2.append('call_result', result);
        fd2.append('call_note',   note);

        const r2 = await fetch('/admin/orders/status/' + orderId, { method: 'POST', body: fd2, credentials: 'same-origin' });

        /* redirect follows automatically */
        msgEl.className = 'alert alert-success py-2 small';
        msgEl.textContent = '<?= __('orders.confirmed_success', 'Order confirmed & call logged!') ?>';
        msgEl.classList.remove('d-none');

        setTimeout(() => { window.location.href = r2.url || window.location.href; }, 600);
        window.location.href = '/admin/orders/prepare-shipping/' + orderId;

    } catch (e) {
        msgEl.className = 'alert alert-danger py-2 small';
        msgEl.textContent = e.message;
        msgEl.classList.remove('d-none');
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-check-circle me-1"></i><?= __('orders.confirm_and_log', 'Confirm & Log Call') ?>';
    }
}
</script>
<?php endif; ?>

<script>
function logCall(orderId) {
    const result = document.getElementById('callResult').value;
    const note   = document.getElementById('callNote').value.trim();
    const msg    = document.getElementById('callMsg');
    if (!result) {
        msg.className = 'mt-2 alert alert-warning py-2 small';
        msg.textContent = '<?= __("calls.select_result_required","Please select a call result") ?>';
        msg.classList.remove('d-none'); return;
    }
    const form = new FormData();
    form.append('result', result); form.append('note', note);
    form.append('_csrf', document.querySelector('input[name=_csrf]')?.value || '');
    fetch('/admin/orders/call-attempt/' + orderId, { method:'POST', body:form, credentials:'same-origin' })
    .then(r => r.json())
    .then(res => {
        if (res.success) {
            msg.className = 'mt-2 alert alert-success py-2 small';
            msg.innerHTML = '<i class="bi bi-check-circle me-1"></i><?= __("calls.logged","Call logged") ?> #' + res.count;
            msg.classList.remove('d-none');
            document.getElementById('callResult').value = '';
            document.getElementById('callNote').value = '';
            setTimeout(() => location.reload(), ['confirmed','rejected'].includes(result) ? 600 : 1400);
        } else {
            msg.className = 'mt-2 alert alert-danger py-2 small';
            msg.textContent = res.error || 'Error'; msg.classList.remove('d-none');
        }
    })
    .catch(e => { msg.className='mt-2 alert alert-danger py-2 small'; msg.textContent=e.message; msg.classList.remove('d-none'); });
}
</script>

<script>
/* ── Maystro: Request return/refund from provider ── */
function requestMaystroRefund(orderId) {
    if (!confirm('<?= __('returns.provider_return_confirm','Send a return request to Maystro?') ?>')) return;

    const csrf = document.querySelector('input[name="_csrf"]')?.value || '';

    fetch('/admin/orders/maystro/refund/' + orderId, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ _csrf: csrf }),
        credentials: 'same-origin',
    })
    .then(r => r.json())
    .then(res => {
        if (res.success) {
            alert('<?= __('returns.provider_return_success','Return request sent to Maystro successfully.') ?>');
            location.reload();
        } else if (res.is_duplicate) {
            // Show friendly duplicate note
            alert(res.error || '<?= __('returns.maystro_duplicate_note', 'تعذر إنشاء الإرجاع: يُرجى المحاولة بعد 24 ساعة من إنشاء الشحنة الأصلية.') ?>');
        } else {
            alert('<?= __('returns.provider_return_failed','Return request failed') ?>' + ': ' + (res.error || res.message || 'Unknown error'));
        }
    })
    .catch(e => alert('Error: ' + e.message));
}
</script>
