<?php
ob_start();
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true || !isset($_SESSION['user'])) {
    header('Location: login.php');
    exit;
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>لوحة التحكم | إدارة الديون</title>
    <link rel="stylesheet" href="css/cairo.css">
    <link rel="stylesheet" href="css/fontawesome/css/all.min.css">
    <link rel="stylesheet" href="css/style.css">
    <script src="js/auth.js?v=<?php echo time(); ?>"></script>
    <style>
        /* ===== DEBTS PAGE – LOCAL OVERRIDES ===== */

        /* Hero banner */
        .debts-hero {
            background: linear-gradient(135deg, #7c1d1d 0%, #b91c1c 50%, #dc2626 100%);
            border-radius: var(--radius-lg);
            padding: 28px 32px;
            margin-bottom: 24px;
            position: relative;
            overflow: hidden;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 20px;
        }
        .debts-hero::before {
            content: '';
            position: absolute;
            width: 280px; height: 280px;
            border-radius: 50%;
            background: rgba(255,255,255,0.04);
            top: -80px; left: -80px;
            pointer-events: none;
        }
        .debts-hero::after {
            content: '';
            position: absolute;
            width: 160px; height: 160px;
            border-radius: 50%;
            background: rgba(255,255,255,0.05);
            bottom: -40px; right: 200px;
            pointer-events: none;
        }
        .debts-hero-text h1 {
            color: #fff;
            font-size: 22px;
            font-weight: 800;
            margin-bottom: 6px;
        }
        .debts-hero-text p {
            color: rgba(255,255,255,0.8);
            font-size: 13px;
            max-width: 520px;
        }
        .debts-hero-icon {
            font-size: 60px;
            color: rgba(255,255,255,0.12);
            flex-shrink: 0;
            position: relative;
            z-index: 1;
        }

        /* ===== KPI CARDS ===== */
        .debts-kpi-row {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 16px;
            margin-bottom: 24px;
        }
        .kpi-card {
            background: var(--bg-card);
            border: 1px solid var(--border-color);
            border-radius: var(--radius-lg);
            padding: 20px 22px;
            display: flex;
            align-items: center;
            gap: 16px;
            box-shadow: var(--shadow-md);
            transition: var(--transition);
            position: relative;
            overflow: hidden;
        }
        .kpi-card::before {
            content: '';
            position: absolute;
            top: 0; right: 0;
            width: 4px; height: 100%;
            border-radius: 0 var(--radius-lg) var(--radius-lg) 0;
        }
        .kpi-card.danger::before  { background: var(--danger); }
        .kpi-card.primary::before { background: var(--primary); }
        .kpi-card.success::before { background: var(--success); }
        .kpi-card:hover { transform: translateY(-3px); box-shadow: var(--shadow-lg); }
        .kpi-icon {
            width: 52px; height: 52px;
            border-radius: 14px;
            display: flex; align-items: center; justify-content: center;
            font-size: 22px;
            flex-shrink: 0;
        }
        .kpi-card.danger  .kpi-icon { background: rgba(239,68,68,0.12); color: var(--danger); }
        .kpi-card.primary .kpi-icon { background: var(--primary-light); color: var(--primary); }
        .kpi-card.success .kpi-icon { background: var(--success-light); color: var(--success); }
        .kpi-value {
            font-size: 24px;
            font-weight: 800;
            line-height: 1.1;
            color: var(--text-primary);
        }
        .kpi-label {
            font-size: 12px;
            color: var(--text-secondary);
            margin-top: 4px;
        }

        /* ===== SPLIT LAYOUT ===== */
        .debts-split {
            display: grid;
            grid-template-columns: 1.1fr 1fr;
            gap: 20px;
            align-items: start;
        }
        @media (max-width: 1100px) {
            .debts-split { grid-template-columns: 1fr; }
            .debts-kpi-row { grid-template-columns: 1fr 1fr; }
        }

        /* ===== SEARCH BAR INSIDE PANEL ===== */
        .panel-search-bar {
            padding: 12px 20px;
            border-bottom: 1px solid var(--border-color);
            background: rgba(0,0,0,0.01);
        }
        body.dark-theme .panel-search-bar {
            background: rgba(255,255,255,0.01);
        }
        .panel-search-inner {
            display: flex;
            gap: 8px;
            align-items: center;
        }
        .panel-search-input-wrap {
            position: relative;
            flex: 1;
        }
        .panel-search-icon {
            position: absolute;
            right: 14px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--text-muted);
            font-size: 14px;
            pointer-events: none;
        }
        .panel-search-input {
            width: 100%;
            padding: 10px 40px 10px 14px;
            border: 1.5px solid var(--border-color);
            background: var(--bg-input);
            color: var(--text-primary);
            border-radius: var(--radius-md);
            font-family: var(--font-family);
            font-size: 13px;
            outline: none;
            transition: var(--transition);
        }
        .panel-search-input:focus {
            border-color: var(--primary);
            background: var(--bg-card);
            box-shadow: 0 0 0 3px rgba(59,130,246,0.12);
        }
        .panel-search-btn {
            padding: 10px 18px;
            border-radius: var(--radius-md);
            border: none;
            background: var(--gradient-primary);
            color: #fff;
            font-family: var(--font-family);
            font-size: 13px;
            font-weight: 700;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 6px;
            transition: var(--transition);
            white-space: nowrap;
            box-shadow: 0 2px 8px rgba(59,130,246,0.2);
        }
        .panel-search-btn:hover {
            box-shadow: 0 4px 14px rgba(59,130,246,0.35);
            transform: translateY(-1px);
        }
        .panel-search-clear {
            padding: 10px 12px;
            border-radius: var(--radius-md);
            border: 1.5px solid var(--border-color);
            background: var(--bg-input);
            color: var(--text-secondary);
            cursor: pointer;
            font-size: 13px;
            display: flex;
            align-items: center;
            gap: 6px;
            transition: var(--transition);
        }
        .panel-search-clear:hover {
            border-color: var(--danger);
            color: var(--danger);
            background: var(--danger-light);
        }
        .panel-results-info {
            padding: 6px 20px 8px;
            font-size: 12px;
            color: var(--text-muted);
            border-bottom: 1px solid var(--border-color);
            display: none;
        }
        .panel-results-info.visible { display: block; }
        .panel-results-info span { color: var(--primary); font-weight: 700; }
        .debtors-panel {
            background: var(--bg-card);
            border: 1px solid var(--border-color);
            border-radius: var(--radius-lg);
            box-shadow: var(--shadow-md);
            overflow: hidden;
        }
        .panel-header {
            padding: 18px 22px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            flex-wrap: wrap;
        }
        .panel-header h2 {
            font-size: 16px;
            font-weight: 700;
            color: var(--text-primary);
        }
        .panel-header p {
            font-size: 12px;
            color: var(--text-secondary);
            margin-top: 2px;
        }

        /* Debtors list */
        .debtors-list {
            display: flex;
            flex-direction: column;
        }
        .debtor-row {
            display: grid;
            grid-template-columns: auto 1fr auto auto;
            align-items: center;
            gap: 14px;
            padding: 14px 20px;
            border-bottom: 1px solid var(--border-color);
            cursor: pointer;
            transition: var(--transition);
            position: relative;
        }
        .debtor-row:last-child { border-bottom: none; }
        .debtor-row:hover {
            background: rgba(59,130,246,0.04);
        }
        .debtor-row.active {
            background: rgba(59,130,246,0.06);
            border-right: 3px solid var(--primary);
        }
        .debtor-avatar {
            width: 42px; height: 42px;
            border-radius: 50%;
            background: var(--gradient-primary);
            color: #fff;
            font-size: 14px;
            font-weight: 700;
            display: flex; align-items: center; justify-content: center;
            flex-shrink: 0;
        }
        .debtor-row.active .debtor-avatar {
            box-shadow: 0 0 0 3px rgba(59,130,246,0.3);
        }
        .debtor-row-info { display: flex; flex-direction: column; gap: 3px; }
        .debtor-row-name {
            font-size: 14px; font-weight: 700;
            color: var(--text-primary);
        }
        .debtor-row-phone {
            font-size: 12px; color: var(--text-secondary);
            display: flex; align-items: center; gap: 5px;
        }
        .debtor-row-balance { display: flex; flex-direction: column; align-items: flex-end; gap: 4px; }
        .balance-amount {
            font-size: 15px; font-weight: 800;
            direction: ltr; white-space: nowrap;
        }
        .balance-amount.negative { color: var(--danger); }
        .balance-amount.positive { color: var(--success); }
        .balance-badge {
            font-size: 10px; font-weight: 700;
            padding: 2px 8px; border-radius: 20px;
        }
        .balance-badge.negative { background: var(--danger-light); color: var(--danger); }
        .balance-badge.positive { background: var(--success-light); color: var(--success); }
        .debtor-row-actions {
            display: flex; gap: 6px;
            opacity: 0; transition: opacity 0.2s;
        }
        .debtor-row:hover .debtor-row-actions,
        .debtor-row.active .debtor-row-actions { opacity: 1; }
        .row-action-btn {
            width: 30px; height: 30px;
            border-radius: 8px;
            border: 1px solid var(--border-color);
            background: var(--bg-input);
            color: var(--text-secondary);
            cursor: pointer;
            display: flex; align-items: center; justify-content: center;
            font-size: 12px;
            transition: var(--transition);
        }
        .row-action-btn:hover { background: var(--primary); color: #fff; border-color: var(--primary); }
        .row-action-btn.del:hover { background: var(--danger); color: #fff; border-color: var(--danger); }

        /* empty state inside list */
        .debtor-empty {
            padding: 50px 20px;
            text-align: center;
            display: none;
            flex-direction: column;
            align-items: center;
            gap: 12px;
        }
        .debtor-empty .empty-icon {
            width: 70px; height: 70px;
            border-radius: 50%;
            background: rgba(220,38,38,0.08);
            color: #dc2626;
            font-size: 30px;
            display: flex; align-items: center; justify-content: center;
        }
        .debtor-empty h3 { font-size: 16px; font-weight: 700; }
        .debtor-empty p { font-size: 13px; color: var(--text-secondary); max-width: 240px; }

        /* ===== RIGHT PANEL: TRANSACTION TIMELINE ===== */
        .txn-panel {
            background: var(--bg-card);
            border: 1px solid var(--border-color);
            border-radius: var(--radius-lg);
            box-shadow: var(--shadow-md);
            overflow: hidden;
            display: flex; flex-direction: column;
        }
        .txn-empty-state {
            flex: 1;
            display: flex; flex-direction: column;
            align-items: center; justify-content: center;
            padding: 60px 24px;
            gap: 14px;
            text-align: center;
        }
        .txn-empty-icon {
            width: 80px; height: 80px;
            border-radius: 50%;
            background: rgba(59,130,246,0.08);
            color: var(--primary);
            font-size: 34px;
            display: flex; align-items: center; justify-content: center;
        }
        .txn-empty-state h3 { font-size: 17px; font-weight: 700; }
        .txn-empty-state p  { font-size: 13px; color: var(--text-secondary); max-width: 260px; }

        /* active debtor summary inside right panel header */
        .txn-debtor-info {
            display: flex; align-items: center; gap: 12px;
            flex: 1; min-width: 0;
        }
        .txn-debtor-avatar {
            width: 38px; height: 38px;
            border-radius: 50%;
            background: var(--gradient-primary);
            color: #fff; font-size: 13px; font-weight: 700;
            display: flex; align-items: center; justify-content: center;
            flex-shrink: 0;
        }
        .txn-debtor-name  { font-size: 14px; font-weight: 700; color: var(--text-primary); }
        .txn-debtor-phone { font-size: 12px; color: var(--text-secondary); margin-top: 2px; }

        /* Transaction timeline */
        .txn-timeline {
            display: flex; flex-direction: column;
            padding: 6px 20px 20px;
            overflow-y: auto;
            max-height: 520px;
        }
        .txn-item {
            display: flex; align-items: center;
            gap: 14px;
            padding: 14px 0;
            border-bottom: 1px solid var(--border-color);
            transition: var(--transition);
        }
        .txn-item:last-child { border-bottom: none; }
        .txn-item:hover { transform: translateX(-4px); }
        .txn-dot {
            width: 42px; height: 42px;
            border-radius: 50%;
            display: flex; align-items: center; justify-content: center;
            font-size: 16px; flex-shrink: 0;
        }
        .txn-dot.debt      { background: rgba(239,68,68,0.12); color: var(--danger); }
        .txn-dot.repayment { background: var(--success-light); color: var(--success); }
        .txn-body { flex: 1; display: flex; flex-direction: column; gap: 3px; }
        .txn-desc { font-size: 13px; font-weight: 600; color: var(--text-primary); }
        .txn-date { font-size: 11px; color: var(--text-secondary); display: flex; align-items: center; gap: 5px; }
        .txn-amount {
            font-size: 15px; font-weight: 800;
            direction: ltr; white-space: nowrap;
        }
        .txn-amount.debt      { color: var(--danger); }
        .txn-amount.repayment { color: var(--success); }
        .txn-del-btn {
            width: 30px; height: 30px; flex-shrink: 0;
            border-radius: 8px;
            border: 1px solid var(--border-color);
            background: var(--bg-input);
            color: var(--text-secondary);
            cursor: pointer;
            display: flex; align-items: center; justify-content: center;
            font-size: 12px;
            transition: var(--transition);
        }
        .txn-del-btn:hover { background: var(--danger); color: #fff; border-color: var(--danger); }
        .txn-pay-btn:hover { background: var(--success) !important; color: #fff !important; border-color: var(--success) !important; }

        /* ===== HISTORY MODAL STYLES ===== */
        .hist-modal-card {
            max-width: 680px !important;
            width: 92% !important;
            max-height: 90vh !important;
            display: flex !important;
            flex-direction: column !important;
            padding: 0 !important;
            overflow: hidden !important;
            border-radius: var(--radius-lg) !important;
        }
        .hist-modal-header {
            padding: 16px 20px;
            background: var(--bg-card);
            border-bottom: 1px solid var(--border-color);
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
        }
        .hist-debtor-info {
            display: flex;
            align-items: center;
            gap: 12px;
            flex: 1;
            min-width: 0;
        }
        .hist-toolbar {
            padding: 12px 20px;
            background: var(--bg-input);
            border-bottom: 1px solid var(--border-color);
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            flex-wrap: wrap;
        }
        .hist-body {
            padding: 16px 20px;
            overflow-y: auto;
            max-height: calc(85vh - 130px);
            flex: 1;
        }
        .txn-timeline {
            display: flex;
            flex-direction: column;
            gap: 8px;
            max-height: none !important;
            padding: 0 !important;
        }

        /* ===== MAIN DEBTS TABLE STYLES ===== */
        .debtors-cards-area {
            background: var(--bg-card);
            border: 1px solid var(--border-color);
            border-radius: var(--radius-lg);
            box-shadow: var(--shadow-md);
            overflow: hidden;
        }
        .table-responsive-wrapper {
            width: 100%;
            overflow-x: auto;
        }
        .main-debts-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 13px;
            direction: rtl;
            white-space: nowrap;
        }
        .main-debts-table thead tr {
            background: var(--bg-input);
            border-bottom: 2px solid var(--border-color);
        }
        .main-debts-table th {
            padding: 14px 16px;
            font-weight: 800;
            font-size: 12.5px;
            color: var(--text-secondary);
            text-align: center;
        }
        .main-debts-table th.th-align-right {
            text-align: right;
        }
        .main-debts-table td {
            padding: 12px 16px;
            border-bottom: 1px solid var(--border-color);
            vertical-align: middle;
        }
        .main-debts-table tbody tr {
            transition: var(--transition);
        }
        .main-debts-table tbody tr:hover {
            background: rgba(59,130,246,0.04);
        }
        .td-index {
            text-align: center;
            font-weight: 700;
            color: var(--text-secondary);
            font-size: 12px;
        }
        .td-cust-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .td-cust-avatar {
            width: 34px; height: 34px;
            border-radius: 50%;
            background: var(--gradient-primary);
            color: #fff;
            font-size: 12px; font-weight: 700;
            display: flex; align-items: center; justify-content: center;
            flex-shrink: 0;
        }
        .td-cust-name {
            font-weight: 700;
            color: var(--text-primary);
            font-size: 13.5px;
        }
        .td-cust-phone {
            font-size: 11px;
            color: var(--text-secondary);
            margin-top: 1px;
        }
        .form-num-badge {
            display: inline-flex;
            align-items: center;
            gap: 5px;
            padding: 4px 10px;
            border-radius: 6px;
            font-weight: 700;
            font-size: 12px;
            background: rgba(59,130,246,0.1);
            color: var(--primary);
            cursor: pointer;
            transition: var(--transition);
        }
        .form-num-badge:hover {
            background: var(--primary);
            color: #fff;
        }
        .form-num-badge.manual {
            background: rgba(107,114,128,0.1);
            color: var(--text-secondary);
            cursor: default;
        }
        .money-cell {
            text-align: center;
            font-weight: 800;
            font-size: 13.5px;
            direction: ltr;
        }
        .money-cell.total-form {
            color: var(--text-primary);
        }
        .money-cell.remain-form {
            color: var(--danger);
        }
        .money-cell.paid-form {
            color: var(--success);
        }
        .money-cell.cust-balance {
            color: #b91c1c;
            background: rgba(239,68,68,0.06);
            padding: 4px 10px;
            border-radius: 8px;
            display: inline-block;
        }
        .money-cell.cust-balance.zero {
            color: var(--success);
            background: var(--success-light);
        }
        .table-actions-cell {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
        }
    </style>
</head>
<body>
<div class="app-container">

    <!-- Sidebar -->
    <?php include 'includes/sidebar.php'; ?>

    <!-- Main Content -->
    <main class="main-content">

        <?php
        $pageTitle = "إدارة الديون";
        $pageIcon = "fa-file-invoice-dollar";
        include 'includes/header.php';
        ?>

        <div class="dashboard-body">

            <!-- Hero Banner -->
            <div class="debts-hero">
                <div class="debts-hero-text">
                    <h1>إدارة ومتابعة الديون والتحصيلات 🧾</h1>
                    <p>تابع أرصدة المدينين وإجمالي المبالغ المستحقة، وسجّل السحبيات ورفع الدفعات المالية بشكل فوري ودقيق.</p>
                </div>
                <i class="fa-solid fa-hand-holding-dollar debts-hero-icon"></i>
            </div>

            <!-- KPI Cards -->
            <div class="debts-kpi-row">
                <div class="kpi-card danger">
                    <div class="kpi-icon"><i class="fa-solid fa-file-invoice-dollar"></i></div>
                    <div>
                        <div class="kpi-value" id="stat-total-debts">0 د.ع</div>
                        <div class="kpi-label">إجمالي الديون المستحقة</div>
                    </div>
                </div>
                <div class="kpi-card primary">
                    <div class="kpi-icon"><i class="fa-solid fa-users"></i></div>
                    <div>
                        <div class="kpi-value" id="stat-active-debtors">0</div>
                        <div class="kpi-label">المدينين النشطين</div>
                    </div>
                </div>
                <div class="kpi-card success">
                    <div class="kpi-icon"><i class="fa-solid fa-circle-check"></i></div>
                    <div>
                        <div class="kpi-value" id="stat-total-repayments">0 د.ع</div>
                        <div class="kpi-label">تحصيل وتسديد الديون (استلام الديون السابقة)</div>
                    </div>
                </div>
            </div>

            <!-- Debtors Table Container -->
            <div class="debtors-cards-area">
                <div class="panel-header">
                    <div>
                        <h2><i class="fa-solid fa-table-list" style="color:var(--primary);margin-left:8px;"></i>سجل الديون والتحصيلات</h2>
                        <p>جدول شامل لديون الاستمارات المتبقية ورصيد كل زبون</p>
                    </div>
                    <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
                        <button class="btn" id="export-excel-btn" style="background:var(--bg-input);border:1px solid var(--border-color);color:var(--text-secondary);" onclick="exportDebtsToExcel()">
                            <i class="fa-solid fa-file-excel" style="color:#1f7244;font-size:15px;"></i> تصدير Excel
                        </button>
                        <button class="btn" id="print-all-debtors-btn" style="background:var(--bg-input);border:1px solid var(--border-color);color:var(--text-secondary);" onclick="printAllDebtors()">
                            <i class="fa-solid fa-print"></i> طباعة الكل
                        </button>
                        <button class="btn btn-primary" id="open-add-modal-btn">
                            <i class="fa-solid fa-user-plus"></i> إضافة مدين
                        </button>
                    </div>
                </div>

                <div class="panel-search-bar">
                    <div class="panel-search-inner" style="flex-wrap: wrap; gap: 10px; align-items: center;">
                        <div class="panel-search-input-wrap" style="min-width: 220px;">
                            <i class="fa-solid fa-magnifying-glass panel-search-icon"></i>
                            <input type="text" id="search-input" class="panel-search-input" placeholder="ابحث باسم الزبون، رقم الاستمارة، أو رقم الهاتف..." autocomplete="off" onkeydown="if(event.key==='Enter') doSearchDebts()">
                        </div>
                        <select id="type-filter" class="panel-search-input" style="width:160px;padding:10px 14px;cursor:pointer;" onchange="applyDebtorsFilter()">
                            <option value="all">كل الأنواع</option>
                            <option value="active_forms">استمارات غير مدفوعة</option>
                            <option value="paid_forms">استمارات مدفوعة</option>
                            <option value="manual_debts">ديون يدوية وسابقة</option>
                        </select>
                        <select id="date-preset-filter" class="panel-search-input" style="width:150px;padding:10px 14px;cursor:pointer;" onchange="onDatePresetChange()">
                            <option value="all">كل التواريخ</option>
                            <option value="today">اليوم</option>
                            <option value="yesterday">الأمس</option>
                            <option value="this_week">هذا الأسبوع</option>
                            <option value="this_month">هذا الشهر</option>
                            <option value="custom">مخصص (فترة زمنية)</option>
                        </select>
                        <div id="custom-date-container" style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;">
                            <div style="display:flex;align-items:center;gap:4px;">
                                <span style="font-size:12px;color:var(--text-secondary);font-weight:700;">من:</span>
                                <input type="date" id="date-from" class="panel-search-input" style="width:145px;padding:8px 10px;cursor:pointer;" onchange="onCustomDateChange()">
                            </div>
                            <div style="display:flex;align-items:center;gap:4px;">
                                <span style="font-size:12px;color:var(--text-secondary);font-weight:700;">إلى:</span>
                                <input type="date" id="date-to" class="panel-search-input" style="width:145px;padding:8px 10px;cursor:pointer;" onchange="onCustomDateChange()">
                            </div>
                        </div>
                        <button class="panel-search-btn" id="search-btn" onclick="doSearchDebts()"><i class="fa-solid fa-search"></i> بحث</button>
                        <button class="panel-search-clear" id="search-clear-btn" title="مسح البحث والتواريخ" onclick="clearSearchDebts()"><i class="fa-solid fa-xmark"></i></button>
                    </div>
                </div>
                <div class="panel-results-info" id="panel-results-info">
                    تم إيجاد <span id="panel-results-count">0</span> نتيجة
                </div>

                <!-- Debts Table -->
                <div class="table-responsive-wrapper" id="debtors-table-container">
                    <table class="main-debts-table">
                        <thead>
                            <tr>
                                <th style="width:45px;text-align:center;">ت</th>
                                <th class="th-align-right">اسم الزبون</th>
                                <th style="text-align:center;">رقم الاستمارة (الحسبة)</th>
                                <th style="text-align:center;">تاريخ الاستمارة (الحسبة)</th>
                                <th style="text-align:center;">المبلغ الكلي للاستمارة</th>
                                <th style="text-align:center;">مبلغ المتبقي للاستمارة</th>
                                <th style="text-align:center;">مبلغ المتبقي للسجل</th>
                                <th style="width:220px;text-align:center;">الإجراءات</th>
                            </tr>
                        </thead>
                        <tbody id="debtors-table-body">
                            <!-- Populated dynamically via JS -->
                        </tbody>
                    </table>
                </div>

                <div class="debtor-empty" id="empty-state-view">
                    <div class="empty-icon"><i class="fa-solid fa-users-slash"></i></div>
                    <h3>لا توجد ديون مسجلة</h3>
                    <p>ابدأ بإضافة أول مدين أو ابحث عن اسم مدين آخر.</p>
                    <button class="btn btn-primary" id="empty-state-add-btn"><i class="fa-solid fa-plus"></i> إضافة مدين</button>
                </div>
            </div>

        </div><!-- /.dashboard-body -->
    </main>
</div>

<!-- ===== MODAL: Transaction History ===== -->
<div class="modal-overlay" id="history-modal">
    <div class="modal-card hist-modal-card">
        <div class="hist-modal-header">
            <div class="hist-debtor-info">
                <div class="dc-avatar" id="hist-avatar" style="width:42px;height:42px;border-radius:50%;background:var(--gradient-primary);color:#fff;font-weight:700;display:flex;align-items:center;justify-content:center;font-size:14px;flex-shrink:0;">م</div>
                <div style="flex:1;min-width:0;">
                    <div style="font-size:15px;font-weight:800;color:var(--text-primary);" id="hist-name">—</div>
                    <div style="font-size:12px;color:var(--text-secondary);margin-top:3px;display:flex;align-items:center;gap:5px;" id="hist-phone">—</div>
                </div>
                <div class="hist-balance-pill negative" id="hist-balance" style="padding:6px 14px;border-radius:20px;font-weight:800;font-size:14px;">0</div>
            </div>
            <button class="modal-close-btn" id="close-history-modal-btn">&times;</button>
        </div>
        <div class="hist-toolbar">
            <button class="btn btn-primary" id="hist-add-tx-btn" style="font-size:13px;padding:8px 18px;">
                <i class="fa-solid fa-plus-circle"></i> تسجيل دين / سداد
            </button>
            <select id="hist-txn-filter" class="panel-search-input" style="width:200px;padding:8px 12px;font-size:12px;cursor:pointer;border-radius:var(--radius-sm);" onchange="filterAndRenderTransactions()">
                <option value="all" selected>كل الحركات التفصيلية</option>
                <option value="unpaid_forms">الاستمارات المستحقة فقط</option>
                <option value="paid_forms">استمارات مدفوعة بالكامل</option>
                <option value="manual_debts">ديون وسدادات يدوية</option>
            </select>
        </div>
        <div class="hist-body">
            <div class="txn-timeline" id="hist-txn-feed"></div>
            <div id="hist-empty" style="padding:40px 20px;text-align:center;color:var(--text-secondary);font-size:13px;display:none;">
                <i class="fa-solid fa-file-invoice" style="font-size:28px;color:var(--text-muted);margin-bottom:10px;display:block;"></i>
                لا توجد حركات مسجلة لهذا المدين.
            </div>
        </div>
    </div>
</div>

<!-- ===== MODAL: Add / Edit Debtor ===== -->
<div class="modal-overlay" id="debtor-modal">
    <div class="modal-card">
        <div class="modal-header">
            <h3 id="modal-title">إضافة مدين جديد</h3>
            <button class="modal-close-btn" id="close-debtor-modal-btn">&times;</button>
        </div>
        <form id="debtor-form" novalidate>
            <input type="hidden" id="debtor-id">
            <div class="modal-body">
                <!-- Customer Selector Search Field & Autocomplete -->
                <div class="form-group" id="customer-select-group" style="position:relative;">
                    <label for="debtor-customer-search">اختيار زبون / عميل مسجل</label>
                    <div class="input-wrapper" style="position:relative;">
                        <i class="fa-solid fa-users input-icon"></i>
                        <input type="text" id="debtor-customer-search" placeholder="اكتب للبحث باسم الزبون المسجل أو اختره من المقترحات..." autocomplete="off" style="width:100%;padding:12px 48px 12px 36px;border:1px solid var(--border-color);background:var(--bg-input);color:var(--text-primary);border-radius:var(--radius-md);font-family:var(--font-family);outline:none;font-size:14px;transition:var(--transition);">
                        <i class="fa-solid fa-chevron-down" id="toggle-customer-dropdown-btn" style="position:absolute; left:14px; top:50%; transform:translateY(-50%); color:var(--text-muted); cursor:pointer; font-size:12px;" title="عرض كافة الزبائن المسجلين"></i>
                    </div>
                    <select id="debtor-customer-select" style="display:none;"></select>
                    <div id="customer-suggestions-dropdown" class="autocomplete-suggestions-list" style="position:absolute; top:100%; right:0; left:0; z-index:1050; background:var(--bg-card); border:1.5px solid var(--border-color); border-radius:var(--radius-md); box-shadow:var(--shadow-md); max-height:220px; overflow-y:auto; display:none; margin-top:4px;"></div>
                </div>

                <!-- Debtor Name Input -->
                <div class="form-group">
                    <label for="debtor-name">اسم المدين <span class="required">*</span></label>
                    <div class="input-wrapper">
                        <i class="fa-solid fa-user-pen input-icon"></i>
                        <input type="text" id="debtor-name" list="customers-datalist" placeholder="اختر من القائمة أعلاه أو أدخل الاسم..." required minlength="3" autocomplete="off">
                        <datalist id="customers-datalist"></datalist>
                    </div>
                    <span class="error-msg" id="debtor-name-error">يرجى إدخال اسم صحيح (3 أحرف على الأقل)</span>
                </div>

                <!-- Amount Field (المبلغ الذي عليه) -->
                <div class="form-group" id="debtor-amount-group">
                    <label for="debtor-amount">المبلغ الذي عليه (د.ع)</label>
                    <div class="input-wrapper">
                        <i class="fa-solid fa-money-bill-wave input-icon"></i>
                        <input type="text" inputmode="numeric" id="debtor-amount" placeholder="10,000,000" autocomplete="off">
                    </div>
                    <span class="error-msg" id="debtor-amount-error" style="display:none;">يرجى إدخال مبلغ صحيح</span>
                    <span style="font-size: 11.5px; color: var(--text-secondary); margin-top: 4px; display: block;">أدخل مبلغ الدين المطلوب سداده من قبل هذا الزبون</span>
                </div>

                <div class="form-group" style="display:none;">
                    <label for="debtor-phone">رقم الهاتف</label>
                    <div class="input-wrapper">
                        <i class="fa-solid fa-phone input-icon"></i>
                        <input type="text" id="debtor-phone" placeholder="07xxxxxxxxx">
                    </div>
                    <span class="error-msg" id="debtor-phone-error">يرجى إدخال رقم هاتف صحيح</span>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" id="cancel-debtor-modal-btn">إلغاء</button>
                <button type="submit" class="btn btn-primary" id="save-debtor-btn">
                    <i class="fa-solid fa-save"></i> حفظ البيانات
                </button>
            </div>
        </form>
    </div>
</div>

<!-- ===== MODAL: Add Transaction ===== -->
<div class="modal-overlay" id="transaction-modal">
    <div class="modal-card">
        <div class="modal-header">
            <h3 id="tx-modal-title">تسجيل حركة دين / سداد</h3>
            <button class="modal-close-btn" id="close-tx-modal-btn">&times;</button>
        </div>
        <form id="transaction-form" novalidate>
            <div class="modal-body">
                <div class="form-group">
                    <label for="tx-type">نوع العملية <span class="required">*</span></label>
                    <div class="input-wrapper">
                        <i class="fa-solid fa-circle-nodes input-icon"></i>
                        <select id="tx-type" required style="width:100%;padding:12px 48px 12px 16px;border:1px solid var(--border-color);background:var(--bg-input);color:var(--text-primary);border-radius:var(--radius-md);font-family:var(--font-family);outline:none;">
                            <option value="debt" selected>سحب دين جديد (إضافة دين)</option>
                            <option value="repayment">سداد دفعة (تحصيل دين)</option>
                        </select>
                    </div>
                </div>
                <div class="form-group" style="display:none;">
                    <label for="tx-safe-id">خزنة المعاملة</label>
                    <div class="input-wrapper">
                        <i class="fa-solid fa-vault input-icon"></i>
                        <select id="tx-safe-id" style="width:100%;padding:12px 48px 12px 16px;border:1px solid var(--border-color);background:var(--bg-input);color:var(--text-primary);border-radius:var(--radius-md);font-family:var(--font-family);outline:none;">
                            <!-- Will be populated with safes -->
                        </select>
                    </div>
                    <span class="error-msg" id="tx-safe-error" style="display:none;color:var(--danger);font-size:11px;">يرجى اختيار خزنة صالحة المعاملة</span>
                </div>
                <div class="form-group">
                    <label for="tx-description">البيان <span class="required">*</span></label>
                    <div class="input-wrapper">
                        <i class="fa-solid fa-file-signature input-icon"></i>
                        <input type="text" id="tx-description" placeholder="وصف العملية..." required minlength="3">
                    </div>
                    <span class="error-msg" id="tx-description-error">يرجى إدخال بيان صحيح (3 أحرف على الأقل)</span>
                </div>
                <div class="form-group">
                    <label for="tx-date">تاريخ الحركة <span class="required">*</span></label>
                    <div class="input-wrapper">
                        <i class="fa-solid fa-calendar input-icon"></i>
                        <input type="date" id="tx-date" required>
                    </div>
                    <span class="error-msg" id="tx-date-error">يرجى اختيار تاريخ صالح</span>
                </div>
                <div class="form-group">
                    <label for="tx-amount">المبلغ (د.ع) <span class="required">*</span></label>
                    <div class="input-wrapper">
                        <i class="fa-solid fa-money-bill input-icon"></i>
                        <input type="text" inputmode="numeric" id="tx-amount" placeholder="10,000,000" autocomplete="off" required>
                    </div>
                    <span class="error-msg" id="tx-amount-error">يرجى إدخال مبلغ أكبر من الصفر</span>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" id="cancel-tx-modal-btn">إلغاء</button>
                <button type="submit" class="btn btn-primary" id="save-tx-btn">
                    <i class="fa-solid fa-save"></i> حفظ الحركة
                </button>
            </div>
        </form>
    </div>
</div>

<!-- ===== MODAL: Pay Form (Full or Partial) ===== -->
<div class="modal-overlay" id="pay-form-modal">
    <div class="modal-card" style="max-width:650px; width:95%;">
        <div class="modal-header" style="padding: 14px 20px;">
            <h3 id="pay-form-modal-title"><i class="fa-solid fa-money-bill-wave" style="color:var(--success);margin-left:6px;"></i> تسديد الاستمارة / دفعة جزئية</h3>
            <button class="modal-close-btn" id="close-pay-form-modal-btn">&times;</button>
        </div>
        <div class="modal-body" style="padding: 16px 20px;">
            <div style="background:var(--bg-input);border:1px solid var(--border-color);border-radius:var(--radius-md);padding:10px 16px;margin-bottom:14px;display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;">
                <div style="display:flex;align-items:center;gap:8px;">
                    <span style="font-size:12px;color:var(--text-secondary);">الاستمارة / الحساب:</span>
                    <span id="pay-form-id-label" style="font-weight:800;color:var(--text-primary);font-size:13.5px;">—</span>
                </div>
                <div style="display:flex;align-items:center;gap:8px;">
                    <span style="font-size:12px;color:var(--text-secondary);">المبلغ المتبقي المستحق:</span>
                    <span id="pay-form-amount-label" style="font-weight:800;color:var(--danger);font-size:16px;direction:ltr;">—</span>
                </div>
            </div>
            <input type="hidden" id="pay-form-id-input">
            <input type="hidden" id="pay-form-max-amount-input">
            
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px 16px;">
                <div class="form-group" style="margin-bottom:0;">
                    <label for="pay-form-type-select">نوع السداد</label>
                    <div class="input-wrapper">
                        <i class="fa-solid fa-calculator input-icon"></i>
                        <select id="pay-form-type-select" style="width:100%;padding:10px 40px 10px 14px;border:1px solid var(--border-color);background:var(--bg-input);color:var(--text-primary);border-radius:var(--radius-md);font-family:var(--font-family);outline:none;">
                            <option value="full" selected>سداد كامل المتبقي</option>
                            <option value="partial">تسديد دفعة جزئية</option>
                        </select>
                    </div>
                </div>

                <div class="form-group" style="margin-bottom:0;">
                    <label for="pay-form-pay-amount">المبلغ المراد تسديده (د.ع) <span class="required">*</span></label>
                    <div class="input-wrapper">
                        <i class="fa-solid fa-money-bill-wave input-icon"></i>
                        <input type="text" inputmode="numeric" id="pay-form-pay-amount" placeholder="10,000,000" autocomplete="off" required style="padding:10px 40px 10px 14px;">
                    </div>
                    <span class="error-msg" id="pay-form-amount-error" style="display:none;color:var(--danger);font-size:11px;">يرجى إدخال مبلغ تسديد صحيح أكبر من الصفر</span>
                </div>

                <div class="form-group" style="margin-bottom:0;">
                    <label for="pay-form-safe-select">الخزنة / الصندوق <span class="required">*</span></label>
                    <div class="input-wrapper">
                        <i class="fa-solid fa-vault input-icon"></i>
                        <select id="pay-form-safe-select" style="width:100%;padding:10px 40px 10px 14px;border:1px solid var(--border-color);background:var(--bg-input);color:var(--text-primary);border-radius:var(--radius-md);font-family:var(--font-family);outline:none;">
                            <!-- populated by JS -->
                        </select>
                    </div>
                </div>

                <div class="form-group" style="margin-bottom:0;">
                    <label for="pay-form-date-input">تاريخ السداد</label>
                    <div class="input-wrapper">
                        <i class="fa-solid fa-calendar input-icon"></i>
                        <input type="date" id="pay-form-date-input" style="padding:10px 40px 10px 14px;">
                    </div>
                </div>

                <div class="form-group" style="grid-column: span 2; margin-bottom:0;">
                    <label for="pay-form-desc-input">ملاحظات / البيان</label>
                    <div class="input-wrapper">
                        <i class="fa-solid fa-file-signature input-icon"></i>
                        <input type="text" id="pay-form-desc-input" placeholder="ملاحظات تظهر في سجل الحركة..." style="padding:10px 40px 10px 14px;">
                    </div>
                </div>
            </div>
        </div>
        <div class="modal-footer" style="padding: 12px 20px;">
            <button type="button" class="btn btn-secondary" id="cancel-pay-form-btn">إلغاء</button>
            <button type="button" class="btn btn-success" id="confirm-pay-form-btn">
                <i class="fa-solid fa-circle-check"></i> تأكيد التسديد
            </button>
        </div>
    </div>
</div>

<!-- ===== MODAL: Delete Confirmation ===== -->

<div class="modal-overlay" id="delete-confirm-modal">
    <div class="modal-card modal-confirm">
        <div class="modal-body text-center">
            <div class="confirm-icon">
                <i class="fa-solid fa-circle-exclamation text-danger"></i>
            </div>
            <h3 id="delete-title">تأكيد الحذف</h3>
            <p id="delete-desc">هل أنت متأكد من رغبتك في حذف هذا العنصر؟</p>
            <p class="text-danger text-sm" style="font-weight:700;margin-top:8px;">هذا الإجراء نهائي ولا يمكن التراجع عنه.</p>
        </div>
        <div class="modal-footer justify-center">
            <button type="button" class="btn btn-secondary" id="cancel-delete-btn">تراجع</button>
            <button type="button" class="btn btn-danger" id="confirm-delete-btn">
                <i class="fa-solid fa-trash-can"></i> نعم، احذف
            </button>
        </div>
    </div>
</div>

<!-- Toast -->
<div class="toast-container" id="toast-container"></div>

<script src="js/debts.js?v=<?php echo time(); ?>"></script>
</body>
</html>

