<?php
$tier     = customer_tier((int)$customer['delivered_orders']);
$initials = strtoupper(mb_substr($customer['name'], 0, 2));
$colors   = ['bg-primary','bg-success','bg-info','bg-warning','bg-danger','bg-secondary'];
$color    = $colors[abs(crc32($customer['email'])) % count($colors)];

$statusColors = [
    'pending'   => 'warning', 'confirmed' => 'info',    'cooking'   => 'primary',
    'ready'     => 'success', 'picked_up' => 'success', 'on_the_way'=> 'warning',
    'delivered' => 'success', 'cancelled' => 'danger',
];
?>

<style>
.tier-badge{display:inline-flex;align-items:center;gap:5px;font-size:.8rem;font-weight:700;
    padding:4px 12px;border-radius:20px;}
.badge-platinum{background:#e0f7fa;color:#006064;}
.badge-gold    {background:#fff8e1;color:#f57f17;}
.badge-silver  {background:#f5f5f5;color:#424242;}
.badge-bronze  {background:#fbe9e7;color:#bf360c;}
.badge-new     {background:#f3f4f6;color:#6b7280;}
.stat-box{background:#fff;border-radius:12px;padding:16px 20px;box-shadow:0 1px 8px rgba(0,0,0,.06);text-align:center;}
.stat-box .n{font-size:1.6rem;font-weight:900;}
.stat-box .l{font-size:.78rem;color:#6b7280;margin-top:2px;}
</style>

<div class="d-flex align-items-center gap-2 mb-4 flex-wrap">
    <a href="<?= url('customers') ?>" class="btn btn-sm btn-outline-secondary">
        <i class="bi bi-arrow-left"></i> Customers
    </a>
    <h4 class="mb-0 fw-bold ms-1">Customer Profile</h4>
    <div class="ms-auto d-flex gap-2">
        <a href="<?= url('customers/'.$customer['id'].'/edit') ?>" class="btn btn-sm btn-outline-primary">
            <i class="bi bi-pencil me-1"></i> Edit
        </a>
    </div>
</div>

<?= flash_alert() ?>

<!-- Blacklist banner -->
<?php if ($customer['blacklisted']): ?>
<div class="alert alert-danger d-flex align-items-center gap-3 mb-3">
    <i class="bi bi-slash-circle-fill fs-4"></i>
    <div class="flex-fill">
        <strong>This customer is blacklisted</strong>
        <?php if ($customer['blacklist_reason']): ?>
        <div class="small mt-1">Reason: <?= e($customer['blacklist_reason']) ?></div>
        <?php endif ?>
        <div class="small text-muted">
            Blacklisted <?= $customer['blacklisted_at'] ? date('d M Y, h:i A', strtotime($customer['blacklisted_at'])) : '' ?>
            <?= $customer['blacklisted_by_name'] ? ' by ' . e($customer['blacklisted_by_name']) : '' ?>
        </div>
    </div>
    <form method="POST" action="<?= url('customers/'.$customer['id'].'/unblacklist') ?>">
        <?= csrf_field() ?>
        <button class="btn btn-sm btn-outline-light fw-semibold"
                onclick="return confirm('Remove from blacklist?')">
            <i class="bi bi-check-circle me-1"></i> Unblacklist
        </button>
    </form>
</div>
<?php endif ?>

<div class="row g-3">

<!-- Profile card -->
<div class="col-lg-4">
    <div class="card border-0 shadow-sm h-100">
    <div class="card-body text-center p-4">
        <div class="d-flex justify-content-center mb-3">
            <div style="width:80px;height:80px;border-radius:50%;display:flex;align-items:center;
                        justify-content:center;font-size:1.6rem;font-weight:900;color:#fff;"
                 class="<?= $color ?>">
                <?= $initials ?>
            </div>
        </div>
        <h5 class="fw-bold mb-1"><?= e($customer['name']) ?></h5>
        <div class="mb-2">
            <span class="tier-badge <?= $tier['class'] ?>"><?= $tier['icon'] ?> <?= $tier['label'] ?></span>
        </div>

        <div class="text-muted small mb-1"><i class="bi bi-envelope me-1"></i><?= e($customer['email']) ?></div>
        <div class="text-muted small mb-1"><i class="bi bi-phone me-1"></i><?= e($customer['phone']) ?></div>
        <div class="text-muted small mb-3">
            <i class="bi bi-calendar me-1"></i>Joined <?= date('d M Y', strtotime($customer['created_at'])) ?>
        </div>

        <?php if ($customer['last_login']): ?>
        <div class="text-muted small mb-3">
            <i class="bi bi-clock-history me-1"></i>Last login <?= date('d M Y', strtotime($customer['last_login'])) ?>
        </div>
        <?php endif ?>

        <div class="mb-3">
            <?php if ($customer['blacklisted']): ?>
                <span class="badge bg-danger px-3 py-2">Blacklisted</span>
            <?php elseif ($customer['is_active']): ?>
                <span class="badge bg-success px-3 py-2">Active</span>
            <?php else: ?>
                <span class="badge bg-secondary px-3 py-2">Inactive</span>
            <?php endif ?>
        </div>

        <?php if ($customer['admin_note']): ?>
        <div class="alert alert-light text-start small py-2 px-3 mb-0">
            <i class="bi bi-sticky me-1 text-warning"></i><?= e($customer['admin_note']) ?>
        </div>
        <?php endif ?>
    </div>
    </div>
</div>

<!-- Stats + actions -->
<div class="col-lg-8">

    <!-- Stat boxes -->
    <div class="row g-2 mb-3">
        <div class="col-6 col-md-3">
            <div class="stat-box">
                <div class="n text-primary"><?= $customer['total_orders'] ?></div>
                <div class="l">Total Orders</div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="stat-box">
                <div class="n text-success"><?= $customer['delivered_orders'] ?></div>
                <div class="l">Delivered</div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="stat-box">
                <div class="n text-danger"><?= $customer['cancelled_orders'] ?></div>
                <div class="l">Cancelled</div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="stat-box">
                <div class="n" style="font-size:1.1rem;"><?= money((float)$customer['total_spent']) ?></div>
                <div class="l">Total Spent</div>
            </div>
        </div>
    </div>
    <div class="row g-2 mb-3">
        <div class="col-6 col-md-6">
            <div class="stat-box">
                <div class="n" style="font-size:1.1rem;"><?= money((float)$customer['avg_order']) ?></div>
                <div class="l">Avg Order Value</div>
            </div>
        </div>
        <div class="col-6 col-md-6">
            <div class="stat-box">
                <div class="n text-info"><?= $customer['delivered_orders'] > 0
                    ? round(($customer['delivered_orders'] / max(1, $customer['total_orders'])) * 100) . '%'
                    : '—' ?></div>
                <div class="l">Completion Rate</div>
            </div>
        </div>
    </div>

    <!-- Saved addresses -->
    <?php if (!empty($addresses)): ?>
    <div class="card border-0 shadow-sm mb-3">
    <div class="card-body p-3">
        <h6 class="fw-bold mb-2"><i class="bi bi-geo-alt me-1 text-danger"></i> Saved Addresses</h6>
        <?php foreach ($addresses as $addr): ?>
        <div class="d-flex align-items-start gap-2 py-2 border-bottom">
            <span class="badge bg-light text-dark border"><?= e($addr['label']) ?></span>
            <div class="flex-fill small">
                <?= e($addr['address_line']) ?>, <?= e($addr['city']) ?>
                <?php if ($addr['is_default']): ?>
                <span class="badge bg-primary ms-1" style="font-size:.6rem;">Default</span>
                <?php endif ?>
            </div>
            <?php if ($addr['latitude'] && $addr['longitude']): ?>
            <a href="https://www.google.com/maps?q=<?= $addr['latitude'] ?>,<?= $addr['longitude'] ?>"
               target="_blank" class="btn btn-sm btn-outline-primary py-0 px-2">
                <i class="bi bi-map"></i>
            </a>
            <?php endif ?>
        </div>
        <?php endforeach ?>
    </div>
    </div>
    <?php endif ?>

    <!-- Action buttons -->
    <div class="d-flex flex-wrap gap-2 mb-3">
        <!-- Toggle active -->
        <form method="POST" action="<?= url('customers/'.$customer['id'].'/toggle') ?>">
            <?= csrf_field() ?>
            <button class="btn btn-sm <?= $customer['is_active'] ? 'btn-outline-warning' : 'btn-outline-success' ?>">
                <i class="bi bi-<?= $customer['is_active'] ? 'pause-circle' : 'play-circle' ?> me-1"></i>
                <?= $customer['is_active'] ? 'Deactivate' : 'Activate' ?>
            </button>
        </form>

        <!-- Blacklist -->
        <?php if (!$customer['blacklisted']): ?>
        <button class="btn btn-sm btn-outline-danger" data-bs-toggle="modal" data-bs-target="#blacklistModal">
            <i class="bi bi-slash-circle me-1"></i> Blacklist
        </button>
        <?php else: ?>
        <form method="POST" action="<?= url('customers/'.$customer['id'].'/unblacklist') ?>">
            <?= csrf_field() ?>
            <button class="btn btn-sm btn-outline-success" onclick="return confirm('Remove from blacklist?')">
                <i class="bi bi-check-circle me-1"></i> Unblacklist
            </button>
        </form>
        <?php endif ?>

        <!-- Delete -->
        <?php if ($customer['total_orders'] == 0): ?>
        <form method="POST" action="<?= url('customers/'.$customer['id'].'/delete') ?>"
              onsubmit="return confirm('Permanently delete this customer?')">
            <?= csrf_field() ?>
            <button class="btn btn-sm btn-danger">
                <i class="bi bi-trash me-1"></i> Delete
            </button>
        </form>
        <?php else: ?>
        <button class="btn btn-sm btn-danger" disabled title="Cannot delete — has orders">
            <i class="bi bi-trash me-1"></i> Delete
        </button>
        <?php endif ?>
    </div>
</div>
</div>

<!-- Order history -->
<?php if (!empty($orders)): ?>
<div class="col-12">
<div class="card border-0 shadow-sm">
<div class="card-body p-3">
    <h6 class="fw-bold mb-3"><i class="bi bi-bag me-1 text-primary"></i> Order History
        <span class="text-muted fw-normal small">(last 20)</span>
    </h6>
    <div class="table-responsive">
    <table class="table table-sm align-middle mb-0">
    <thead class="table-light">
        <tr>
            <th>Order #</th>
            <th>Date</th>
            <th>Type</th>
            <th>Payment</th>
            <th class="text-center">Status</th>
            <th class="text-end">Amount</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
    <?php foreach ($orders as $o): ?>
    <tr>
        <td class="fw-semibold small"><?= e($o['order_number']) ?></td>
        <td class="small text-muted"><?= date('d M Y', strtotime($o['placed_at'])) ?></td>
        <td class="small text-capitalize"><?= e($o['order_type'] ?? 'delivery') ?></td>
        <td class="small text-capitalize"><?= e($o['payment_method']) ?></td>
        <td class="text-center">
            <span class="badge bg-<?= $statusColors[$o['status']] ?? 'secondary' ?>">
                <?= ucwords(str_replace('_', ' ', $o['status'])) ?>
            </span>
        </td>
        <td class="text-end fw-bold small"><?= money((float)$o['total_amount']) ?></td>
        <td>
            <a href="<?= url('orders/'.$o['id']) ?>" class="btn btn-sm btn-outline-secondary py-0 px-2">
                <i class="bi bi-eye"></i>
            </a>
        </td>
    </tr>
    <?php endforeach ?>
    </tbody>
    </table>
    </div>
</div>
</div>
</div>
<?php endif ?>

<!-- Blacklist Modal -->
<div class="modal fade" id="blacklistModal" tabindex="-1">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
    <div class="modal-header border-0 pb-0">
        <h5 class="modal-title text-danger fw-bold">
            <i class="bi bi-slash-circle me-2"></i>Blacklist Customer
        </h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
    </div>
    <form method="POST" action="<?= url('customers/'.$customer['id'].'/blacklist') ?>">
    <?= csrf_field() ?>
    <div class="modal-body">
        <p class="text-muted small">The customer's account will be deactivated. They will not be able to login or place orders.</p>
        <div class="mb-3">
            <label class="form-label fw-semibold">Reason <span class="text-danger">*</span></label>
            <textarea name="reason" class="form-control" rows="3"
                      placeholder="e.g. Repeated fake orders, abusive behaviour…" required></textarea>
        </div>
    </div>
    <div class="modal-footer border-0 pt-0">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="submit" class="btn btn-danger fw-semibold">
            <i class="bi bi-slash-circle me-1"></i> Confirm Blacklist
        </button>
    </div>
    </form>
</div>
</div>
</div>
