<?php $__template->layout('Layout.main'); ?>

<?php $__template->section('title'); ?>طابور الخزينة<?php $__template->endSection(); ?>

<?php $__template->section('content'); ?>
<!-- Filters -->
<div class="card" style="margin-bottom:15px;">
    <div style="padding:15px 20px;">
        <form method="GET" action="/cashier" style="display:flex;gap:10px;flex-wrap:wrap;align-items:end;">
            <div>
                <label class="form-label" style="font-size:12px;">بحث</label>
                <input type="text" name="search" class="form-input" value="<?= e($filters['search'] ?? '') ?>" placeholder="اسم العضو، رقم الاستمارة، رقم الطلب...">
            </div>
            <div>
                <label class="form-label" style="font-size:12px;">الحالة</label>
                <select name="status" class="form-select">
                    <option value="">معلق + قيد التنفيذ</option>
                    <option value="pending" <?= ($filters['status'] ?? '') === 'pending' ? 'selected' : '' ?>>معلق</option>
                    <option value="processing" <?= ($filters['status'] ?? '') === 'processing' ? 'selected' : '' ?>>قيد التنفيذ</option>
                    <option value="completed" <?= ($filters['status'] ?? '') === 'completed' ? 'selected' : '' ?>>مكتمل</option>
                    <option value="cancelled" <?= ($filters['status'] ?? '') === 'cancelled' ? 'selected' : '' ?>>ملغى</option>
                </select>
            </div>
            <div>
                <label class="form-label" style="font-size:12px;">نوع الدفعة</label>
                <select name="payment_type" class="form-select">
                    <option value="">الكل</option>
                    <option value="form_fee" <?= ($filters['payment_type'] ?? '') === 'form_fee' ? 'selected' : '' ?>>رسوم استمارة</option>
                    <option value="membership_fee" <?= ($filters['payment_type'] ?? '') === 'membership_fee' ? 'selected' : '' ?>>رسوم عضوية</option>
                    <option value="down_payment" <?= ($filters['payment_type'] ?? '') === 'down_payment' ? 'selected' : '' ?>>مقدم أقساط</option>
                    <option value="divorce_fee" <?= ($filters['payment_type'] ?? '') === 'divorce_fee' ? 'selected' : '' ?>>رسوم طلاق</option>
                    <option value="death_fee" <?= ($filters['payment_type'] ?? '') === 'death_fee' ? 'selected' : '' ?>>رسوم وفاة</option>
                    <option value="waiver_fee" <?= ($filters['payment_type'] ?? '') === 'waiver_fee' ? 'selected' : '' ?>>رسوم تنازل</option>
                    <option value="separation_fee" <?= ($filters['payment_type'] ?? '') === 'separation_fee' ? 'selected' : '' ?>>رسوم فصل</option>
                    <option value="addition_fee" <?= ($filters['payment_type'] ?? '') === 'addition_fee' ? 'selected' : '' ?>>رسوم إضافة</option>
                    <option value="annual_subscription" <?= ($filters['payment_type'] ?? '') === 'annual_subscription' ? 'selected' : '' ?>>اشتراك سنوي</option>
                    <option value="fine" <?= ($filters['payment_type'] ?? '') === 'fine' ? 'selected' : '' ?>>غرامة</option>
                </select>
            </div>
            <button type="submit" class="btn btn-outline">بحث</button>
            <?php if (!empty($filters['search']) || !empty($filters['status']) || !empty($filters['payment_type'])): ?>
                <a href="/cashier" class="btn btn-outline" style="color:#DC2626;border-color:#DC2626;">مسح</a>
            <?php endif; ?>
        </form>
    </div>
</div>

