<?php
$vehicleIcons = ['BIKE' => 'fa-motorcycle', 'THREE_WHEELER' => 'fa-truck-pickup', 'BICYCLE' => 'fa-bicycle', 'VAN' => 'fa-van-shuttle'];
$vehicleLabels = ['BIKE' => 'Motorbike', 'THREE_WHEELER' => 'Three-Wheeler', 'BICYCLE' => 'Bicycle', 'VAN' => 'Van'];
?>
<div class="grid-cards">
    <div class="stat-card c-blue">
        <div class="stat-icon"><i class="fa-solid fa-users"></i></div>
        <div class="stat-label">Total Riders</div>
        <div class="stat-value"><?= (int) $summary['total_riders'] ?></div>
        <div class="stat-sub"><?= (int) $summary['active_riders'] ?> active</div>
    </div>
    <div class="stat-card c-purple">
        <div class="stat-icon"><i class="fa-solid fa-motorcycle"></i></div>
        <div class="stat-label">On Delivery Now</div>
        <div class="stat-value"><?= (int) $summary['on_delivery_now'] ?></div>
        <div class="stat-sub">Assigned + Picked up</div>
    </div>
    <div class="stat-card c-green">
        <div class="stat-icon"><i class="fa-solid fa-flag-checkered"></i></div>
        <div class="stat-label">Delivered Today</div>
        <div class="stat-value"><?= (int) $summary['delivered_today'] ?></div>
        <div class="stat-sub">Across all riders</div>
    </div>
</div>

<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;flex-wrap:wrap;gap:10px;">
    <form method="GET" action="<?= Router::url('riders') ?>" style="display:flex;gap:8px;">
        <input type="text" name="search" class="form-control" style="width:260px;" placeholder="Search by name, phone, vehicle no..." value="<?= e($search) ?>">
        <button type="submit" class="btn btn-secondary"><i class="fa-solid fa-magnifying-glass"></i></button>
        <?php if ($search !== ''): ?>
        <a href="<?= Router::url('riders') ?>" class="btn btn-secondary"><i class="fa-solid fa-xmark"></i></a>
        <?php endif; ?>
    </form>
    <?php if (Auth::can('delivery', 'edit')): ?>
    <button type="button" class="btn btn-primary" onclick="rmsOpenModal('rmsAddRiderModal')"><i class="fa-solid fa-user-plus"></i> Add Delivery Rider</button>
    <?php endif; ?>
</div>

