<!-- TAB 2: INSTALLMENTS & DEBTS -->
    <div class="tab-pane fade <?= $activeTab=='debts'?'show active':'' ?>" id="debts" role="tabpanel">
        
        <div class="d-flex justify-content-between align-items-center mb-4 animate-slide-up delay-1">
            <h4 class="fw-bold mb-0">نظام الأقساط الذكي</h4>
            <button class="btn btn-primary btn-premium shadow-sm" data-bs-toggle="modal" data-bs-target="#newInstallmentModal"><i class="fa-solid fa-cart-plus"></i> منتج قسط جديد</button>
        </div>
        
        <div class="row mb-5 pb-4 border-bottom animate-slide-up delay-2">
            <?php 
            $installmentsModalsHtml = '';
            if(empty($installments)) echo '<div class="col-12 text-center text-muted my-4"><i class="fa-solid fa-box-open fs-1 align-middle mb-3 opacity-50"></i><p>لا يوجد أقساط نشطة حالياً.</p></div>';
            foreach($installments as $ins): 
                $paidJson = json_decode($ins->paid_months_json ?? '[]', true);
                if(!is_array($paidJson)) $paidJson = [];
                $paidCount = count($paidJson);
                $percent = ($ins->total_months > 0) ? ($paidCount / $ins->total_months) * 100 : 0;
                $isArchived = ($paidCount >= $ins->total_months);
                if($isArchived) continue; // Keep grid clean
            ?>
            <div class="col-md-4 mb-4">
                <div class="card card-saas h-100 position-relative pb-4">
                    <div class="position-absolute top-0 end-0 m-3">
                         <div class="dropdown">
                            <button class="btn btn-sm btn-light text-secondary rounded-circle" data-bs-toggle="dropdown"><i class="fa-solid fa-ellipsis-vertical"></i></button>
                            <ul class="dropdown-menu shadow-sm">
                                <li><a class="dropdown-item" href="<?= BASE_URL ?>/finance/edit/finance_installments/<?= $ins->id ?>"><i class="fa-solid fa-pen text-primary me-2"></i> تعديل</a></li>
                                <li><a class="dropdown-item text-danger" href="<?= BASE_URL ?>/finance/delete/finance_installments/<?= $ins->id ?>" onclick="return confirm('متأكد من الحذف؟');"><i class="fa-solid fa-trash me-2"></i> حذف</a></li>
                            </ul>
                        </div>
                    </div>
                    <div class="card-body text-center mt-3" style="cursor: pointer;" data-bs-toggle="modal" data-bs-target="#viewInstallment<?= $ins->id ?>">
                        <div class="d-inline-flex bg-primary-subtle text-primary rounded-circle p-3 mb-3 fs-3 shadow-sm" style="width: 70px; height: 70px; justify-content:center; align-items:center;">
                            <i class="fa-solid <?= htmlspecialchars($ins->icon) ?>"></i>
                        </div>
                        <h5 class="fw-bold text-dark mb-1"><?= htmlspecialchars($ins->name) ?></h5>
                        <div class="badge bg-light text-dark mb-4 border"><?= number_format($ins->monthly_amount) ?> ج.م / شهر</div>
                        
                        <div class="px-3">
                            <div class="d-flex justify-content-between mb-1 fs-6">
                                <span class="text-success fw-bold"><i class="fa-solid fa-check-circle"></i> دُفع <?= $paidCount ?></span>
                                <span class="text-muted">متبقي <?= $ins->total_months - $paidCount ?></span>
                            </div>
                            <div class="progress rounded-pill bg-light" style="height: 12px; box-shadow: inset 0 1px 3px rgba(0,0,0,.1);">
                                <div class="progress-bar bg-primary progress-bar-striped progress-bar-animated" style="width: <?= $percent ?>%"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Modal logic internally created for each active installment for immediate clean UI state logic -->
            <?php ob_start(); ?>
            <div class="modal fade" id="viewInstallment<?= $ins->id ?>" tabindex="-1">
                <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
                    <div class="modal-content border-0 shadow-lg">
                        <div class="modal-header bg-light border-0">
                            <h5 class="modal-title fw-bold text-dark"><i class="fa-solid <?= htmlspecialchars($ins->icon) ?> text-primary me-2"></i> جدول سداد: <?= htmlspecialchars($ins->name) ?></h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body p-4 bg-white">
                            <form action="<?= BASE_URL ?>/finance/updateInstallmentPaidState" method="POST" id="formIns<?= $ins->id ?>">
                                <?= csrf_field() ?>
                                <input type="hidden" name="installment_id" value="<?= $ins->id ?>">
                                <input type="hidden" name="paid_json" id="jsonStr<?= $ins->id ?>" value="<?= htmlspecialchars($ins->paid_months_json) ?>">
                                
                                <div class="timeline-container">
                                    <?php 
                                    $startDate = new DateTime($ins->start_date);
                                    $today = new DateTime();
                                    
                                    for ($i = 1; $i <= $ins->total_months; $i++):
                                        $isPaid = in_array($i, $paidJson);
                                        $dueDate = clone $startDate;
                                        $dueDate->modify('+' . ($i - 1) . ' months');
                                        
                                        $isLate = (!$isPaid && $dueDate < $today && $dueDate->format('Y-m') !== $today->format('Y-m'));
                                        
                                        $badgeStatus = $isPaid ? '<span class="badge bg-success">تم السداد</span>' : ($isLate ? '<span class="badge bg-danger">متأخر!</span>' : '<span class="badge bg-light border text-dark">مستحق</span>');
                                    ?>
                                        <div class="timeline-item <?= $isPaid ? 'paid' : '' ?> <?= $isLate ? 'late' : '' ?> d-flex justify-content-between align-items-center">
                                            <div>
                                                <div class="fw-bold mb-1 text-dark">الشهر <?= $i ?> <small class="text-muted ms-2">(<?= $dueDate->format('M Y') ?>)</small></div>
                                                <div class="text-muted"><?= number_format($ins->monthly_amount) ?> ج.م <?= $badgeStatus ?></div>
                                            </div>
                                            <div class="form-check form-switch fs-4">
                                                <input class="form-check-input check-month-ins-<?= $ins->id ?>" type="checkbox" role="switch" data-month="<?= $i ?>" <?= $isPaid ? 'checked' : '' ?> onchange="updatePaidJson(<?= $ins->id ?>)">
                                            </div>
                                        </div>
                                    <?php endfor; ?>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer bg-light border-0">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إغلاق</button>
                            <button type="button" class="btn btn-primary fw-bold" onclick="document.getElementById('formIns<?= $ins->id ?>').submit();">حفظ تقدم السداد <i class="fa-solid fa-circle-check ms-1"></i></button>
                        </div>
                    </div>
                </div>
            </div>
            </div>
            <?php 
                $installmentsModalsHtml .= ob_get_clean();
            endforeach; 
            ?>
        </div>
        <?= $installmentsModalsHtml ?>

        <div class="d-flex justify-content-between align-items-center mb-4 mt-5 animate-slide-up delay-3">
            <h4 class="fw-bold mb-0">سجل الديون والسلفيات</h4>
            <button class="btn btn-danger btn-premium shadow-sm" data-bs-toggle="modal" data-bs-target="#debtModal"><i class="fa-solid fa-handshake"></i> تسجيل دين</button>
        </div>

        <div class="card card-saas animate-slide-up delay-4">
            <div class="card-body p-0">
                <table class="table table-hover align-middle mb-0">
                    <thead class="table-light text-muted fw-bold">
                        <tr>
                            <th>الطرف الآخر</th>
                            <th>النوع</th>
                            <th>المبلغ</th>
                            <th>تاريخ الاستحقاق</th>
                            <th class="text-end">الإجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($debts as $debt): ?>
                        <tr class="<?= $debt->status == 'paid' ? 'opacity-50 text-decoration-line-through text-muted' : '' ?>">
                            <td class="fw-bold"><i class="fa-regular fa-user me-2 text-secondary"></i> <?= htmlspecialchars($debt->person_name) ?></td>
                            <td><?= $debt->type == 'owed' ? '<span class="badge bg-danger-subtle text-danger">دين عليّ</span>' : '<span class="badge bg-success-subtle text-success">ديون لي</span>' ?></td>
                            <td class="fw-bold fs-5">
                                <?= number_format($debt->amount) ?>
                                <?php if(isset($debt->paid_amount) && $debt->paid_amount > 0): ?>
                                    <div class="small fw-normal text-success mt-1"><i class="fa-solid fa-arrow-down fa-sm"></i> مسدد: <?= number_format($debt->paid_amount) ?></div>
                                <?php endif; ?>
                            </td>
                            <td class="text-muted"><?= $debt->due_date ?? 'غير محدد' ?></td>
                            <td class="text-end">
                                <?php if($debt->status == 'pending'): ?>
                                <button type="button" class="btn btn-sm btn-outline-primary rounded-pill fw-bold me-1" onclick="openDebtPay(<?= $debt->id ?>, <?= $debt->amount - ($debt->paid_amount ?? 0) ?>)">سداد دفعة</button>
                                <a href="<?= BASE_URL ?>/finance/toggleDebt/<?= $debt->id ?>" class="btn btn-sm btn-success rounded-pill fw-bold text-white me-2">إغلاق</a>
                                <?php endif; ?>
                                <a href="<?= BASE_URL ?>/finance/edit/finance_debts/<?= $debt->id ?>" class="btn btn-sm text-secondary"><i class="fa-solid fa-pen"></i></a>
                                <a href="<?= BASE_URL ?>/finance/delete/finance_debts/<?= $debt->id ?>" class="btn btn-sm text-danger" onclick="return confirm('تأكيد الحذف؟');"><i class="fa-solid fa-trash"></i></a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    