<!-- Queue -->
<div class="card">
    <?php
    $pendingCount = 0;
    foreach ($requests as $r) {
        if ($r['status'] === 'pending') $pendingCount++;
    }
    ?>
    <?php if ($pendingCount > 0): ?>
        <div style="padding:12px 20px;background:#FEF2F2;border-bottom:1px solid #FECACA;font-size:14px;color:#DC2626;font-weight:600;">
            <?= $pendingCount ?> طلب في الانتظار
        </div>
    <?php endif; ?>

    <div class="table-responsive">
        <table class="data-table" style="width:100%;">
            <thead>
                <tr>
                    <th>رقم الطلب</th>
                    <th>العضو</th>
                    <th>رقم الاستمارة</th>
                    <th>نوع الدفعة</th>
                    <th>المبلغ</th>
                    <th>الحالة</th>
                    <th>وقت الانتظار</th>
                    <th>بواسطة</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($requests as $r):
                    $statusColor = match($r['status']) {
                        'pending'    => '#F59E0B',
                        'processing' => '#3B82F6',
                        'completed'  => '#059669',
                        'cancelled'  => '#DC2626',
                        default      => '#6B7280',
                    };
                    $statusLabel = match($r['status']) {
                        'pending'    => 'معلق',
                        'processing' => 'قيد التنفيذ',
                        'completed'  => 'مكتمل',
                        'cancelled'  => 'ملغى',
                        default      => $r['status'],
                    };
                    $typeLabel = \App\Modules\Cashier\Services\PaymentRequestService::getPaymentTypeLabel($r['payment_type']);
                    $waitMinutes = (int) ((time() - strtotime($r['created_at'])) / 60);
                    if ($waitMinutes < 60) {
                        $waitText = $waitMinutes . ' د';
                    } elseif ($waitMinutes < 1440) {
                        $waitText = intdiv($waitMinutes, 60) . ' س ' . ($waitMinutes % 60) . ' د';
                    } else {
                        $waitText = intdiv($waitMinutes, 1440) . ' يوم';
                    }
                    $urgent = ($r['status'] === 'pending' && $waitMinutes > 30);
                ?>
                    <tr<?= $r['status'] === 'cancelled' ? ' style="opacity:0.5;"' : '' ?><?= $urgent ? ' style="background:#FEF2F2;"' : '' ?>>
                        <td style="direction:ltr;text-align:right;font-weight:600;font-size:12px;"><?= e($r['request_number']) ?></td>
                        <td>
                            <a href="/members/<?= (int)$r['member_id'] ?>" style="color:#0D7377;font-weight:600;"><?= e($r['member_name'] ?? '—') ?></a>
                        </td>
                        <td style="font-weight:600;color:#D97706;"><?= e($r['form_number'] ?? '—') ?></td>
                        <td><?= $typeLabel ?></td>
                        <td style="direction:ltr;text-align:right;font-weight:700;font-size:15px;">
                            <?= money($r['amount']) ?>
                            <?php
                            $nd = $r['notes'] ? json_decode($r['notes'], true) : null;
                            $fb = $nd['fee_breakdown'] ?? null;
                            if (is_array($fb) && !empty($fb)):
                                $detailLines = [];
                                $totalLine = '';
                                foreach ($fb as $ln) {
                                    if (str_contains($ln, '═══')) continue;
                                    if (str_starts_with($ln, '💵')) { $totalLine = $ln; continue; }
                                    $detailLines[] = $ln;
                                }
                            ?>
                            <div style="font-size:11px;font-weight:400;color:#374151;margin-top:4px;max-width:280px;line-height:1.5;text-align:right;direction:rtl;background:#F9FAFB;border:1px solid #E5E7EB;border-radius:6px;padding:6px 8px;">
                                <?php foreach ($detailLines as $dl): ?>
                                    <div style="padding:1px 0;"><?= e($dl) ?></div>
                                <?php endforeach; ?>
                                <?php if ($totalLine): ?>
                                    <div style="border-top:1px solid #D1D5DB;margin-top:4px;padding-top:4px;font-weight:700;color:#059669;"><?= e($totalLine) ?></div>
                                <?php endif; ?>
                            </div>
                            <?php endif; ?>
                        </td>
                        <td><span style="color:<?= $statusColor ?>;font-weight:600;font-size:13px;"><?= $statusLabel ?></span></td>
                        <td style="font-size:12px;<?= $urgent ? 'color:#DC2626;font-weight:700;' : 'color:#6B7280;' ?>"><?= $waitText ?></td>
                        <td style="font-size:12px;color:#6B7280;"><?= e($r['requested_by_name'] ?? '—') ?></td>
                        <td>
                            <?php if ($r['status'] === 'pending' || $r['status'] === 'processing'): ?>
                                <a href="/cashier/<?= (int)$r['id'] ?>" class="btn btn-sm btn-primary">تحصيل</a>
                            <?php elseif ($r['status'] === 'completed'): ?>
                                <span style="color:#059669;font-size:12px;">&#x2705; تم</span>
                                <?php if (!empty($r['receipt_id'])): ?>
                                    <a href="/receipts/<?= (int)$r['receipt_id'] ?>/print" target="_blank" class="btn btn-sm btn-outline" style="font-size:11px;margin-top:4px;">&#x1f5a8; طباعة</a>
                                <?php endif; ?>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($requests)): ?>
                    <tr><td colspan="9" style="text-align:center;color:#6B7280;padding:40px;">
                        <div style="font-size:48px;margin-bottom:10px;">&#x1f4ad;</div>
                        لا توجد طلبات دفع
                    </td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
setTimeout(function(){ location.reload(); }, 30000);
(function(){
    var params = new URLSearchParams(window.location.search);
    var printId = params.get('print_receipt');
    if (printId) {
        window.open('/receipts/' + printId + '/print', '_blank');
        params.delete('print_receipt');
        var newUrl = window.location.pathname + (params.toString() ? '?' + params.toString() : '');
        window.history.replaceState({}, '', newUrl);
    }
})();
</script>
<?php $__template->endSection(); ?>
