<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>معالج إدخال عضوية بأثر رجعي<?php $__template->endSection(); ?>

<?php $__template->section('content'); ?>

<div id="retroWizard">
    <!-- Progress Bar -->
    <div class="card" style="margin-bottom:16px;padding:16px;">
        <div style="display:flex;justify-content:space-between;align-items:center;position:relative;">
            <div style="position:absolute;top:50%;left:40px;right:40px;height:3px;background:#E5E7EB;z-index:0;transform:translateY(-50%);"></div>
            <div id="progressFill" style="position:absolute;top:50%;left:40px;height:3px;background:#2563EB;z-index:0;transform:translateY(-50%);width:0%;transition:width 0.3s;"></div>
            <?php
            $steps = ['البيانات الأساسية', 'التواريخ', 'المالية', 'الأقساط', 'الملحقون', 'الاشتراكات', 'المخالفات'];
            foreach ($steps as $i => $label):
                $stepNum = $i + 1;
            ?>
            <div class="wizard-step-indicator" data-step="<?= $stepNum ?>" style="text-align:center;position:relative;z-index:1;cursor:pointer;">
                <div id="stepCircle<?= $stepNum ?>" style="width:40px;height:40px;border-radius:50%;background:#E5E7EB;color:#9CA3AF;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:14px;margin:0 auto;transition:all 0.3s;">
                    <?= $stepNum ?>
                </div>
                <div id="stepLabel<?= $stepNum ?>" style="font-size:10px;margin-top:6px;color:#6B7280;font-weight:400;white-space:nowrap;"><?= $label ?></div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- Warning Banner -->
    <div class="card" style="margin-bottom:16px;padding:14px 20px;background:#FEF3C7;border:1px solid #F59E0B;">
        <div style="display:flex;align-items:center;gap:10px;">
            <i data-lucide="alert-triangle" style="width:22px;height:22px;color:#D97706;flex-shrink:0;"></i>
            <div>
                <div style="font-weight:700;color:#92400E;font-size:14px;">أداة إدخال بأثر رجعي — للمدير فقط</div>
                <div style="font-size:12px;color:#92400E;margin-top:2px;">هذه الأداة تتجاوز جميع مسارات العمل المعتادة. تُستخدم لإدخال بيانات أعضاء قدامى بكل تفاصيلهم المالية والزمنية لاختبار جميع السيناريوهات.</div>
            </div>
        </div>
    </div>

    <form id="retroForm" action="/members/retroactive-wizard" method="POST">
        <?= csrf_field() ?>

        <!-- ═══════════════ STEP 1: Basic Info ═══════════════ -->
        <div class="wizard-panel" id="panel-1">
            <div class="card" style="margin-bottom:16px;">
                <div style="padding:16px 20px;border-bottom:1px solid #E5E7EB;">
                    <h3 style="margin:0;font-size:16px;font-weight:700;"><i data-lucide="user-plus" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> البيانات الأساسية للعضو</h3>
                </div>
                <div style="padding:20px;">
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:#374151;">الاسم بالعربية <span style="color:#EF4444;">*</span></label>
                            <input type="text" name="full_name_ar" required class="form-input" style="width:100%;padding:10px 14px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;" placeholder="الاسم رباعي بالعربية">
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:#374151;">الاسم بالإنجليزية</label>
                            <input type="text" name="full_name_en" class="form-input" style="width:100%;padding:10px 14px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;direction:ltr;" placeholder="Full Name in English">
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:#374151;">رقم العضوية</label>
                            <input type="text" name="membership_number" class="form-input" style="width:100%;padding:10px 14px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;direction:ltr;" placeholder="رقم العضوية القديم (اختياري — يُولّد تلقائياً إن ترك فارغاً)">
                            <div style="font-size:11px;color:#6B7280;margin-top:4px;">أدخل رقم العضوية الأصلي للعضو القديم إن وُجد</div>
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:#374151;">الرقم القومي</label>
                            <input type="text" name="national_id" class="form-input" style="width:100%;padding:10px 14px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;direction:ltr;" maxlength="14" placeholder="14 رقم">
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:#374151;">رقم جواز السفر</label>
                            <input type="text" name="passport_number" class="form-input" style="width:100%;padding:10px 14px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;direction:ltr;" placeholder="للأجانب">
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:#374151;">تاريخ الميلاد</label>
                            <input type="date" name="date_of_birth" class="form-input" style="width:100%;padding:10px 14px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;">
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:#374151;">النوع</label>
                            <select name="gender" class="form-input" style="width:100%;padding:10px 14px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;">
                                <option value="male">ذكر</option>
                                <option value="female">أنثى</option>
                            </select>
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:#374151;">الهاتف المحمول</label>
                            <input type="text" name="phone_mobile" class="form-input" style="width:100%;padding:10px 14px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;direction:ltr;" placeholder="01XXXXXXXXX">
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:#374151;">الهاتف المنزلي</label>
                            <input type="text" name="phone_home" class="form-input" style="width:100%;padding:10px 14px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;direction:ltr;">
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:#374151;">البريد الإلكتروني</label>
                            <input type="email" name="email" class="form-input" style="width:100%;padding:10px 14px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;direction:ltr;">
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:#374151;">الفرع <span style="color:#EF4444;">*</span></label>
                            <select name="branch_id" required class="form-input" style="width:100%;padding:10px 14px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;">
                                <?php foreach ($branches as $b): ?>
                                <option value="<?= $b['id'] ?>"><?= e($b['name_ar']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:#374151;">نوع العضوية</label>
                            <select name="membership_type" class="form-input" style="width:100%;padding:10px 14px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;">
                                <option value="working">عاملة</option>
                                <option value="seasonal">موسمية</option>
                                <option value="sports">رياضية</option>
                                <option value="honorary">شرفية</option>
                                <option value="foreign">أجنبية</option>
                            </select>
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:#374151;">الجنسية</label>
                            <select name="nationality" class="form-input" style="width:100%;padding:10px 14px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;">
                                <option value="egyptian">مصري</option>
                                <option value="foreign">أجنبي</option>
                            </select>
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:#374151;">المؤهل</label>
                            <select name="qualification_id" class="form-input" style="width:100%;padding:10px 14px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;">
                                <option value="">— اختر —</option>
                                <?php foreach ($qualifications as $q): ?>
                                <option value="<?= $q['id'] ?>"><?= e($q['name_ar']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:#374151;">المهنة</label>
                            <input type="text" name="occupation" class="form-input" style="width:100%;padding:10px 14px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;">
                        </div>
                    </div>
                    <div style="margin-top:16px;display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;">
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:#374151;">العنوان</label>
                            <input type="text" name="residence_address" class="form-input" style="width:100%;padding:10px 14px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;">
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:#374151;">المنطقة</label>
                            <input type="text" name="area" class="form-input" style="width:100%;padding:10px 14px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;">
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:#374151;">المحافظة</label>
                            <input type="text" name="governorate" class="form-input" style="width:100%;padding:10px 14px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;">
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- ═══════════════ STEP 2: Dates & Timeline ═══════════════ -->
        <div class="wizard-panel" id="panel-2" style="display:none;">
            <div class="card" style="margin-bottom:16px;">
                <div style="padding:16px 20px;border-bottom:1px solid #E5E7EB;">
                    <h3 style="margin:0;font-size:16px;font-weight:700;"><i data-lucide="calendar" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> التواريخ والجدول الزمني</h3>
                    <p style="margin:6px 0 0;font-size:12px;color:#6B7280;">حدد تواريخ الانضمام والاستمارة لمحاكاة العضوية القديمة</p>
                </div>
                <div style="padding:20px;">
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:#374151;">تاريخ تقديم الاستمارة <span style="color:#EF4444;">*</span></label>
                            <input type="date" name="form_date" required class="form-input" style="width:100%;padding:10px 14px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;" value="2020-01-15">
                            <div style="font-size:11px;color:#6B7280;margin-top:4px;">تاريخ تقديم طلب العضوية الأصلي</div>
                        </div>
                        <div>
                            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:#374151;">تاريخ التفعيل/الانضمام <span style="color:#EF4444;">*</span></label>
                            <input type="date" name="join_date" required class="form-input" style="width:100%;padding:10px 14px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;" value="2020-02-01">
                            <div style="font-size:11px;color:#6B7280;margin-top:4px;">التاريخ الذي أصبح فيه العضو نشطاً</div>
                        </div>
                    </div>

                    <!-- Quick Presets -->
                    <div style="margin-top:20px;padding:16px;background:#F0FDF4;border-radius:10px;border:1px solid #86EFAC;">
                        <div style="font-size:13px;font-weight:700;color:#166534;margin-bottom:10px;"><i data-lucide="zap" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> إعدادات سريعة للسيناريوهات</div>
                        <div style="display:flex;flex-wrap:wrap;gap:8px;">
                            <button type="button" class="btn-preset" onclick="setPresetDates('2018-01-01','2018-02-01')" style="padding:6px 12px;background:#fff;border:1px solid #D1D5DB;border-radius:6px;font-size:12px;cursor:pointer;">عضو من 2018 (7 سنوات)</button>
                            <button type="button" class="btn-preset" onclick="setPresetDates('2020-06-01','2020-07-01')" style="padding:6px 12px;background:#fff;border:1px solid #D1D5DB;border-radius:6px;font-size:12px;cursor:pointer;">عضو من 2020 (5 سنوات)</button>
                            <button type="button" class="btn-preset" onclick="setPresetDates('2022-03-01','2022-04-01')" style="padding:6px 12px;background:#fff;border:1px solid #D1D5DB;border-radius:6px;font-size:12px;cursor:pointer;">عضو من 2022 (3 سنوات)</button>
                            <button type="button" class="btn-preset" onclick="setPresetDates('2024-01-01','2024-02-01')" style="padding:6px 12px;background:#fff;border:1px solid #D1D5DB;border-radius:6px;font-size:12px;cursor:pointer;">عضو من 2024 (سنة)</button>
                            <button type="button" class="btn-preset" onclick="setPresetDates('2015-01-01','2015-02-01')" style="padding:6px 12px;background:#fff;border:1px solid #D1D5DB;border-radius:6px;font-size:12px;cursor:pointer;">عضو من 2015 (10 سنوات)</button>
                        </div>
                    </div>

                    <!-- Timeline Preview -->
                    <div style="margin-top:20px;padding:16px;background:#EFF6FF;border-radius:10px;border:1px solid #93C5FD;">
                        <div style="font-size:13px;font-weight:700;color:#1E40AF;margin-bottom:8px;">معاينة الجدول الزمني</div>
                        <div id="timelinePreview" style="font-size:12px;color:#1E40AF;line-height:1.8;">
                            <div>سنوات العضوية: <strong id="yearsDiff">—</strong></div>
                            <div>اشتراكات سنوية مستحقة: <strong id="subsRequired">—</strong></div>
                            <div>أقساط شهرية محتملة: <strong id="installmentsMax">—</strong></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- ═══════════════ STEP 3: Financial ═══════════════ -->
        <div class="wizard-panel" id="panel-3" style="display:none;">
            <div class="card" style="margin-bottom:16px;">
                <div style="padding:16px 20px;border-bottom:1px solid #E5E7EB;">
                    <h3 style="margin:0;font-size:16px;font-weight:700;"><i data-lucide="banknote" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> البيانات المالية — رسوم الاستمارة وقيمة العضوية</h3>
                </div>
                <div style="padding:20px;">
                    <!-- Form Fee -->
                    <div style="padding:16px;background:#F9FAFB;border-radius:10px;border:1px solid #E5E7EB;margin-bottom:20px;">
                        <div style="font-size:14px;font-weight:700;color:#374151;margin-bottom:12px;">رسوم الاستمارة</div>
                        <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
                            <div>
                                <label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px;color:#6B7280;">المبلغ (ج.م)</label>
                                <input type="number" name="form_fee_amount" value="505" step="0.01" class="form-input" style="width:100%;padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:14px;">
                            </div>
                            <div>
                                <label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px;color:#6B7280;">طريقة الدفع</label>
                                <select name="form_fee_method" class="form-input" style="width:100%;padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:14px;" onchange="toggleCheckFields('form_fee', this.value)">
                                    <option value="cash">نقدي</option>
                                    <option value="check">شيك</option>
                                    <option value="visa">فيزا</option>
                                    <option value="bank_transfer">تحويل بنكي</option>
                                </select>
                            </div>
                        </div>
                        <div id="form_fee_check_fields" style="display:none;margin-top:12px;grid-template-columns:1fr 1fr 1fr;gap:12px;">
                            <input type="text" name="form_fee_check_number" placeholder="رقم الشيك" class="form-input" style="padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:13px;">
                            <input type="text" name="form_fee_check_bank" placeholder="البنك" class="form-input" style="padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:13px;">
                            <input type="date" name="form_fee_check_date" class="form-input" style="padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:13px;">
                        </div>
                    </div>

                    <!-- Membership Value -->
                    <div style="padding:16px;background:#F0FDF4;border-radius:10px;border:1px solid #86EFAC;">
                        <div style="font-size:14px;font-weight:700;color:#166534;margin-bottom:12px;">قيمة العضوية</div>
                        <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px;">
                            <div>
                                <label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px;color:#6B7280;">قيمة العضوية (ج.م)</label>
                                <input type="number" name="membership_value" value="150000" step="0.01" class="form-input" style="width:100%;padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:14px;">
                            </div>
                            <div>
                                <label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px;color:#6B7280;">الخصم (ج.م)</label>
                                <input type="number" name="discount_amount" value="0" step="0.01" class="form-input" style="width:100%;padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:14px;">
                            </div>
                            <div>
                                <label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px;color:#6B7280;">تاريخ السداد</label>
                                <input type="date" name="membership_payment_date" class="form-input" style="width:100%;padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:14px;">
                            </div>
                        </div>
                        <div style="margin-top:12px;">
                            <label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px;color:#6B7280;">طريقة سداد العضوية</label>
                            <select name="membership_payment_method" id="membershipPayMethod" class="form-input" style="width:100%;padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:14px;" onchange="handleMembershipPayMethod(this.value)">
                                <option value="cash">نقدي — كامل</option>
                                <option value="check">شيك — كامل</option>
                                <option value="visa">فيزا — كامل</option>
                                <option value="bank_transfer">تحويل بنكي — كامل</option>
                                <option value="installment">تقسيط (مقدم + أقساط شهرية)</option>
                            </select>
                        </div>
                        <!-- Check/Visa/Transfer fields for membership -->
                        <div id="membership_extra_fields" style="display:none;margin-top:12px;grid-template-columns:1fr 1fr 1fr;gap:12px;">
                            <input type="text" name="membership_check_number" placeholder="رقم الشيك" class="form-input" style="padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:13px;">
                            <input type="text" name="membership_check_bank" placeholder="البنك" class="form-input" style="padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:13px;">
                            <input type="date" name="membership_check_date" class="form-input" style="padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:13px;">
                            <input type="text" name="membership_visa_reference" placeholder="رقم عملية الفيزا" class="form-input" style="padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:13px;">
                            <input type="text" name="membership_transfer_reference" placeholder="رقم التحويل" class="form-input" style="padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:13px;">
                            <input type="text" name="membership_transfer_bank" placeholder="بنك التحويل" class="form-input" style="padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:13px;">
                        </div>
                    </div>

                    <!-- Quick Value Presets -->
                    <div style="margin-top:16px;display:flex;flex-wrap:wrap;gap:8px;">
                        <span style="font-size:12px;color:#6B7280;padding:6px 0;">قيم شائعة:</span>
                        <button type="button" onclick="document.querySelector('[name=membership_value]').value='150000'" style="padding:4px 10px;background:#EFF6FF;border:1px solid #93C5FD;border-radius:4px;font-size:12px;cursor:pointer;">150,000</button>
                        <button type="button" onclick="document.querySelector('[name=membership_value]').value='225000'" style="padding:4px 10px;background:#EFF6FF;border:1px solid #93C5FD;border-radius:4px;font-size:12px;cursor:pointer;">225,000</button>
                        <button type="button" onclick="document.querySelector('[name=membership_value]').value='300000'" style="padding:4px 10px;background:#EFF6FF;border:1px solid #93C5FD;border-radius:4px;font-size:12px;cursor:pointer;">300,000</button>
                        <button type="button" onclick="document.querySelector('[name=membership_value]').value='500000'" style="padding:4px 10px;background:#EFF6FF;border:1px solid #93C5FD;border-radius:4px;font-size:12px;cursor:pointer;">500,000</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- ═══════════════ STEP 4: Installments ═══════════════ -->
        <div class="wizard-panel" id="panel-4" style="display:none;">
            <div class="card" style="margin-bottom:16px;">
                <div style="padding:16px 20px;border-bottom:1px solid #E5E7EB;">
                    <h3 style="margin:0;font-size:16px;font-weight:700;"><i data-lucide="calculator" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> خطة التقسيط والأقساط المدفوعة</h3>
                    <p style="margin:6px 0 0;font-size:12px;color:#6B7280;">فقط إذا كانت طريقة السداد "تقسيط" — حدد الأقساط التي تم سدادها بالفعل</p>
                </div>
                <div style="padding:20px;">
                    <div id="installmentSection">
                        <div id="noInstallmentMsg" style="text-align:center;padding:40px;color:#9CA3AF;">
                            <i data-lucide="info" style="width:32px;height:32px;margin-bottom:8px;"></i>
                            <div style="font-size:14px;">طريقة السداد ليست "تقسيط" — يمكنك تخطي هذه الخطوة</div>
                        </div>
                        <div id="installmentFields" style="display:none;">
                            <div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:12px;margin-bottom:16px;">
                                <div>
                                    <label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px;color:#6B7280;">المقدم (ج.م)</label>
                                    <input type="number" name="inst_down_payment" id="instDown" value="37500" step="0.01" class="form-input" style="width:100%;padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:14px;" onchange="recalcInstallments()">
                                </div>
                                <div>
                                    <label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px;color:#6B7280;">عدد الأشهر</label>
                                    <input type="number" name="inst_months" id="instMonths" value="12" min="1" max="30" class="form-input" style="width:100%;padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:14px;" onchange="recalcInstallments()">
                                </div>
                                <div>
                                    <label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px;color:#6B7280;">نسبة الفائدة %</label>
                                    <input type="number" name="inst_interest_rate" id="instRate" value="22" step="0.01" class="form-input" style="width:100%;padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:14px;" onchange="recalcInstallments()">
                                </div>
                                <div>
                                    <label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px;color:#6B7280;">تاريخ البدء</label>
                                    <input type="date" name="inst_start_date" id="instStart" class="form-input" style="width:100%;padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:14px;" onchange="recalcInstallments()">
                                </div>
                            </div>
                            <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px;margin-bottom:16px;">
                                <div>
                                    <label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px;color:#6B7280;">طريقة دفع المقدم</label>
                                    <select name="inst_down_method" class="form-input" style="width:100%;padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:14px;">
                                        <option value="cash">نقدي</option>
                                        <option value="check">شيك</option>
                                        <option value="visa">فيزا</option>
                                    </select>
                                </div>
                                <div>
                                    <label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px;color:#6B7280;">رقم شيك المقدم</label>
                                    <input type="text" name="inst_down_check_number" class="form-input" style="width:100%;padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:13px;">
                                </div>
                                <div>
                                    <label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px;color:#6B7280;">بنك شيك المقدم</label>
                                    <input type="text" name="inst_down_check_bank" class="form-input" style="width:100%;padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:13px;">
                                </div>
                            </div>

                            <!-- Schedule Preview -->
                            <div style="margin-top:16px;padding:16px;background:#F9FAFB;border-radius:10px;border:1px solid #E5E7EB;">
                                <div style="font-size:13px;font-weight:700;margin-bottom:8px;color:#374151;">جدول الأقساط <span id="instSummary" style="font-weight:400;color:#6B7280;"></span></div>
                                <div style="max-height:300px;overflow-y:auto;">
                                    <table style="width:100%;border-collapse:collapse;font-size:12px;">
                                        <thead>
                                            <tr style="background:#E5E7EB;">
                                                <th style="padding:6px 8px;text-align:right;">رقم</th>
                                                <th style="padding:6px 8px;text-align:right;">تاريخ الاستحقاق</th>
                                                <th style="padding:6px 8px;text-align:right;">المبلغ</th>
                                                <th style="padding:6px 8px;text-align:right;">أصل</th>
                                                <th style="padding:6px 8px;text-align:right;">فائدة</th>
                                                <th style="padding:6px 8px;text-align:center;">مدفوع؟</th>
                                                <th style="padding:6px 8px;text-align:right;">تاريخ السداد</th>
                                                <th style="padding:6px 8px;text-align:right;">طريقة</th>
                                            </tr>
                                        </thead>
                                        <tbody id="installmentSchedule"></tbody>
                                    </table>
                                </div>
                            </div>
                            <input type="hidden" name="inst_paid_numbers" id="instPaidNumbers" value="">

                            <!-- Cheques -->
                            <div style="margin-top:16px;padding:16px;background:#FFF7ED;border-radius:10px;border:1px solid #FDBA74;">
                                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
                                    <div style="font-size:13px;font-weight:700;color:#9A3412;">شيكات مقدمة</div>
                                    <button type="button" onclick="addCheque()" style="padding:4px 10px;background:#fff;border:1px solid #FDBA74;border-radius:4px;font-size:12px;cursor:pointer;">+ إضافة شيك</button>
                                </div>
                                <div id="chequesList"></div>
                                <input type="hidden" name="cheque_count" id="chequeCount" value="0">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- ═══════════════ STEP 5: Dependents ═══════════════ -->
        <div class="wizard-panel" id="panel-5" style="display:none;">
            <div class="card" style="margin-bottom:16px;">
                <div style="padding:16px 20px;border-bottom:1px solid #E5E7EB;">
                    <h3 style="margin:0;font-size:16px;font-weight:700;"><i data-lucide="users" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> الملحقون (الزوجات والأبناء والأعضاء المؤقتون)</h3>
                </div>
                <div style="padding:20px;">
                    <!-- Spouses -->
                    <div style="margin-bottom:24px;">
                        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
                            <div style="font-size:14px;font-weight:700;color:#374151;">الزوجات</div>
                            <button type="button" onclick="addSpouse()" style="padding:6px 14px;background:#2563EB;color:#fff;border:none;border-radius:6px;font-size:12px;cursor:pointer;font-weight:600;">+ إضافة زوجة</button>
                        </div>
                        <div id="spousesList"></div>
                        <input type="hidden" name="spouse_count" id="spouseCount" value="0">
                    </div>

                    <!-- Children -->
                    <div style="margin-bottom:24px;">
                        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
                            <div style="font-size:14px;font-weight:700;color:#374151;">الأبناء</div>
                            <button type="button" onclick="addChild()" style="padding:6px 14px;background:#2563EB;color:#fff;border:none;border-radius:6px;font-size:12px;cursor:pointer;font-weight:600;">+ إضافة ابن/ابنة</button>
                        </div>
                        <div id="childrenList"></div>
                        <input type="hidden" name="child_count" id="childCount" value="0">
                    </div>

                    <!-- Temporary Members -->
                    <div>
                        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
                            <div style="font-size:14px;font-weight:700;color:#374151;">أعضاء مؤقتون</div>
                            <button type="button" onclick="addTempMember()" style="padding:6px 14px;background:#2563EB;color:#fff;border:none;border-radius:6px;font-size:12px;cursor:pointer;font-weight:600;">+ إضافة عضو مؤقت</button>
                        </div>
                        <div id="tempMembersList"></div>
                        <input type="hidden" name="temp_member_count" id="tempMemberCount" value="0">
                    </div>
                </div>
            </div>
        </div>

        <!-- ═══════════════ STEP 6: Subscriptions ═══════════════ -->
        <div class="wizard-panel" id="panel-6" style="display:none;">
            <div class="card" style="margin-bottom:16px;">
                <div style="padding:16px 20px;border-bottom:1px solid #E5E7EB;">
                    <h3 style="margin:0;font-size:16px;font-weight:700;"><i data-lucide="repeat" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> الاشتراكات السنوية</h3>
                    <p style="margin:6px 0 0;font-size:12px;color:#6B7280;">أضف اشتراكات سنوية — مدفوعة أو متأخرة — لاختبار الغرامات والإسقاط</p>
                </div>
                <div style="padding:20px;">
                    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
                        <button type="button" onclick="generateSubscriptionYears()" style="padding:6px 14px;background:#059669;color:#fff;border:none;border-radius:6px;font-size:12px;cursor:pointer;font-weight:600;"><i data-lucide="wand-2" style="width:13px;height:13px;vertical-align:middle;margin-left:4px;"></i> توليد تلقائي من تاريخ الانضمام</button>
                        <button type="button" onclick="addSubscriptionRow()" style="padding:6px 14px;background:#2563EB;color:#fff;border:none;border-radius:6px;font-size:12px;cursor:pointer;font-weight:600;">+ إضافة سنة يدوياً</button>
                    </div>

                    <div style="max-height:400px;overflow-y:auto;">
                        <table style="width:100%;border-collapse:collapse;font-size:12px;" id="subsTable">
                            <thead>
                                <tr style="background:#F3F4F6;">
                                    <th style="padding:8px;text-align:right;">الشخص</th>
                                    <th style="padding:8px;text-align:right;">السنة المالية</th>
                                    <th style="padding:8px;text-align:right;">المبلغ الأساسي</th>
                                    <th style="padding:8px;text-align:right;">رسم تنمية</th>
                                    <th style="padding:8px;text-align:right;">الإجمالي</th>
                                    <th style="padding:8px;text-align:right;">المدفوع</th>
                                    <th style="padding:8px;text-align:right;">الغرامة</th>
                                    <th style="padding:8px;text-align:center;">الحالة</th>
                                    <th style="padding:8px;text-align:right;">تاريخ السداد</th>
                                    <th style="padding:8px;text-align:center;">حذف</th>
                                </tr>
                            </thead>
                            <tbody id="subscriptionRows"></tbody>
                        </table>
                    </div>
                    <input type="hidden" name="subscription_count" id="subscriptionCount" value="0">
                </div>
            </div>
        </div>

        <!-- ═══════════════ STEP 7: Violations & Fines ═══════════════ -->
        <div class="wizard-panel" id="panel-7" style="display:none;">
            <div class="card" style="margin-bottom:16px;">
                <div style="padding:16px 20px;border-bottom:1px solid #E5E7EB;">
                    <h3 style="margin:0;font-size:16px;font-weight:700;"><i data-lucide="shield-alert" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> المخالفات والغرامات</h3>
                    <p style="margin:6px 0 0;font-size:12px;color:#6B7280;">اختياري — أضف مخالفات وغرامات تاريخية لاختبار سيناريوهات الإيقاف والاستئناف</p>
                </div>
                <div style="padding:20px;">
                    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
                        <button type="button" onclick="addViolation()" style="padding:6px 14px;background:#DC2626;color:#fff;border:none;border-radius:6px;font-size:12px;cursor:pointer;font-weight:600;">+ إضافة مخالفة</button>
                    </div>
                    <div id="violationsList"></div>
                    <input type="hidden" name="violation_count" id="violationCount" value="0">

                    <!-- Final Summary -->
                    <div style="margin-top:24px;padding:20px;background:linear-gradient(135deg,#EFF6FF,#F0FDF4);border-radius:12px;border:1px solid #93C5FD;">
                        <div style="font-size:16px;font-weight:800;color:#1E40AF;margin-bottom:12px;"><i data-lucide="check-circle-2" style="width:20px;height:20px;vertical-align:middle;margin-left:6px;"></i> ملخص العضوية</div>
                        <div id="finalSummary" style="font-size:13px;color:#374151;line-height:2;"></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Navigation Buttons -->
        <div class="card" style="padding:16px 20px;display:flex;justify-content:space-between;align-items:center;">
            <button type="button" id="btnPrev" onclick="prevStep()" style="padding:10px 24px;background:#F3F4F6;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;display:none;">
                <i data-lucide="arrow-right" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> السابق
            </button>
            <div style="flex:1;"></div>
            <button type="button" id="btnNext" onclick="nextStep()" style="padding:10px 24px;background:#2563EB;color:#fff;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;">
                التالي <i data-lucide="arrow-left" style="width:16px;height:16px;vertical-align:middle;margin-right:4px;"></i>
            </button>
            <button type="submit" id="btnSubmit" style="display:none;padding:10px 24px;background:#059669;color:#fff;border:none;border-radius:8px;font-size:14px;font-weight:700;cursor:pointer;">
                <i data-lucide="rocket" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> إنشاء العضوية بأثر رجعي
            </button>
        </div>
    </form>
</div>

<script>
let currentStep = 1;
const totalSteps = 7;

function updateStepUI() {
    for (let i = 1; i <= totalSteps; i++) {
        const panel = document.getElementById('panel-' + i);
        const circle = document.getElementById('stepCircle' + i);
        const label = document.getElementById('stepLabel' + i);
        panel.style.display = (i === currentStep) ? '' : 'none';
        if (i < currentStep) {
            circle.style.background = '#059669';
            circle.style.color = '#fff';
            circle.innerHTML = '&#10003;';
            label.style.color = '#059669';
            label.style.fontWeight = '600';
        } else if (i === currentStep) {
            circle.style.background = '#2563EB';
            circle.style.color = '#fff';
            circle.innerHTML = i;
            label.style.color = '#2563EB';
            label.style.fontWeight = '700';
        } else {
            circle.style.background = '#E5E7EB';
            circle.style.color = '#9CA3AF';
            circle.innerHTML = i;
            label.style.color = '#6B7280';
            label.style.fontWeight = '400';
        }
    }
    document.getElementById('progressFill').style.width = ((currentStep - 1) / (totalSteps - 1) * 100) + '%';
    document.getElementById('btnPrev').style.display = currentStep > 1 ? '' : 'none';
    document.getElementById('btnNext').style.display = currentStep < totalSteps ? '' : 'none';
    document.getElementById('btnSubmit').style.display = currentStep === totalSteps ? '' : 'none';

    if (currentStep === 4) updateInstallmentVisibility();
    if (currentStep === 7) updateFinalSummary();
    if (currentStep === 2) updateTimelinePreview();
}

function markInvalid(el, msg) {
    el.style.border = '2px solid #EF4444';
    el.style.background = '#FEF2F2';
    let hint = el.nextElementSibling;
    if (!hint || !hint.classList.contains('val-hint')) {
        hint = document.createElement('div');
        hint.className = 'val-hint';
        hint.style.cssText = 'font-size:11px;color:#DC2626;margin-top:3px;font-weight:600;';
        el.parentNode.insertBefore(hint, el.nextSibling);
    }
    hint.textContent = msg;
}

function clearInvalid(el) {
    el.style.border = '';
    el.style.background = '';
    const hint = el.nextElementSibling;
    if (hint && hint.classList.contains('val-hint')) hint.remove();
}

function validateStep(step) {
    const panel = document.getElementById('panel-' + step);
    if (!panel) return true;
    let valid = true;
    panel.querySelectorAll('.val-hint').forEach(h => h.remove());
    panel.querySelectorAll('.form-input,.form-select,select,input,textarea').forEach(el => { el.style.border = ''; el.style.background = ''; });

    function check(el, msg) {
        if (!el) return;
        const val = el.value ? el.value.trim() : '';
        if (!val) { markInvalid(el, msg); valid = false; }
    }
    function checkMin(el, min, msg) {
        if (!el) return;
        if (parseFloat(el.value) < min || !el.value.trim()) { markInvalid(el, msg); valid = false; }
    }

    if (step === 1) {
        check(panel.querySelector('[name=full_name_ar]'), 'الاسم بالعربية مطلوب');
        check(panel.querySelector('[name=branch_id]'), 'الفرع مطلوب');
        check(panel.querySelector('[name=gender]'), 'النوع مطلوب');
        check(panel.querySelector('[name=phone_mobile]'), 'رقم الهاتف المحمول مطلوب');
        // date_of_birth OR national_id required
        const dob = panel.querySelector('[name=date_of_birth]');
        const nid = panel.querySelector('[name=national_id]');
        if ((!dob || !dob.value.trim()) && (!nid || nid.value.trim().length !== 14)) {
            if (dob) markInvalid(dob, 'تاريخ الميلاد مطلوب (أو أدخل الرقم القومي 14 رقم)');
            valid = false;
        }
    }

    if (step === 2) {
        check(panel.querySelector('[name=form_date]'), 'تاريخ الاستمارة مطلوب');
        check(panel.querySelector('[name=join_date]'), 'تاريخ الانضمام مطلوب');
    }

    if (step === 3) {
        checkMin(panel.querySelector('[name=membership_value]'), 1, 'قيمة العضوية مطلوبة');
    }

    // Step 5: validate dependents — each one needs mandatory fields matching DB NOT NULL
    if (step === 5) {
        const sc = parseInt(document.getElementById('spouseCount').value) || 0;
        for (let i = 1; i <= sc; i++) {
            const row = document.getElementById('spouseRow' + i);
            if (!row) continue;
            const nameEl = row.querySelector('[name=spouse_name_' + i + ']');
            const dobEl = row.querySelector('[name=spouse_dob_' + i + ']');
            const nidEl = row.querySelector('[name=spouse_nid_' + i + ']');
            const marriageEl = row.querySelector('[name=spouse_marriage_date_' + i + ']');
            const joinEl = row.querySelector('[name=spouse_join_date_' + i + ']');
            check(nameEl, 'اسم الزوجة مطلوب');
            check(marriageEl, 'تاريخ الزواج مطلوب');
            check(joinEl, 'تاريخ الانضمام مطلوب');
            if ((!dobEl || !dobEl.value.trim()) && (!nidEl || nidEl.value.trim().length !== 14)) {
                if (dobEl) markInvalid(dobEl, 'تاريخ الميلاد مطلوب (أو الرقم القومي)');
                valid = false;
            }
        }
        const cc = parseInt(document.getElementById('childCount').value) || 0;
        for (let i = 1; i <= cc; i++) {
            const row = document.getElementById('childRow' + i);
            if (!row) continue;
            const nameEl = row.querySelector('[name=child_name_' + i + ']');
            const dobEl = row.querySelector('[name=child_dob_' + i + ']');
            const nidEl = row.querySelector('[name=child_nid_' + i + ']');
            const joinEl = row.querySelector('[name=child_join_date_' + i + ']');
            check(nameEl, 'اسم الابن/الابنة مطلوب');
            check(joinEl, 'تاريخ الانضمام مطلوب');
            if ((!dobEl || !dobEl.value.trim()) && (!nidEl || nidEl.value.trim().length !== 14)) {
                if (dobEl) markInvalid(dobEl, 'تاريخ الميلاد مطلوب (أو الرقم القومي)');
                valid = false;
            }
        }
        const tc = parseInt(document.getElementById('tempMemberCount').value) || 0;
        for (let i = 1; i <= tc; i++) {
            const row = document.getElementById('tempRow' + i);
            if (!row) continue;
            const nameEl = row.querySelector('[name=temp_name_' + i + ']');
            const dobEl = row.querySelector('[name=temp_dob_' + i + ']');
            const nidEl = row.querySelector('[name=temp_nid_' + i + ']');
            const catEl = row.querySelector('[name=temp_category_' + i + ']');
            check(nameEl, 'اسم العضو المؤقت مطلوب');
            check(catEl, 'الفئة مطلوبة');
            if ((!dobEl || !dobEl.value.trim()) && (!nidEl || nidEl.value.trim().length !== 14)) {
                if (dobEl) markInvalid(dobEl, 'تاريخ الميلاد مطلوب (أو الرقم القومي)');
                valid = false;
            }
        }
    }

    if (!valid) {
        const firstBad = panel.querySelector('[style*="border: 2px solid"]');
        if (firstBad) { firstBad.focus(); firstBad.scrollIntoView({behavior:'smooth', block:'center'}); }
    }
    return valid;
}

function nextStep() {
    if (!validateStep(currentStep)) return;
    if (currentStep < totalSteps) { currentStep++; updateStepUI(); window.scrollTo(0, 0); }
}
function prevStep() {
    if (currentStep > 1) { currentStep--; updateStepUI(); window.scrollTo(0, 0); }
}

document.querySelectorAll('.wizard-step-indicator').forEach(el => {
    el.addEventListener('click', () => {
        const s = parseInt(el.dataset.step);
        if (s <= currentStep) { currentStep = s; updateStepUI(); }
    });
});

// Date presets
function setPresetDates(form, join) {
    document.querySelector('[name=form_date]').value = form;
    document.querySelector('[name=join_date]').value = join;
    updateTimelinePreview();
}

function updateTimelinePreview() {
    const joinDate = document.querySelector('[name=join_date]').value;
    if (!joinDate) return;
    const join = new Date(joinDate);
    const now = new Date();
    const years = Math.floor((now - join) / (365.25 * 24 * 60 * 60 * 1000));
    document.getElementById('yearsDiff').textContent = years + ' سنة';
    document.getElementById('subsRequired').textContent = years + ' اشتراك';
    document.getElementById('installmentsMax').textContent = 'حتى ' + Math.min(years * 12, 30) + ' شهر';
}

// Financial fields toggles
function toggleCheckFields(prefix, method) {
    const el = document.getElementById(prefix + '_check_fields');
    if (el) { el.style.display = (method === 'check') ? 'grid' : 'none'; }
}

function handleMembershipPayMethod(method) {
    const extra = document.getElementById('membership_extra_fields');
    if (method !== 'cash' && method !== 'installment') {
        extra.style.display = 'grid';
        extra.style.gridTemplateColumns = '1fr 1fr 1fr';
    } else {
        extra.style.display = 'none';
    }
    updateInstallmentVisibility();
}

function updateInstallmentVisibility() {
    const method = document.getElementById('membershipPayMethod').value;
    const show = method === 'installment';
    document.getElementById('noInstallmentMsg').style.display = show ? 'none' : '';
    document.getElementById('installmentFields').style.display = show ? '' : 'none';
    if (show) recalcInstallments();
}

// Installment schedule calculation
function recalcInstallments() {
    const total = parseFloat(document.querySelector('[name=membership_value]').value) || 150000;
    const down = parseFloat(document.getElementById('instDown').value) || 37500;
    const months = parseInt(document.getElementById('instMonths').value) || 12;
    const rate = parseFloat(document.getElementById('instRate').value) || 22;
    const startDate = document.getElementById('instStart').value || document.querySelector('[name=join_date]').value || new Date().toISOString().split('T')[0];

    const remaining = total - down;
    const monthlyRate = rate / 1200;
    const monthlyPrincipal = remaining / months;
    let balance = remaining;
    let totalInterest = 0;
    const tbody = document.getElementById('installmentSchedule');
    tbody.innerHTML = '';

    for (let i = 1; i <= months; i++) {
        const interest = Math.round(balance * monthlyRate * 100) / 100;
        totalInterest += interest;
        const principal = (i === months) ? balance : monthlyPrincipal;
        const amount = Math.round((principal + interest) * 100) / 100;
        balance -= principal;
        if (balance < 0) balance = 0;

        const dueDate = new Date(startDate);
        dueDate.setMonth(dueDate.getMonth() + i);
        const dueDateStr = dueDate.toISOString().split('T')[0];
        const isPast = dueDate < new Date();

        tbody.innerHTML += `
            <tr style="border-bottom:1px solid #F3F4F6;${isPast ? 'background:#FEF3C7;' : ''}">
                <td style="padding:6px 8px;">${i}</td>
                <td style="padding:6px 8px;direction:ltr;">${dueDateStr}</td>
                <td style="padding:6px 8px;">${amount.toLocaleString('ar-EG', {minimumFractionDigits:2})}</td>
                <td style="padding:6px 8px;">${Math.round(principal).toLocaleString()}</td>
                <td style="padding:6px 8px;">${interest.toLocaleString('ar-EG', {minimumFractionDigits:2})}</td>
                <td style="padding:6px 8px;text-align:center;">
                    <input type="checkbox" class="inst-paid-cb" data-num="${i}" onchange="updatePaidInstallments()" ${isPast ? 'checked' : ''}>
                </td>
                <td style="padding:6px 8px;">
                    <input type="date" name="inst_paid_date_${i}" value="${isPast ? dueDateStr : ''}" style="font-size:11px;padding:2px 4px;border:1px solid #D1D5DB;border-radius:4px;width:100%;">
                </td>
                <td style="padding:6px 8px;">
                    <select name="inst_paid_method_${i}" style="font-size:11px;padding:2px 4px;border:1px solid #D1D5DB;border-radius:4px;">
                        <option value="cash">نقدي</option>
                        <option value="check">شيك</option>
                    </select>
                </td>
            </tr>`;
    }

    document.getElementById('instSummary').textContent = `— إجمالي الفائدة: ${totalInterest.toLocaleString('ar-EG', {minimumFractionDigits:2})} ج.م | القسط الشهري ≈ ${Math.round((remaining + totalInterest) / months).toLocaleString()} ج.م`;
    updatePaidInstallments();
}

function updatePaidInstallments() {
    const checks = document.querySelectorAll('.inst-paid-cb:checked');
    const nums = Array.from(checks).map(cb => cb.dataset.num);
    document.getElementById('instPaidNumbers').value = nums.join(',');
}

// Cheques
let chequeIdx = 0;
function addCheque() {
    chequeIdx++;
    document.getElementById('chequeCount').value = chequeIdx;
    document.getElementById('chequesList').innerHTML += `
        <div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr auto;gap:8px;margin-bottom:8px;align-items:end;" id="chequeRow${chequeIdx}">
            <div><label style="font-size:11px;color:#6B7280;">رقم الشيك</label><input type="text" name="cheque_number_${chequeIdx}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></div>
            <div><label style="font-size:11px;color:#6B7280;">البنك</label><input type="text" name="cheque_bank_${chequeIdx}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></div>
            <div><label style="font-size:11px;color:#6B7280;">التاريخ</label><input type="date" name="cheque_date_${chequeIdx}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></div>
            <div><label style="font-size:11px;color:#6B7280;">المبلغ</label><input type="number" name="cheque_amount_${chequeIdx}" step="0.01" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></div>
            <button type="button" onclick="document.getElementById('chequeRow${chequeIdx}').remove()" style="padding:6px 10px;background:#FEE2E2;border:1px solid #FECACA;border-radius:4px;color:#DC2626;cursor:pointer;font-size:12px;">×</button>
        </div>`;
}

// Spouses — Pricing Rules from system:
// SPOUSE_BASE_MEMBER_FEE: 15% of membership_value (1st spouse, base member)
// SPOUSE_2ND_FEE: 10% + 150/year
// SPOUSE_3RD_FEE: 20% + 200/year
// SPOUSE_4TH_FEE: 30% + 300/year
// SPOUSE_FOREIGN_FEE: 15% of membership_value (foreign nationality)
// SPOUSE_ACQUIRED_MEMBER_FEE: 50% (acquired member)
const SPOUSE_FEE_RULES = {
    1: { pct: 15, label: 'زوجة أولى — 15%' },
    2: { pct: 10, annual: 150, label: 'زوجة ثانية — 10% + 150/سنة' },
    3: { pct: 20, annual: 200, label: 'زوجة ثالثة — 20% + 200/سنة' },
    4: { pct: 30, annual: 300, label: 'زوجة رابعة — 30% + 300/سنة' },
};
const SPOUSE_FOREIGN_PCT = 15;

function calcSpouseFee(idx) {
    const membershipValue = parseFloat(document.querySelector('[name=membership_value]').value) || 150000;
    const nationality = document.querySelector(`[name=spouse_nationality_${idx}]`).value;
    const marriageDate = document.querySelector(`[name=spouse_marriage_date_${idx}]`).value;
    const joinDate = document.querySelector('[name=join_date]').value;
    const feeInput = document.querySelector(`[name=spouse_fee_${idx}]`);
    const feeHint = document.getElementById(`spouseFeeHint${idx}`);

    let fee = 0;
    let hint = '';

    if (nationality && nationality !== 'مصري' && nationality !== 'egyptian') {
        fee = membershipValue * (SPOUSE_FOREIGN_PCT / 100);
        hint = `أجنبي: ${SPOUSE_FOREIGN_PCT}% × ${membershipValue.toLocaleString()} = ${fee.toLocaleString()} ج.م`;
    } else {
        const rule = SPOUSE_FEE_RULES[idx] || SPOUSE_FEE_RULES[4];
        fee = membershipValue * (rule.pct / 100);
        hint = `${rule.label} × ${membershipValue.toLocaleString()} = ${fee.toLocaleString()} ج.م`;
        if (rule.annual && marriageDate && joinDate) {
            const baseDate = new Date(Math.max(new Date(marriageDate), new Date(joinDate)));
            const now = new Date();
            const years = Math.max(1, Math.ceil((now - baseDate) / (365.25 * 24 * 60 * 60 * 1000)));
            const annualTotal = rule.annual * years;
            fee += annualTotal;
            hint += ` + ${rule.annual}×${years} سنة = ${fee.toLocaleString()} ج.م`;
        }
    }

    feeInput.value = fee.toFixed(2);
    if (feeHint) feeHint.textContent = hint;
}

let spouseIdx = 0;
function addSpouse() {
    spouseIdx++;
    document.getElementById('spouseCount').value = spouseIdx;
    const joinDate = document.querySelector('[name=join_date]').value || '';
    const idx = spouseIdx;
    document.getElementById('spousesList').innerHTML += `
        <div style="padding:12px;background:#F9FAFB;border-radius:8px;border:1px solid #E5E7EB;margin-bottom:10px;" id="spouseRow${idx}">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;">
                <span style="font-size:13px;font-weight:600;color:#374151;">زوجة #${idx}</span>
                <button type="button" onclick="document.getElementById('spouseRow${idx}').remove()" style="padding:2px 8px;background:#FEE2E2;border:1px solid #FECACA;border-radius:4px;color:#DC2626;cursor:pointer;font-size:12px;">حذف</button>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;">
                <div><label style="font-size:11px;color:#6B7280;">الاسم *</label><input type="text" name="spouse_name_${idx}" required class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></div>
                <div><label style="font-size:11px;color:#6B7280;">الرقم القومي</label><input type="text" name="spouse_nid_${idx}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;direction:ltr;"></div>
                <div><label style="font-size:11px;color:#6B7280;">تاريخ الميلاد</label><input type="date" name="spouse_dob_${idx}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></div>
                <div>
                    <label style="font-size:11px;color:#6B7280;">الجنسية *</label>
                    <select name="spouse_nationality_${idx}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;" onchange="calcSpouseFee(${idx})">
                        <option value="مصري">مصري</option>
                        <option value="أجنبي">أجنبي</option>
                    </select>
                </div>
                <div><label style="font-size:11px;color:#6B7280;">تاريخ الزواج *</label><input type="date" name="spouse_marriage_date_${idx}" required class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;" onchange="calcSpouseFee(${idx})"></div>
                <div><label style="font-size:11px;color:#6B7280;">الهاتف</label><input type="text" name="spouse_phone_${idx}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;direction:ltr;"></div>
                <div><label style="font-size:11px;color:#6B7280;">تاريخ الانضمام</label><input type="date" name="spouse_join_date_${idx}" value="${joinDate}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></div>
                <div>
                    <label style="font-size:11px;color:#6B7280;">رسوم الإضافة (ج.م)</label>
                    <input type="number" name="spouse_fee_${idx}" value="0" step="0.01" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;">
                    <div id="spouseFeeHint${idx}" style="font-size:10px;color:#2563EB;margin-top:2px;"></div>
                </div>
                <div style="display:flex;align-items:end;">
                    <button type="button" onclick="calcSpouseFee(${idx})" style="padding:5px 10px;background:#EFF6FF;border:1px solid #93C5FD;border-radius:4px;font-size:11px;cursor:pointer;color:#1D4ED8;">حساب الرسوم تلقائياً</button>
                </div>
            </div>
            <div style="margin-top:8px;display:flex;align-items:center;gap:12px;">
                <label style="font-size:11px;color:#6B7280;display:flex;align-items:center;gap:4px;"><input type="checkbox" name="spouse_separate_fee_${idx}" value="1"> رسوم إضافة منفصلة (ليست ضمن العضوية)</label>
                <select name="spouse_pay_method_${idx}" style="font-size:11px;padding:4px 8px;border:1px solid #D1D5DB;border-radius:4px;"><option value="cash">نقدي</option><option value="check">شيك</option></select>
            </div>
        </div>`;
    calcSpouseFee(idx);
}

// Children
let childIdx = 0;
function addChild() {
    childIdx++;
    document.getElementById('childCount').value = childIdx;
    const joinDate = document.querySelector('[name=join_date]').value || '';
    document.getElementById('childrenList').innerHTML += `
        <div style="padding:12px;background:#F9FAFB;border-radius:8px;border:1px solid #E5E7EB;margin-bottom:10px;" id="childRow${childIdx}">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;">
                <span style="font-size:13px;font-weight:600;color:#374151;">ابن/ابنة #${childIdx}</span>
                <button type="button" onclick="document.getElementById('childRow${childIdx}').remove()" style="padding:2px 8px;background:#FEE2E2;border:1px solid #FECACA;border-radius:4px;color:#DC2626;cursor:pointer;font-size:12px;">حذف</button>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:10px;">
                <div><label style="font-size:11px;color:#6B7280;">الاسم *</label><input type="text" name="child_name_${childIdx}" required class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></div>
                <div><label style="font-size:11px;color:#6B7280;">الرقم القومي</label><input type="text" name="child_nid_${childIdx}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;direction:ltr;"></div>
                <div><label style="font-size:11px;color:#6B7280;">تاريخ الميلاد</label><input type="date" name="child_dob_${childIdx}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></div>
                <div><label style="font-size:11px;color:#6B7280;">النوع</label><select name="child_gender_${childIdx}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"><option value="male">ذكر</option><option value="female">أنثى</option></select></div>
            </div>
            <div style="margin-top:8px;display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;">
                <div><label style="font-size:11px;color:#6B7280;">تاريخ الانضمام</label><input type="date" name="child_join_date_${childIdx}" value="${joinDate}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></div>
                <div><label style="font-size:11px;color:#6B7280;">رسوم الإضافة</label><input type="number" name="child_fee_${childIdx}" value="0" step="0.01" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></div>
                <div style="display:flex;align-items:end;">
                    <label style="font-size:11px;color:#6B7280;display:flex;align-items:center;gap:4px;"><input type="checkbox" name="child_separate_fee_${childIdx}" value="1"> رسوم منفصلة</label>
                </div>
            </div>
        </div>`;
}

// Temporary Members
let tempIdx = 0;
function addTempMember() {
    tempIdx++;
    document.getElementById('tempMemberCount').value = tempIdx;
    const joinDate = document.querySelector('[name=join_date]').value || '';
    const idx = tempIdx;
    document.getElementById('tempMembersList').innerHTML += `
        <div style="padding:12px;background:#FFF7ED;border-radius:8px;border:1px solid #FDBA74;margin-bottom:10px;" id="tempRow${idx}">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;">
                <span style="font-size:13px;font-weight:600;color:#9A3412;">عضو مؤقت #${idx}</span>
                <button type="button" onclick="document.getElementById('tempRow${idx}').remove()" style="padding:2px 8px;background:#FEE2E2;border:1px solid #FECACA;border-radius:4px;color:#DC2626;cursor:pointer;font-size:12px;">حذف</button>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:10px;">
                <div><label style="font-size:11px;color:#6B7280;">الاسم *</label><input type="text" name="temp_name_${idx}" required class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></div>
                <div><label style="font-size:11px;color:#6B7280;">الرقم القومي</label><input type="text" name="temp_nid_${idx}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;direction:ltr;"></div>
                <div><label style="font-size:11px;color:#6B7280;">تاريخ الميلاد</label><input type="date" name="temp_dob_${idx}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></div>
                <div><label style="font-size:11px;color:#6B7280;">النوع</label><select name="temp_gender_${idx}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"><option value="male">ذكر</option><option value="female">أنثى</option></select></div>
            </div>
            <div style="margin-top:8px;display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;">
                <div>
                    <label style="font-size:11px;color:#6B7280;">الفئة *</label>
                    <select name="temp_category_${idx}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;">
                        <option value="parent">والدين العضو العامل</option>
                        <option value="special_needs">أبناء ذوي الاحتياجات الخاصة</option>
                        <option value="unmarried_daughter">بنات العضو غير المتزوجات</option>
                        <option value="sister">شقيقة العضو العامل</option>
                        <option value="stepchild">أبناء الزوج/الزوجة</option>
                        <option value="orphan">الطفل اليتيم</option>
                        <option value="disabled_sibling">شقيق العضو المعاق</option>
                        <option value="nanny">المربية</option>
                    </select>
                </div>
                <div><label style="font-size:11px;color:#6B7280;">صلة القرابة</label><input type="text" name="temp_relationship_${idx}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></div>
                <div><label style="font-size:11px;color:#6B7280;">تاريخ الانضمام</label><input type="date" name="temp_join_date_${idx}" value="${joinDate}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></div>
            </div>
            <div style="margin-top:8px;display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;">
                <div><label style="font-size:11px;color:#6B7280;">رسوم الإضافة</label><input type="number" name="temp_fee_${idx}" value="0" step="0.01" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></div>
                <div style="display:flex;align-items:end;">
                    <label style="font-size:11px;color:#6B7280;display:flex;align-items:center;gap:4px;"><input type="checkbox" name="temp_separate_fee_${idx}" value="1"> رسوم منفصلة</label>
                </div>
                <div>
                    <label style="font-size:11px;color:#6B7280;">طريقة الدفع</label>
                    <select name="temp_pay_method_${idx}" style="font-size:11px;padding:4px 8px;border:1px solid #D1D5DB;border-radius:4px;width:100%;"><option value="cash">نقدي</option><option value="check">شيك</option></select>
                </div>
            </div>
        </div>`;
}

// Subscriptions
let subIdx = 0;
function addSubscriptionRow(year, status, baseAmt, devFee, personType, personIndex, personName) {
    subIdx++;
    document.getElementById('subscriptionCount').value = subIdx;
    year = year || '';
    status = status || 'pending';
    baseAmt = baseAmt || '492.00';
    devFee = devFee || '35.00';
    personType = personType || 'member';
    personIndex = personIndex || 0;
    personName = personName || 'العضو';
    const total = (parseFloat(baseAmt) + parseFloat(devFee)).toFixed(2);

    document.getElementById('subscriptionRows').innerHTML += `
        <tr style="border-bottom:1px solid #F3F4F6;" id="subRow${subIdx}">
            <td style="padding:6px;">
                <span style="font-size:11px;color:#374151;white-space:nowrap;">${personName}</span>
                <input type="hidden" name="sub_person_type_${subIdx}" value="${personType}">
                <input type="hidden" name="sub_person_index_${subIdx}" value="${personIndex}">
                <input type="hidden" name="sub_person_name_${subIdx}" value="${personName}">
            </td>
            <td style="padding:6px;"><input type="text" name="sub_year_${subIdx}" value="${year}" placeholder="2023/2024" style="width:90px;padding:4px 6px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;direction:ltr;"></td>
            <td style="padding:6px;"><input type="number" name="sub_base_${subIdx}" value="${baseAmt}" step="0.01" style="width:70px;padding:4px 6px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></td>
            <td style="padding:6px;"><input type="number" name="sub_dev_fee_${subIdx}" value="${devFee}" step="0.01" style="width:60px;padding:4px 6px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></td>
            <td style="padding:6px;"><input type="number" name="sub_total_${subIdx}" value="${total}" step="0.01" style="width:70px;padding:4px 6px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></td>
            <td style="padding:6px;"><input type="number" name="sub_paid_${subIdx}" value="${status === 'paid' ? total : '0'}" step="0.01" style="width:70px;padding:4px 6px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></td>
            <td style="padding:6px;"><input type="number" name="sub_fine_${subIdx}" value="0" step="0.01" style="width:60px;padding:4px 6px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></td>
            <td style="padding:6px;text-align:center;">
                <select name="sub_status_${subIdx}" style="padding:4px 6px;border:1px solid #D1D5DB;border-radius:4px;font-size:11px;" onchange="this.closest('tr').style.background=this.value==='paid'?'#F0FDF4':this.value==='overdue'?'#FEF2F2':'#fff'">
                    <option value="pending" ${status==='pending'?'selected':''}>معلق</option>
                    <option value="paid" ${status==='paid'?'selected':''}>مدفوع</option>
                    <option value="overdue" ${status==='overdue'?'selected':''}>متأخر</option>
                    <option value="exempted" ${status==='exempted'?'selected':''}>معفى</option>
                </select>
            </td>
            <td style="padding:6px;"><input type="date" name="sub_paid_date_${subIdx}" style="padding:4px 6px;border:1px solid #D1D5DB;border-radius:4px;font-size:11px;width:110px;"></td>
            <td style="padding:6px;text-align:center;"><button type="button" onclick="document.getElementById('subRow${subIdx}').remove()" style="color:#DC2626;cursor:pointer;border:none;background:none;font-size:16px;">×</button></td>
        </tr>`;
}

function generateSubscriptionYears() {
    const joinDate = document.querySelector('[name=join_date]').value;
    if (!joinDate) { alert('حدد تاريخ الانضمام أولاً'); return; }

    document.getElementById('subscriptionRows').innerHTML = '';
    subIdx = 0;

    const joinYear = parseInt(joinDate.split('-')[0]);
    const currentYear = new Date().getFullYear();
    const memberName = document.querySelector('[name=full_name_ar]').value || 'العضو';

    // Member subscriptions
    for (let y = joinYear; y <= currentYear; y++) {
        const fy = y + '/' + (y + 1);
        const isPast = y < currentYear - 1;
        const status = isPast ? 'paid' : (y === currentYear - 1 ? 'overdue' : 'pending');
        addSubscriptionRow(fy, status, '492.00', '35.00', 'member', 0, memberName);
    }

    // Spouse subscriptions
    const spouseCount = parseInt(document.getElementById('spouseCount').value) || 0;
    for (let s = 1; s <= spouseCount; s++) {
        const spouseNameEl = document.querySelector(`[name=spouse_name_${s}]`);
        if (!spouseNameEl || !spouseNameEl.value) continue;
        const spouseName = spouseNameEl.value || ('زوجة #' + s);
        const spouseJoinEl = document.querySelector(`[name=spouse_join_date_${s}]`);
        const spouseJoinYear = spouseJoinEl && spouseJoinEl.value ? parseInt(spouseJoinEl.value.split('-')[0]) : joinYear;
        for (let y = spouseJoinYear; y <= currentYear; y++) {
            const fy = y + '/' + (y + 1);
            const isPast = y < currentYear - 1;
            const status = isPast ? 'paid' : (y === currentYear - 1 ? 'overdue' : 'pending');
            addSubscriptionRow(fy, status, '492.00', '35.00', 'spouse', s, spouseName);
        }
    }

    // Child subscriptions
    const childCount = parseInt(document.getElementById('childCount').value) || 0;
    for (let c = 1; c <= childCount; c++) {
        const childNameEl = document.querySelector(`[name=child_name_${c}]`);
        if (!childNameEl || !childNameEl.value) continue;
        const childName = childNameEl.value || ('ابن #' + c);
        const childJoinEl = document.querySelector(`[name=child_join_date_${c}]`);
        const childJoinYear = childJoinEl && childJoinEl.value ? parseInt(childJoinEl.value.split('-')[0]) : joinYear;
        for (let y = childJoinYear; y <= currentYear; y++) {
            const fy = y + '/' + (y + 1);
            const isPast = y < currentYear - 1;
            const status = isPast ? 'paid' : (y === currentYear - 1 ? 'overdue' : 'pending');
            addSubscriptionRow(fy, status, '222.00', '35.00', 'child', c, childName);
        }
    }

    // Temporary member subscriptions
    const tempCount = parseInt(document.getElementById('tempMemberCount').value) || 0;
    for (let t = 1; t <= tempCount; t++) {
        const tempNameEl = document.querySelector(`[name=temp_name_${t}]`);
        if (!tempNameEl || !tempNameEl.value) continue;
        const tempName = tempNameEl.value || ('مؤقت #' + t);
        const tempJoinEl = document.querySelector(`[name=temp_join_date_${t}]`);
        const tempJoinYear = tempJoinEl && tempJoinEl.value ? parseInt(tempJoinEl.value.split('-')[0]) : joinYear;
        for (let y = tempJoinYear; y <= currentYear; y++) {
            const fy = y + '/' + (y + 1);
            const isPast = y < currentYear - 1;
            const status = isPast ? 'paid' : (y === currentYear - 1 ? 'overdue' : 'pending');
            addSubscriptionRow(fy, status, '222.00', '35.00', 'temporary', t, tempName);
        }
    }
}

// Violations
let violationIdx = 0;
function addViolation() {
    violationIdx++;
    document.getElementById('violationCount').value = violationIdx;
    document.getElementById('violationsList').innerHTML += `
        <div style="padding:14px;background:#FEF2F2;border-radius:8px;border:1px solid #FECACA;margin-bottom:10px;" id="violationRow${violationIdx}">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;">
                <span style="font-size:13px;font-weight:600;color:#991B1B;">مخالفة #${violationIdx}</span>
                <button type="button" onclick="document.getElementById('violationRow${violationIdx}').remove()" style="padding:2px 8px;background:#fff;border:1px solid #FECACA;border-radius:4px;color:#DC2626;cursor:pointer;font-size:12px;">حذف</button>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;">
                <div><label style="font-size:11px;color:#6B7280;">تاريخ المخالفة</label><input type="date" name="violation_date_${violationIdx}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></div>
                <div><label style="font-size:11px;color:#6B7280;">الوصف *</label><input type="text" name="violation_desc_${violationIdx}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;" placeholder="وصف المخالفة"></div>
                <div><label style="font-size:11px;color:#6B7280;">ملاحظات/أدلة</label><input type="text" name="violation_evidence_${violationIdx}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></div>
            </div>
            <div style="margin-top:10px;display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:10px;">
                <div><label style="font-size:11px;color:#6B7280;">مبلغ الغرامة</label><input type="number" name="violation_fine_amount_${violationIdx}" value="1000" step="0.01" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></div>
                <div><label style="font-size:11px;color:#6B7280;">نوع العقوبة</label>
                    <select name="violation_penalty_type_${violationIdx}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;">
                        <option value="warning">إنذار</option>
                        <option value="caution">تنبيه</option>
                        <option value="fine" selected>غرامة مالية</option>
                        <option value="suspension">إيقاف مؤقت</option>
                        <option value="ban">حرمان</option>
                        <option value="termination">فصل</option>
                    </select>
                </div>
                <div><label style="font-size:11px;color:#6B7280;">حالة الغرامة</label>
                    <select name="violation_fine_status_${violationIdx}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;" onchange="toggleFinePayFields(${violationIdx}, this.value)">
                        <option value="imposed">مفروضة</option>
                        <option value="paid">مدفوعة</option>
                        <option value="waived">متنازل عنها</option>
                        <option value="appeal_pending">قيد الاستئناف</option>
                    </select>
                </div>
                <div><label style="font-size:11px;color:#6B7280;">تاريخ السداد</label><input type="date" name="violation_fine_paid_date_${violationIdx}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></div>
            </div>
            <div style="margin-top:8px;display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                <div><label style="font-size:11px;color:#6B7280;">بداية الإيقاف</label><input type="date" name="violation_suspension_from_${violationIdx}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></div>
                <div><label style="font-size:11px;color:#6B7280;">نهاية الإيقاف</label><input type="date" name="violation_suspension_to_${violationIdx}" class="form-input" style="width:100%;padding:6px 8px;border:1px solid #D1D5DB;border-radius:4px;font-size:12px;"></div>
            </div>
        </div>`;
}

function toggleFinePayFields(idx, status) {
    const dateField = document.querySelector(`[name=violation_fine_paid_date_${idx}]`);
    if (dateField) dateField.closest('div').style.opacity = status === 'paid' ? '1' : '0.4';
}

// Final Summary
function updateFinalSummary() {
    const name = document.querySelector('[name=full_name_ar]').value || '—';
    const joinDate = document.querySelector('[name=join_date]').value || '—';
    const membershipValue = parseFloat(document.querySelector('[name=membership_value]').value || 0);
    const method = document.getElementById('membershipPayMethod').value;
    const methodLabels = {cash:'نقدي كامل',check:'شيك',visa:'فيزا',bank_transfer:'تحويل بنكي',installment:'تقسيط'};
    const spouses = parseInt(document.getElementById('spouseCount').value) || 0;
    const children = parseInt(document.getElementById('childCount').value) || 0;
    const temps = parseInt(document.getElementById('tempMemberCount').value) || 0;
    const subs = parseInt(document.getElementById('subscriptionCount').value) || 0;
    const violations = parseInt(document.getElementById('violationCount').value) || 0;

    let html = `
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;">
            <div><strong>الاسم:</strong> ${name}</div>
            <div><strong>تاريخ الانضمام:</strong> ${joinDate}</div>
            <div><strong>قيمة العضوية:</strong> ${membershipValue.toLocaleString()} ج.م</div>
            <div><strong>طريقة السداد:</strong> ${methodLabels[method] || method}</div>
            <div><strong>الزوجات:</strong> ${spouses}</div>
            <div><strong>الأبناء:</strong> ${children}</div>
            <div><strong>أعضاء مؤقتون:</strong> ${temps}</div>
            <div><strong>اشتراكات سنوية:</strong> ${subs} سنة</div>
            <div><strong>مخالفات:</strong> ${violations}</div>
        </div>`;

    if (method === 'installment') {
        const months = document.getElementById('instMonths').value || '12';
        const down = parseFloat(document.getElementById('instDown').value || 0);
        const paidNums = document.getElementById('instPaidNumbers').value;
        const paidCount = paidNums ? paidNums.split(',').length : 0;
        html += `<div style="margin-top:8px;padding:8px;background:#fff;border-radius:6px;"><strong>خطة التقسيط:</strong> ${months} شهر — مقدم ${down.toLocaleString()} ج.م — أقساط مدفوعة: ${paidCount}/${months}</div>`;
    }

    document.getElementById('finalSummary').innerHTML = html;
}

// Form submit validation
document.getElementById('retroForm').addEventListener('submit', function(e) {
    var stepsToValidate = [1, 2, 3, 5];
    for (var i = 0; i < stepsToValidate.length; i++) {
        var s = stepsToValidate[i];
        if (!validateStep(s)) {
            e.preventDefault();
            currentStep = s;
            updateStepUI();
            window.scrollTo(0, 0);
            return;
        }
    }
});

// Clear highlights on input
document.getElementById('retroForm').addEventListener('input', function(e) {
    if (e.target.style.border && e.target.style.border.includes('solid')) {
        clearInvalid(e.target);
    }
});

// Init
updateStepUI();
</script>

<style>
.wizard-panel .card { transition: all 0.2s; }
.wizard-panel .card:hover { box-shadow: 0 4px 12px rgba(0,0,0,0.08); }
.btn-preset:hover { background: #EFF6FF !important; border-color: #2563EB !important; }
.val-hint { animation: valShake 0.3s ease; }
@keyframes valShake { 0%,100%{transform:translateX(0)} 25%{transform:translateX(-4px)} 75%{transform:translateX(4px)} }
</style>

<?php $__template->endSection(); ?>