<div>
    <?php foreach ($riders as $r):
        $initials = strtoupper(substr($r['full_name'], 0, 1));
        $vIcon = $vehicleIcons[$r['vehicle_type']] ?? 'fa-motorcycle';
    ?>
    <div class="rider-card">
        <?php if (!empty($r['photo_path'])): ?>
        <img src="<?= BASE_URL ?>/<?= e($r['photo_path']) ?>" alt="" class="rider-avatar-img">
        <?php else: ?>
        <div class="rider-avatar"><?= e($initials) ?></div>
        <?php endif; ?>
        <div class="rider-main">
            <div class="rider-top">
                <strong><?= e($r['full_name']) ?></strong>
                <?= $r['is_active'] ? '<span class="badge badge-green"><i class="fa-solid fa-circle-check"></i> Active</span>' : '<span class="badge badge-red"><i class="fa-solid fa-circle-xmark"></i> Inactive</span>' ?>
                <?php if ($r['active_count'] > 0): ?>
                <span class="badge badge-blue"><i class="fa-solid fa-motorcycle"></i> <?= (int) $r['active_count'] ?> on the way</span>
                <?php endif; ?>
            </div>
            <div class="rider-meta">
                <?php if ($r['phone']): ?><span><i class="fa-solid fa-phone"></i> <?= e($r['phone']) ?></span><?php endif; ?>
                <?php if ($r['vehicle_type']): ?><span><i class="fa-solid <?= $vIcon ?>"></i> <?= e($vehicleLabels[$r['vehicle_type']] ?? $r['vehicle_type']) ?><?= $r['vehicle_number'] ? ' · ' . e($r['vehicle_number']) : '' ?></span><?php endif; ?>
            </div>
            <div class="rider-stats">
                <span><strong><?= (int) $r['delivered_today'] ?></strong> today</span>
                <span><strong><?= (int) $r['delivered_count'] ?></strong> all-time</span>
                <?php if ($r['failed_count'] > 0): ?><span style="color:var(--color-danger);"><strong><?= (int) $r['failed_count'] ?></strong> failed</span><?php endif; ?>
            </div>
        </div>
        <?php if (Auth::can('delivery', 'edit')): ?>
        <div class="rider-actions">
            <button type="button" class="btn btn-secondary" style="padding:6px 12px;font-size:12px;" onclick="rmsOpenModal('rmsHistoryModal<?= $r['id'] ?>')" title="Delivery History"><i class="fa-solid fa-clock-rotate-left"></i></button>
            <button type="button" class="btn btn-secondary" style="padding:6px 12px;font-size:12px;" onclick="rmsOpenModal('rmsEditRiderModal<?= $r['id'] ?>')"><i class="fa-solid fa-pen"></i></button>
            <form method="POST" action="<?= Router::url('riders/toggle') ?>">
                <?= $csrf ?>
                <input type="hidden" name="id" value="<?= $r['id'] ?>">
                <button type="submit" class="btn btn-secondary" style="padding:6px 12px;font-size:12px;">
                    <?= $r['is_active'] ? '<i class="fa-solid fa-ban"></i>' : '<i class="fa-solid fa-check"></i>' ?>
                </button>
            </form>
        </div>
        <?php endif; ?>
    </div>

    <?php if (Auth::can('delivery', 'view')):
        $statusMeta = [
            'ASSIGNED'  => ['label' => 'Assigned',  'badge' => 'badge-blue'],
            'PICKED_UP' => ['label' => 'Picked Up', 'badge' => 'badge-gold'],
            'DELIVERED' => ['label' => 'Delivered', 'badge' => 'badge-green'],
            'FAILED'    => ['label' => 'Failed',    'badge' => 'badge-red'],
        ];
        $history = $historyByRider[$r['id']] ?? [];
    ?>
    <div class="rms-modal-overlay" id="rmsHistoryModal<?= $r['id'] ?>">
        <div class="rms-modal" style="max-width:560px;">
            <div class="rms-modal-head">
                <h3><i class="fa-solid fa-clock-rotate-left" style="color:var(--color-teal);margin-right:6px;"></i><?= e($r['full_name']) ?> — Delivery History</h3>
                <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsHistoryModal<?= $r['id'] ?>')"><i class="fa-solid fa-xmark"></i></button>
            </div>
            <div style="max-height:60vh;overflow-y:auto;">
                <?php foreach ($history as $h): $sm = $statusMeta[$h['status']] ?? ['label' => $h['status'], 'badge' => 'badge-gray']; ?>
                <div class="history-row">
                    <div class="hr-top">
                        <strong><?= e($h['order_number']) ?></strong>
                        <span class="badge <?= $sm['badge'] ?>"><?= e($sm['label']) ?></span>
                        <span class="hr-amount"><?= formatMoney((float) $h['total_amount']) ?></span>
                    </div>
                    <div class="hr-meta">
                        <?php if ($h['customer_name']): ?><span><i class="fa-solid fa-user"></i> <?= e($h['customer_name']) ?></span><?php endif; ?>
                        <?php if ($h['zone_name']): ?><span><i class="fa-solid fa-location-dot"></i> <?= e($h['zone_name']) ?></span><?php endif; ?>
                        <span><i class="fa-regular fa-clock"></i>
                            <?php if ($h['delivered_at']): ?>Delivered <?= date('d M, h:i A', strtotime($h['delivered_at'])) ?>
                            <?php elseif ($h['picked_up_at']): ?>Picked up <?= date('d M, h:i A', strtotime($h['picked_up_at'])) ?>
                            <?php elseif ($h['assigned_at']): ?>Assigned <?= date('d M, h:i A', strtotime($h['assigned_at'])) ?>
                            <?php endif; ?>
                        </span>
                    </div>
                    <?php if ($h['status'] === 'FAILED' && !empty($h['notes'])): ?>
                    <div class="hr-meta" style="color:var(--color-danger);"><i class="fa-solid fa-note-sticky"></i> <?= e($h['notes']) ?></div>
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
                <?php if (empty($history)): ?>
                <div style="text-align:center;color:var(--color-text-muted);padding:30px 0;font-size:13px;">No deliveries yet for this rider.</div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <?php if (Auth::can('delivery', 'edit')): ?>
    <div class="rms-modal-overlay" id="rmsEditRiderModal<?= $r['id'] ?>">
        <div class="rms-modal">
            <div class="rms-modal-head">
                <h3><i class="fa-solid fa-pen" style="color:var(--color-teal);margin-right:6px;"></i>Edit Rider</h3>
                <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsEditRiderModal<?= $r['id'] ?>')"><i class="fa-solid fa-xmark"></i></button>
            </div>
            <form method="POST" action="<?= Router::url('riders/update') ?>" enctype="multipart/form-data">
                <?= $csrf ?>
                <input type="hidden" name="id" value="<?= $r['id'] ?>">
                <div class="form-group">
                    <label>Photo</label>
                    <?php if (!empty($r['photo_path'])): ?>
                    <div class="rider-photo-preview">
                        <img src="<?= BASE_URL ?>/<?= e($r['photo_path']) ?>" alt="">
                        <label class="remove-image-check">
                            <input type="checkbox" name="remove_photo" value="1"> Remove current photo
                        </label>
                    </div>
                    <?php endif; ?>
                    <input type="file" name="photo" class="form-control" accept="image/jpeg,image/png,image/webp">
                </div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                    <div class="form-group">
                        <label>Full Name</label>
                        <input type="text" name="full_name" class="form-control" value="<?= e($r['full_name']) ?>">
                    </div>
                    <div class="form-group">
                        <label>Phone</label>
                        <input type="text" name="phone" class="form-control" value="<?= e($r['phone'] ?? '') ?>">
                    </div>
                    <div class="form-group">
                        <label>Vehicle Type</label>
                        <select name="vehicle_type" class="form-control">
                            <option value="">— None —</option>
                            <?php foreach ($vehicleLabels as $key => $label): ?>
                            <option value="<?= $key ?>" <?= $r['vehicle_type'] === $key ? 'selected' : '' ?>><?= e($label) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Vehicle No.</label>
                        <input type="text" name="vehicle_number" class="form-control" value="<?= e($r['vehicle_number'] ?? '') ?>">
                    </div>
                    <div class="form-group" style="grid-column:span 2;">
                        <label>Username (login for Rider App)</label>
                        <input type="text" name="username" class="form-control" value="<?= e($r['username']) ?>">
                    </div>
                    <div class="form-group" style="grid-column:span 2;">
                        <label>New Password (leave blank to keep unchanged)</label>
                        <input type="password" name="password" class="form-control">
                    </div>
                </div>
                <button type="submit" class="btn btn-primary"><i class="fa-solid fa-floppy-disk"></i> Save</button>
                <button type="button" class="btn btn-secondary" onclick="rmsCloseModal('rmsEditRiderModal<?= $r['id'] ?>')">Cancel</button>
            </form>
        </div>
    </div>
    <?php endif; ?>
    <?php endforeach; ?>

    <?php if (empty($riders)): ?>
    <div class="panel" style="text-align:center;color:var(--color-text-muted);padding:40px;">
        <i class="fa-solid fa-motorcycle" style="font-size:24px;margin-bottom:8px;display:block;opacity:0.5;"></i>
        No delivery riders found.
    </div>
    <?php endif; ?>
