<?php
$tags = array_values(array_filter(explode(',', (string)($customer['tags'] ?? ''))));
$tagColors = ['vip'=>'warning','returning'=>'success','new'=>'info'];
$tagLabels = [
    'vip'       => __('customers.tag.vip', 'VIP'),
    'returning' => __('customers.tag.returning', 'Returning'),
    'new'       => __('customers.tag.new', 'New'),
];
$noteLines = preg_split("/\r\n|\r|\n/", trim((string)($customer['notes'] ?? ''))) ?: [];
$noteLines = array_values(array_filter(array_map('trim', $noteLines)));

$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'=>'الأبيض سيدي الشيخ']
];
$wilayaCodeRaw = (string)($customer['wilaya_code'] ?? '');
$wilayaCodeInt = (int) ltrim($wilayaCodeRaw, '0');
$wilayaLabel = $wilayaCodeRaw !== '' ? (($dzWilayas[$wilayaCodeInt]['fr'] ?? $wilayaCodeRaw)) : '—';
?>

<div class="content-wrapper">
<section class="content pt-3">
<div class="container-fluid pb-5">

    <div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4">
        <div>
            <div class="d-flex align-items-center gap-3 mb-1">
                <div class="rounded-circle d-flex align-items-center justify-content-center flex-shrink-0"
                     style="width:52px;height:52px;background:var(--bs-primary-bg-subtle,rgba(13,110,253,.1))">
                    <i class="bi bi-person-vcard-fill text-primary fs-4"></i>
                </div>
                <div>
                    <div class="d-flex align-items-center gap-2 flex-wrap mb-1">
                        <span class="badge bg-light text-dark border">#<?= (int)$customer['id'] ?></span>
                        <h3 class="mb-0 fw-bold"><?= htmlspecialchars($customer['full_name'] ?: __('customers.no_name', 'Customer')) ?></h3>
                    </div>
                    <p class="text-muted mb-0 small"><?= __('customers.details_subtitle', 'Customer profile, notes, recent orders and WhatsApp history') ?></p>
                </div>
            </div>
        </div>
        <div class="d-flex flex-wrap gap-2">
            <a href="https://wa.me/<?= ltrim((string)($customer['phone_normalized'] ?? ''), '+') ?>" target="_blank" rel="noopener" class="btn btn-success">
                <i class="bi bi-whatsapp me-2"></i>
                <?= __('customers.contact_whatsapp', 'Open WhatsApp') ?>
            </a>
            <a href="/admin/customers" class="btn btn-outline-secondary">
                <i class="bi bi-arrow-right me-2"></i>
                <?= __('actions.back', 'Back') ?>
            </a>
        </div>
    </div>

     <div class="row g-3 mb-4">
        <div class="col-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100" style="border-top:3px solid #0d6efd !important">
                <div class="card-body px-4 py-3">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div class="rounded-circle d-flex align-items-center justify-content-center bg-primary-subtle"
                             style="width:42px;height:42px">
                            <i class="bi bi-bag-check fs-5 text-primary"></i>
                        </div>
                    </div>
                    <div class="fw-bold fs-2 lh-1 mb-1"><?= (int)($customer['orders_count'] ?? 0) ?></div>
                    <div class="text-muted small"><?= __('customers.col.orders', 'Orders') ?></div>
                    <div class="text-muted" style="font-size:.72rem"><?= __('customers.active_shipped_orders', 'Active shipped orders counted for this customer') ?></div>
                </div>
            </div>
        </div>
        <div class="col-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100" style="border-top:3px solid #198754 !important">
                <div class="card-body px-4 py-3">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div class="rounded-circle d-flex align-items-center justify-content-center bg-success-subtle"
                             style="width:42px;height:42px">
                            <i class="bi bi-cash-stack fs-5 text-success"></i>
                        </div>
                    </div>
                    <div class="fw-bold fs-2 lh-1 mb-1"><?= number_format((float)($customer['total_spent'] ?? 0), 0) ?></div>
                    <div class="text-muted small"><?= __('customers.col.spent', 'Total Spent') ?></div>
                    <div class="text-muted" style="font-size:.72rem"><?= __('finance.currency', 'DZD') ?></div>
                </div>
            </div>
        </div>
        <div class="col-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100" style="border-top:3px solid #6f42c1 !important">
                <div class="card-body px-4 py-3">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div class="rounded-circle d-flex align-items-center justify-content-center"
                             style="width:42px;height:42px;background:#6f42c120">
                            <i class="bi bi-chat-dots fs-5" style="color:#6f42c1"></i>
                        </div>
                    </div>
                    <div class="fw-bold fs-2 lh-1 mb-1"><?= (int)($customer['msgs_sent'] ?? 0) ?></div>
                    <div class="text-muted small"><?= __('customers.messages_sent', 'Messages Sent') ?></div>
                    <div class="text-muted" style="font-size:.72rem"><?= __('customers.whatsapp_history', 'Recorded WhatsApp messages') ?></div>
                </div>
            </div>
        </div>
        <div class="col-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100" style="border-top:3px solid #ffc107 !important">
                <div class="card-body px-4 py-3">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div class="rounded-circle d-flex align-items-center justify-content-center bg-warning-subtle"
                             style="width:42px;height:42px">
                            <i class="bi bi-calendar-event fs-5 text-warning"></i>
                        </div>
                    </div>
                    <div class="fw-bold lh-1 mb-1" style="font-size:1.65rem;"><?= !empty($customer['first_order_at']) ? date('d/m/Y', strtotime($customer['first_order_at'])) : '—' ?></div>
                    <div class="text-muted small"><?= __('customers.orders_since','since') ?></div>
                    <div class="text-muted" style="font-size:.72rem"><?= __('customers.last_order_label', 'Last order') ?>: <?= !empty($customer['last_order_at']) ? date('d/m/Y', strtotime($customer['last_order_at'])) : '—' ?></div>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-3">
        <div class="col-lg-4">
            <div class="card border-0 shadow-sm mb-3">
                <div class="card-header bg-white border-bottom py-3">
                    <h6 class="mb-0 fw-semibold"><i class="bi bi-person-lines-fill me-2 text-primary"></i><?= __('customers.profile', 'Customer Profile') ?></h6>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <div class="text-muted small mb-1"><?= __('customers.col.phone', 'Phone') ?></div>
                        <div class="fw-semibold">
                            <a href="https://wa.me/<?= ltrim((string)($customer['phone_normalized'] ?? ''), '+') ?>" target="_blank" class="text-decoration-none">
                                <?= htmlspecialchars((string)($customer['phone'] ?? '—')) ?>
                            </a>
                        </div>
                        <div class="text-muted small"><?= htmlspecialchars((string)($customer['phone_normalized'] ?? '')) ?></div>
                    </div>
                    <div class="mb-3">
                        <div class="text-muted small mb-1"><?= __('customers.col.city', 'City') ?></div>
                        <div class="fw-semibold"><?= htmlspecialchars((string)($customer['city'] ?? '—')) ?></div>
                    </div>
                    <div class="mb-3">
                        <div class="text-muted small mb-1"><?= __('customers.wilaya', 'Wilaya') ?></div>
                        <div class="fw-semibold"><?= htmlspecialchars($wilayaLabel) ?></div>
                    </div>
                    <div class="mb-0">
                        <div class="text-muted small mb-2"><?= __('customers.col.tags', 'Tags') ?></div>
                        <?php if ($tags): ?>
                            <div class="d-flex flex-wrap gap-2">
                                <?php foreach ($tags as $tag): ?>
                                    <span class="badge bg-<?= $tagColors[$tag] ?? 'secondary' ?>-subtle text-<?= $tagColors[$tag] ?? 'secondary' ?> border border-<?= $tagColors[$tag] ?? 'secondary' ?>-subtle">
                                        <?= $tagLabels[$tag] ?? htmlspecialchars($tag) ?>
                                    </span>
                                <?php endforeach; ?>
                            </div>
                        <?php else: ?>
                            <div class="text-muted small"><?= __('customers.no_tags', 'No active tag') ?></div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                    <h6 class="mb-0 fw-semibold"><i class="bi bi-journal-text me-2 text-success"></i><?= __('customers.notes', 'Notes') ?></h6>
                    <span class="badge bg-secondary rounded-pill"><?= count($noteLines) ?></span>
                </div>
                <div class="card-body">
                    <?php if ($noteLines): ?>
                        <div class="timeline-notes d-flex flex-column gap-2">
                            <?php foreach (array_reverse($noteLines) as $line): ?>
                                <div class="border rounded-3 p-2 bg-light-subtle">
                                    <div class="small text-dark"><?= nl2br(htmlspecialchars($line)) ?></div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="text-muted small"><?= __('customers.no_notes', 'No notes available for this customer yet.') ?></div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div class="col-lg-8">
            <div class="card border-0 shadow-sm mb-3">
                <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                    <h6 class="mb-0 fw-semibold"><i class="bi bi-bag-check me-2 text-primary"></i><?= __('customers.recent_orders', 'Recent Orders') ?></h6>
                    <span class="badge bg-secondary rounded-pill"><?= count($customerOrders) ?></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">#</th>
                                    <th><?= __('orders.status', 'Status') ?></th>
                                    <th><?= __('orders.tracking_number', 'Tracking') ?></th>
                                    <th><?= __('customers.col.spent', 'Total Spent') ?></th>
                                    <th><?= __('customers.col.city', 'City') ?></th>
                                    <th><?= __('customers.col.last_order', 'Date') ?></th>
                                    <th class="text-center"><?= __('actions.view', 'View') ?></th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php if (empty($customerOrders)): ?>
                                <tr><td colspan="7" class="text-center text-muted py-4"><?= __('customers.no_orders', 'No orders found for this customer.') ?></td></tr>
                            <?php else: ?>
                                <?php foreach ($customerOrders as $order):
                                    $tracking = trim((string)($order['tracking_number'] ?? '')) ?: trim((string)($order['tracking_from_extra'] ?? ''));
                                    $statusText = trim((string)($order['order_status'] ?? $order['status'] ?? 'pending'));
                                ?>
                                <tr>
                                    <td class="ps-3 fw-semibold">#<?= (int)$order['id'] ?></td>
                                    <td><span class="badge bg-light text-dark border"><?= htmlspecialchars($statusText) ?></span></td>
                                    <td><?= $tracking !== '' ? htmlspecialchars($tracking) : '<span class="text-muted small">—</span>' ?></td>
                                    <td class="fw-semibold">
                                        <?= number_format((float)($order['computed_total'] ?? 0), 0) ?>
                                        <small class="text-muted"><?= __('finance.currency', 'DZD') ?></small>
                                    </td>
                                    <td class="text-muted small"><?= htmlspecialchars((string)($order['shipping_destination_city'] ?? '—')) ?></td>
                                    <td class="text-muted small"><?= !empty($order['created_at']) ? date('d/m/Y H:i', strtotime($order['created_at'])) : '—' ?></td>
                                    <td class="text-center">
                                        <a href="/admin/orders/view/<?= (int)$order['id'] ?>" class="btn btn-sm btn-outline-primary">
                                            <i class="bi bi-box-arrow-up-left"></i>
                                        </a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                    <h6 class="mb-0 fw-semibold"><i class="bi bi-chat-dots me-2 text-muted"></i><?= __('customers.whatsapp_history', 'WhatsApp History') ?></h6>
                    <span class="badge bg-secondary rounded-pill"><?= count($customerMessages) ?></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"><?= __('customers.message_type', 'Type') ?></th>
                                    <th><?= __('customers.message_status', 'Status') ?></th>
                                    <th><?= __('customers.message_campaign', 'Campaign / Event') ?></th>
                                    <th><?= __('customers.message_provider', 'Provider') ?></th>
                                    <th><?= __('customers.col.last_order', 'Date') ?></th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php if (empty($customerMessages)): ?>
                                <tr><td colspan="5" class="text-center text-muted py-4"><?= __('customers.no_messages', 'No WhatsApp messages logged for this customer yet.') ?></td></tr>
                            <?php else: ?>
                                <?php foreach ($customerMessages as $msg): ?>
                                <tr>
                                    <td class="ps-3">
                                        <div class="fw-semibold"><?= htmlspecialchars((string)($msg['type'] ?? '—')) ?></div>
                                        <div class="text-muted small text-truncate" style="max-width:320px"><?= htmlspecialchars((string)($msg['message'] ?? '')) ?></div>
                                    </td>
                                    <td><span class="badge <?= ($msg['status'] ?? '') === 'sent' ? 'bg-success-subtle text-success border border-success-subtle' : 'bg-danger-subtle text-danger border border-danger-subtle' ?>"><?= htmlspecialchars((string)($msg['status'] ?? 'pending')) ?></span></td>
                                    <td>
                                        <div class="small fw-semibold"><?= htmlspecialchars((string)($msg['campaign'] ?? '—')) ?></div>
                                        <div class="text-muted small"><?= htmlspecialchars((string)($msg['event'] ?? '')) ?></div>
                                    </td>
                                    <td class="text-muted small"><?= htmlspecialchars((string)($msg['provider'] ?? '—')) ?></td>
                                    <td class="text-muted small"><?= !empty($msg['sent_at']) ? date('d/m/Y H:i', strtotime($msg['sent_at'])) : (!empty($msg['created_at']) ? date('d/m/Y H:i', strtotime($msg['created_at'])) : '—') ?></td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

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