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

<?php $__template->section('title'); ?>خزنة العضويات<?php $__template->endSection(); ?>

<?php $__template->section('content'); ?>
<!-- Session Status Bar -->
<?php if (isset($treasury) && $treasury): ?>
<div class="card" style="margin-bottom:15px;border:2px solid <?= isset($currentSession) && $currentSession ? '#059669' : '#D97706' ?>;">
    <div style="padding:12px 20px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;">
        <?php if (isset($currentSession) && $currentSession): ?>
            <div style="display:flex;align-items:center;gap:15px;">
                <span style="background:#ECFDF5;color:#059669;padding:4px 12px;border-radius:8px;font-size:12px;font-weight:700;">وردية مفتوحة</span>
                <span style="font-size:13px;color:#374151;">رقم: <strong><?= e($currentSession['session_number']) ?></strong></span>
                <span style="font-size:13px;color:#374151;">تحصيلات: <strong><?= money((float)($currentSession['total_collected'] ?? 0)) ?></strong></span>
                <span style="font-size:13px;color:#374151;">إيصالات: <strong><?= (int)($currentSession['total_receipts'] ?? 0) ?></strong></span>
                <span style="font-size:13px;color:#374151;">العهدة: <strong><?= money((float)($custodyBalance ?? 0)) ?></strong></span>
            </div>
            <form method="POST" action="/cashier/session/close" style="margin:0;" onsubmit="return confirm('هل تريد إغلاق الوردية الحالية؟');">
                <?= csrf_field() ?>
                <button type="submit" class="btn btn-sm" style="background:#D97706;color:#fff;font-size:12px;">
                    <i data-lucide="lock" style="width:13px;height:13px;vertical-align:middle;"></i> إغلاق الوردية
                </button>
            </form>
        <?php else: ?>
            <div style="display:flex;align-items:center;gap:10px;">
                <span style="background:#FEF3C7;color:#D97706;padding:4px 12px;border-radius:8px;font-size:12px;font-weight:700;">لا توجد وردية مفتوحة</span>
                <span style="font-size:13px;color:#6B7280;">يجب فتح وردية قبل التحصيل</span>
            </div>
            <form method="POST" action="/cashier/session/open" style="margin:0;">
                <?= csrf_field() ?>
                <button type="submit" class="btn btn-sm" style="background:#059669;color:#fff;font-size:12px;">
                    <i data-lucide="unlock" style="width:13px;height:13px;vertical-align:middle;"></i> فتح وردية
                </button>
            </form>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<!-- 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="foreign_membership_fee" <?= ($filters['payment_type'] ?? '') === 'foreign_membership_fee' ? 'selected' : '' ?>>رسوم عضوية أجنبية</option>
                    <option value="sports_membership_fee" <?= ($filters['payment_type'] ?? '') === 'sports_membership_fee' ? 'selected' : '' ?>>رسوم عضوية رياضية</option>
                    <option value="seasonal_fee" <?= ($filters['payment_type'] ?? '') === 'seasonal_fee' ? '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>
                            <?php
                            $displayName = $r['member_name'] ?? '—';
                            if ($r['payment_type'] === 'death_fee' && !empty($r['notes'])) {
                                $nd2 = json_decode($r['notes'], true);
                                if (!empty($nd2['recipient_name'])) $displayName = $nd2['recipient_name'];
                            }
                            if ($r['payment_type'] === 'separation_fee' && !empty($r['notes'])) {
                                $nd2 = json_decode($r['notes'], true);
                                if (!empty($nd2['child_name'])) $displayName = $nd2['child_name'];
                            }
                            ?>
                            <?php if ((int)($r['member_id'] ?? 0) > 0): ?>
                            <a href="/members/<?= (int)$r['member_id'] ?>" style="color:#0D7377;font-weight:600;"><?= e($displayName) ?></a>
                            <?php else: ?>
                            <span style="font-weight:600;"><?= e($r['description_ar'] ?? '—') ?></span>
                            <?php endif; ?>
                        </td>
                        <td style="font-weight:600;color:#D97706;"><?php
                            $fnDisplay = $r['form_number'] ?? null;
                            if (!$fnDisplay && $r['payment_type'] === 'death_fee' && !empty($r['notes'])) {
                                $nd3 = json_decode($r['notes'], true);
                                $fnDisplay = $nd3['form_number'] ?? null;
                            }
                            if (!$fnDisplay && $r['payment_type'] === 'death_fee' && !empty($r['related_entity_id']) && ($r['related_entity_type'] ?? '') === 'death_cases') {
                                $dcRow = \App\Core\App::getInstance()->db()->selectOne("SELECT form_number FROM death_cases WHERE id = ?", [(int) $r['related_entity_id']]);
                                $fnDisplay = $dcRow['form_number'] ?? null;
                            }
                            if (!$fnDisplay && $r['payment_type'] === 'separation_fee' && !empty($r['related_entity_id']) && ($r['related_entity_type'] ?? '') === 'transfer_requests') {
                                $trRow = \App\Core\App::getInstance()->db()->selectOne(
                                    "SELECT m.form_number FROM transfer_requests tr JOIN members m ON m.id = tr.target_member_id WHERE tr.id = ?",
                                    [(int) $r['related_entity_id']]
                                );
                                $fnDisplay = $trRow['form_number'] ?? null;
                            }
                            echo e($fnDisplay ?: '—');
                        ?></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'): ?>
                                <?php if (can('cashier.process_payment')): ?>
                                <a href="/cashier/<?= (int)$r['id'] ?>" class="btn btn-sm btn-primary">تحصيل</a>
                                <?php endif; ?>
                            <?php elseif ($r['status'] === 'completed'): ?>
                                <span style="color:#059669;font-size:12px;">&#x2705; تم</span>
                                <?php if (!empty($r['receipt_id']) && can('receipt.print')): ?>
                                    <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 if (can('cashier.cancel_request')): ?>
                                <form method="POST" action="/cashier/<?= (int)$r['id'] ?>/cancel" style="display:inline;margin-top:4px;">
                                    <?= csrf_field() ?>
                                    <input type="hidden" name="reason" value="">
                                    <button type="submit" class="btn btn-sm" style="font-size:11px;color:#DC2626;border:1px solid #DC2626;background:transparent;"
                                        onclick="var r=prompt('سبب إلغاء الدفعة:');if(!r)return false;this.form.reason.value=r;return confirm('سيتم إلغاء الدفعة وإرجاع حالة العضوية. متأكد؟');">إلغاء الدفعة</button>
                                </form>
                                <?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(); ?>