</div>

<?php if (Auth::can('delivery', 'edit')): ?>
<div class="rms-modal-overlay" id="rmsAddRiderModal">
    <div class="rms-modal">
        <div class="rms-modal-head">
            <h3><i class="fa-solid fa-user-plus" style="color:var(--color-teal);margin-right:6px;"></i>Add Delivery Rider</h3>
            <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsAddRiderModal')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST" action="<?= Router::url('riders/store') ?>" enctype="multipart/form-data">
            <?= $csrf ?>
            <div class="form-group">
                <label>Photo (optional)</label>
                <input type="file" name="photo" class="form-control" accept="image/jpeg,image/png,image/webp">
                <div style="font-size:11px;color:var(--color-text-muted);margin-top:4px;">JPG, PNG or WEBP — max 3MB.</div>
            </div>
            <div class="form-group">
                <label>Full Name</label>
                <input type="text" name="full_name" class="form-control" required>
            </div>
            <div class="form-group">
                <label>Phone</label>
                <input type="text" name="phone" class="form-control" placeholder="07XXXXXXXX">
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                <div class="form-group">
                    <label>Vehicle Type</label>
                    <select name="vehicle_type" class="form-control">
                        <option value="">— None —</option>
                        <?php foreach ($vehicleLabels as $key => $label): ?>
                        <option value="<?= $key ?>"><?= e($label) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Vehicle No.</label>
                    <input type="text" name="vehicle_number" class="form-control" placeholder="e.g. NP-1234">
                </div>
            </div>
            <div class="form-group">
                <label>Username</label>
                <input type="text" name="username" class="form-control" required>
            </div>
            <div class="form-group">
                <label>Password</label>
                <input type="password" name="password" class="form-control" required>
            </div>
            <button type="submit" class="btn btn-primary" style="width:100%;"><i class="fa-solid fa-plus"></i> Add Rider</button>
        </form>
    </div>
</div>
<?php endif; ?>

<style>
.rider-card {
    background: var(--color-surface); border: 1px solid var(--color-border); border-radius: var(--radius);
    padding: 14px 16px; display: flex; align-items: flex-start; gap: 14px; margin-bottom: 10px; box-shadow: var(--shadow-sm);
}
.rider-avatar {
    width: 42px; height: 42px; border-radius: 50%; background: var(--color-navy); color: #fff;
    display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 15px; flex-shrink: 0;
}
.rider-avatar-img { width: 42px; height: 42px; border-radius: 50%; object-fit: cover; flex-shrink: 0; }
.rider-photo-preview {
    display: flex; align-items: center; gap: 12px; margin-bottom: 10px;
    padding: 10px; border: 1px solid var(--color-border); border-radius: 8px; background: var(--color-bg);
}
.rider-photo-preview img { width: 56px; height: 56px; object-fit: cover; border-radius: 50%; flex-shrink: 0; }
.rider-photo-preview .remove-image-check { font-size: 12px; color: var(--color-danger); display: flex; align-items: center; gap: 6px; }
.rider-main { flex: 1; min-width: 0; }
.rider-top { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-bottom: 6px; }
.rider-top strong { font-size: 14px; }
.rider-meta { display: flex; gap: 16px; font-size: 12px; color: var(--color-text-muted); margin-bottom: 6px; flex-wrap: wrap; }
.rider-stats { display: flex; gap: 16px; font-size: 12px; color: var(--color-text-muted); }
.rider-stats strong { color: var(--color-text); }
.rider-actions { display: flex; gap: 6px; flex-shrink: 0; }

/* ---------- Modal popup ---------- */
.rms-modal-overlay {
    display: none; position: fixed; inset: 0; background: rgba(20,25,40,0.55);
    z-index: 1000; align-items: center; justify-content: center; padding: 20px;
}
.rms-modal-overlay.open { display: flex; }
.rms-modal {
    background: var(--color-surface); border-radius: var(--radius); padding: 24px;
    width: 100%; max-width: 480px; max-height: 90vh; overflow-y: auto;
    box-shadow: var(--shadow-md); animation: rmsModalIn 0.15s ease;
}
@keyframes rmsModalIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
}
.rms-modal-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; }
.rms-modal-head h3 { font-size: 16px; }
.rms-modal-close {
    background: var(--color-bg); border: 1px solid var(--color-border); border-radius: 8px;
    width: 30px; height: 30px; cursor: pointer; color: var(--color-text-muted);
}
.rms-modal-close:hover { color: var(--color-danger); }

.history-row { padding: 10px 0; border-bottom: 1px solid var(--color-border); font-size: 12.5px; }
.hr-top { display: flex; align-items: center; gap: 8px; margin-bottom: 4px; flex-wrap: wrap; }
.hr-top strong { font-size: 13px; }
.hr-amount { margin-left: auto; color: var(--color-accent); font-weight: 700; }
.hr-meta { display: flex; gap: 14px; color: var(--color-text-muted); flex-wrap: wrap; margin-top: 2px; }
</style>

<script>
function rmsOpenModal(id) {
    document.getElementById(id).classList.add('open');
}
function rmsCloseModal(id) {
    document.getElementById(id).classList.remove('open');
}
// Close modal when clicking the dark overlay (outside the card)
document.addEventListener('click', function (e) {
    if (e.target.classList.contains('rms-modal-overlay')) {
        e.target.classList.remove('open');
    }
});
// Close modal with Escape key
document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape') {
        document.querySelectorAll('.rms-modal-overlay.open').forEach(m => m.classList.remove('open'));
    }
});
</script>
