// Business Logic and UI Interactions for Debts/Credits Management Page
// ✅ Connected to MySQL Database via api/debts.php

// App State
let state = {
debtors: [],
debtEntries: [],
filteredDebtors: [],
activeDebtorId: null,
searchTerm: "",
deleteTargetType: null, // 'debtor' or 'entry'
};

function getOrgName() {
    let settings = {};
    const localSettings = localStorage.getItem("dashboard_settings") || localStorage.getItem("system_settings");
    if (localSettings) {
        try { settings = JSON.parse(localSettings); } catch(e){}
    }
    return settings.orgName || settings.org_name || settings.companyName || "مكتب الحاج أمجد سهل عبدالامير";
}

// -------------------------------------------------------------
// 2. DOM Elements Selection
// -------------------------------------------------------------
const dom = {
// Containers
debtorsTableBody:       document.getElementById("debtors-table-body"),
debtorsTableContainer:  document.getElementById("debtors-table-container"),
debtTransactionsFeed:   document.getElementById("hist-txn-feed"),

// Empty States
emptyStateDebtors:      document.getElementById("empty-state-view"),
emptyStateTransactions: document.getElementById("hist-empty"),

// Search
searchInput:       document.getElementById("search-input"),
searchBtn:         document.getElementById("search-btn"),
searchClearBtn:    document.getElementById("search-clear-btn"),
panelResultsInfo:  document.getElementById("panel-results-info"),
panelResultsCount: document.getElementById("panel-results-count"),

// Stats
statTotalDebts:      document.getElementById("stat-total-debts"),
statActiveDebtors:   document.getElementById("stat-active-debtors"),
statTotalRepayments: document.getElementById("stat-total-repayments"),

// History Modal
historyModal:  document.getElementById("history-modal"),
histAvatar:    document.getElementById("hist-avatar"),
histName:      document.getElementById("hist-name"),
histPhone:     document.getElementById("hist-phone"),
histBalance:   document.getElementById("hist-balance"),
histAddTxBtn:  document.getElementById("hist-add-tx-btn"),

// Modals
debtorModal:        document.getElementById("debtor-modal"),
transactionModal:   document.getElementById("transaction-modal"),
deleteConfirmModal: document.getElementById("delete-confirm-modal"),

// Debtor Form
debtorForm:         document.getElementById("debtor-form"),
debtorIdInput:      document.getElementById("debtor-id"),
debtorNameInput:    document.getElementById("debtor-name"),
debtorPhoneInput:   document.getElementById("debtor-phone"),
debtorAmountInput:  document.getElementById("debtor-amount"),
debtorCustomerSelect: document.getElementById("debtor-customer-select"),
customersDatalist:   document.getElementById("customers-datalist"),
debtorAmountGroup:  document.getElementById("debtor-amount-group"),
customerSelectGroup: document.getElementById("customer-select-group"),
debtorNameError:    document.getElementById("debtor-name-error"),
debtorPhoneError:   document.getElementById("debtor-phone-error"),
debtorModalTitle:   document.getElementById("modal-title"),

// Transaction Form
transactionForm:    document.getElementById("transaction-form"),
txTypeSelect:       document.getElementById("tx-type"),
txSafeIdSelect:     document.getElementById("tx-safe-id"),
txDescriptionInput: document.getElementById("tx-description"),
txDateInput:        document.getElementById("tx-date"),
txAmountInput:      document.getElementById("tx-amount"),
payFormPayAmountInput: document.getElementById("pay-form-pay-amount"),
txDescriptionError: document.getElementById("tx-description-error"),
txDateError:        document.getElementById("tx-date-error"),
txAmountError:      document.getElementById("tx-amount-error"),

// Buttons
openAddDebtorBtn: document.getElementById("open-add-modal-btn"),
emptyStateAddDebtorBtn: document.getElementById("empty-state-add-btn"),
openAddTxBtn: document.getElementById("open-transaction-modal-btn"),

closeDebtorModalBtn: document.getElementById("close-debtor-modal-btn"),
cancelDebtorModalBtn: document.getElementById("cancel-debtor-modal-btn"),
closeTxModalBtn: document.getElementById("close-tx-modal-btn"),
cancelTxModalBtn:     document.getElementById("cancel-tx-modal-btn"),

cancelDeleteBtn:  document.getElementById("cancel-delete-btn"),
confirmDeleteBtn: document.getElementById("confirm-delete-btn"),
deleteDesc:       document.getElementById("delete-desc"),
deleteTitle:      document.getElementById("delete-title"),

// Theme / Toast
themeToggle:    document.getElementById("theme-toggle"),
toastContainer: document.getElementById("toast-container")
};

let lastStates = {};
function checkSystemStateAndRefresh(targetTables, refreshCallback) {
    fetch('api/check_state.php')
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success' && res.states) {
                let hasChanges = false;
                targetTables.forEach(t => {
                    const newTs = res.states[t] || 0;
                    if (lastStates[t] !== undefined && lastStates[t] !== newTs) {
                        hasChanges = true;
                    }
                    lastStates[t] = newTs;
                });
                if (hasChanges) {
                    refreshCallback();
                }
            }
        })
        .catch(err => console.error("Error checking states:", err));
}

// -------------------------------------------------------------
// 3. Initialization
// -------------------------------------------------------------
document.addEventListener("DOMContentLoaded", () => {
    // Populate initial states
    fetch('api/check_state.php')
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success' && res.states) {
                lastStates = res.states;
            }
        }).catch(() => {});

    loadData(true);
    setInterval(() => {
        checkSystemStateAndRefresh(['debtors', 'safe_transactions', 'forms'], () => loadData(false));
    }, 3000);
    initTheme();
    setupEventListeners();
    loadSafesDropdown();
});

// Load data from MySQL database
let lastDebtorsJson = "";
function loadData(force = false) {
fetch('api/debts.php?action=list_debtors')
.then(r => {
    if (!r.ok) {
        if (r.status === 401) {
            window.location.href = 'login.php';
            return null;
        }
    }
    return r.json();
})
.then(res => {
if (!res) return;
if (res.status === 'success') {
    const debtorsJson = JSON.stringify(res.debtors);
    if (debtorsJson !== lastDebtorsJson || force) {
        lastDebtorsJson = debtorsJson;
        state.debtors = res.debtors;
        applyDebtorsFilter();
    }

    // If the active debtor modal is open, also refresh their transactions silently
    if (state.activeDebtorId) {
        const activeDebtor = state.debtors.find(x => x.id === state.activeDebtorId);
        if (activeDebtor) {
            const balance = parseFloat(activeDebtor.balance) || 0;
            if (dom.histBalance) {
                dom.histBalance.textContent = `${formatCurrency(Math.abs(balance))} ${getCurrency()}`;
            }
        }
        renderTransactionsFeed(state.activeDebtorId, true);
    }
} else if (force) {
    showToast(res.message || 'فشل تحميل بيانات المدينين', 'danger');
}
})
.catch(err => {
    console.error("Error loading debtors data:", err);
    if (force) showToast('فشل الاتصال بالخادم', 'danger');
});
}

// Fetch safes from API and populate dropdown
function loadSafesDropdown() {
if (!dom.txSafeIdSelect) return;
fetch('api/safes.php?action=list')
.then(r => r.json())
.then(res => {
if (res.status === 'success' && res.safes) {
dom.txSafeIdSelect.innerHTML = '<option value="">-- اختر الخزنة/الصندوق --</option>';
res.safes.forEach(safe => {
const option = document.createElement("option");
option.value = safe.id;
option.textContent = safe.name;
dom.txSafeIdSelect.appendChild(option);
});
}
})
.catch(() => {});
}

// -------------------------------------------------------------
// 4. Dark/Light Theme Management
// -------------------------------------------------------------
function initTheme() {
const savedTheme = localStorage.getItem("dashboard_theme");
if (savedTheme === "dark") {
document.body.classList.add("dark-theme");
dom.themeToggle.innerHTML = '<i class="fa-solid fa-sun"></i>';
} else {
document.body.classList.remove("dark-theme");
dom.themeToggle.innerHTML = '<i class="fa-solid fa-moon"></i>';
}
}

function toggleTheme() {
if (document.body.classList.contains("dark-theme")) {
document.body.classList.remove("dark-theme");
dom.themeToggle.innerHTML = '<i class="fa-solid fa-moon"></i>';
localStorage.setItem("dashboard_theme", "light");
showToast("تم تفعيل الوضع المضيء", "info");
} else {
document.body.classList.add("dark-theme");
dom.themeToggle.innerHTML = '<i class="fa-solid fa-sun"></i>';
localStorage.setItem("dashboard_theme", "dark");
showToast("تم تفعيل الوضع الداكن", "info");
}
}

// -------------------------------------------------------------
// 5. Toast Notifications
// -------------------------------------------------------------
function showToast(message, type = "success") {
const toast = document.createElement("div");
toast.className = `toast toast-${type}`;

let iconClass = "fa-circle-check";
if (type === "danger") iconClass = "fa-circle-xmark";
if (type === "warning") iconClass = "fa-circle-exclamation";
if (type === "info") iconClass = "fa-circle-info";

toast.innerHTML = `
<i class="fa-solid ${iconClass} toast-icon"></i>
<span class="toast-message">${message}</span>
`;

dom.toastContainer.appendChild(toast);

setTimeout(() => {
toast.remove();
}, 3000);
}

// -------------------------------------------------------------
// 6. Statistics & Calculations
// -------------------------------------------------------------
function calculateOutstandingBalance(debtorId) {
const debtor = state.debtors.find(x => x.id === debtorId);
return debtor ? debtor.balance : 0;
}

function updateStatistics() {
fetch('api/debts.php?action=get_stats')
.then(r => r.json())
.then(res => {
if (res.status === 'success' && res.stats) {
const s = res.stats;
dom.statTotalDebts.textContent = `${formatCurrency(s.totalOutstanding)} ${getCurrency()}`;
dom.statActiveDebtors.textContent = s.activeDebtors;
dom.statTotalRepayments.textContent = `${formatCurrency(s.totalRepayments)} ${getCurrency()}`;
}
})
.catch(() => {});
}

// Helper to read current currency from settings
function getCurrency() {
const settings = localStorage.getItem("dashboard_settings");
if (settings) {
try {
return JSON.parse(settings).currency || "د.ع";
} catch (e) {}
}
return "د.ع";
}

// Helper to get the work day start hour from settings
function getWorkDayStartHour() {
const settings = localStorage.getItem("dashboard_settings");
if (settings) {
try {
const parsed = JSON.parse(settings);
return parsed.workDayStartHour !== undefined ? parseInt(parsed.workDayStartHour) : 5;
} catch (e) {
return 5;
}
}
return 5;
}

// Helper to determine the work day date string (YYYY-MM-DD) for a given date object or string
function getWorkDayDate(dateInput) {
const d = new Date(dateInput);
if (isNaN(d.getTime())) {
return dateInput; // Fallback for raw YYYY-MM-DD strings without time
}


// If it's a date string like "2026-06-21" without a time component, treat it as is
if (typeof dateInput === 'string' && !dateInput.includes('T') && !dateInput.includes(':')) {
return dateInput;
}

const startHour = getWorkDayStartHour();
const adjusted = new Date(d.getTime() - (startHour * 60 * 60 * 1000));

const year = adjusted.getFullYear();
const month = String(adjusted.getMonth() + 1).padStart(2, '0');
const day = String(adjusted.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}

function formatCurrency(val) {
return parseFloat(val).toLocaleString('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 0 });
}

// -------------------------------------------------------------
// 7. Search & Filtering
// -------------------------------------------------------------
function applyDebtorsFilter() {
state.searchTerm = dom.searchInput.value.trim().toLowerCase();
renderDebtorsCards();
updateStatistics();

// Handle active debtor after filter
if (state.activeDebtorId) {
const remains = state.debtors.find(x => x.id === state.activeDebtorId);
if (!remains) {
clearSelection();
}
} else {
clearSelection();
}
}

// Search button handler
window.doSearchDebts = function() {
applyDebtorsFilter();
if (dom.searchInput) dom.searchInput.focus();
};

// Clear search
// Date Preset Handler
window.onDatePresetChange = function() {
    const presetSelect = document.getElementById("date-preset-filter");
    const preset = presetSelect ? presetSelect.value : "all";
    const dateFrom = document.getElementById("date-from");
    const dateTo = document.getElementById("date-to");

    if (!dateFrom || !dateTo) return;

    const todayStr = getWorkDayDate(new Date());

    if (preset === "all") {
        dateFrom.value = "";
        dateTo.value = "";
    } else if (preset === "today") {
        dateFrom.value = todayStr;
        dateTo.value = todayStr;
    } else if (preset === "yesterday") {
        const d = new Date();
        d.setDate(d.getDate() - 1);
        const yestStr = getWorkDayDate(d);
        dateFrom.value = yestStr;
        dateTo.value = yestStr;
    } else if (preset === "this_week") {
        const now = new Date();
        const dayOfWeek = now.getDay();
        const diffToSat = (dayOfWeek + 1) % 7;
        const sat = new Date(now);
        sat.setDate(now.getDate() - diffToSat);
        dateFrom.value = getWorkDayDate(sat);
        dateTo.value = todayStr;
    } else if (preset === "this_month") {
        const now = new Date();
        const firstDay = new Date(now.getFullYear(), now.getMonth(), 1);
        dateFrom.value = getWorkDayDate(firstDay);
        dateTo.value = todayStr;
    }

    applyDebtorsFilter();
};

// Custom Date Range Input Handler
window.onCustomDateChange = function() {
    const presetSelect = document.getElementById("date-preset-filter");
    if (presetSelect && presetSelect.value !== "custom") {
        presetSelect.value = "custom";
    }
    applyDebtorsFilter();
};

// Clear search and date filters
window.clearSearchDebts = function() {
    if (dom.searchInput) dom.searchInput.value = "";
    const filterSelect = document.getElementById("type-filter");
    if (filterSelect) filterSelect.value = "all";

    const presetSelect = document.getElementById("date-preset-filter");
    if (presetSelect) presetSelect.value = "all";

    const dateFrom = document.getElementById("date-from");
    if (dateFrom) dateFrom.value = "";

    const dateTo = document.getElementById("date-to");
    if (dateTo) dateTo.value = "";

    if (dom.panelResultsInfo) dom.panelResultsInfo.classList.remove("visible");
    applyDebtorsFilter();
};

// -------------------------------------------------------------
// 8. Render Debtors Table (Master List with Requested Columns)
// -------------------------------------------------------------
function renderDebtorsCards() {
if (!dom.debtorsTableBody) return;
dom.debtorsTableBody.innerHTML = "";

const filterSelect = document.getElementById("type-filter");
const filterVal = filterSelect ? filterSelect.value : "all";
const s = state.searchTerm;

const dateFromVal = document.getElementById("date-from") ? document.getElementById("date-from").value.trim() : "";
const dateToVal = document.getElementById("date-to") ? document.getElementById("date-to").value.trim() : "";
const isDateFiltered = dateFromVal !== "" || dateToVal !== "";

let flatRows = [];

state.debtors.forEach(debtor => {
    const custName = debtor.name || '';
    const custPhone = debtor.phone || '';
    const custBalance = parseFloat(debtor.balance) || 0;
    
    const items = debtor.items && debtor.items.length > 0 ? debtor.items : [
        {
            id: 'debtor_' + debtor.id,
            formId: null,
            formNumber: debtor.unpaidFormsCount > 0 ? `${debtor.unpaidFormsCount} استمارة` : 'دين يدوي',
            formDate: debtor.createdAt ? debtor.createdAt.split(' ')[0] : '—',
            totalAmount: Math.abs(custBalance),
            totalPaid: parseFloat(debtor.totalRepaid) || 0,
            remainingAmount: Math.abs(custBalance),
            isForm: false
        }
    ];

    items.forEach(item => {
        // 1. Filter by search
        if (s !== "") {
            const nameMatch = custName.toLowerCase().includes(s);
            const phoneMatch = custPhone.includes(s);
            const formMatch = (item.formNumber && item.formNumber.toLowerCase().includes(s)) || (item.formId && String(item.formId).includes(s));
            if (!nameMatch && !phoneMatch && !formMatch) return;
        }

        // 2. Filter by type
        if (filterVal === "active_forms") {
            if (!item.isForm || item.remainingAmount <= 0.01) return;
        } else if (filterVal === "paid_forms") {
            if (!item.isForm || item.remainingAmount > 0.01) return;
        } else if (filterVal === "manual_debts") {
            if (item.isForm) return;
        } else if (filterVal === "all") {
            // In "all", if no search term and no date filter: show active forms OR manual debt rows where remaining > 0.01
            if (s === "" && !isDateFiltered) {
                if (item.isForm && item.remainingAmount <= 0.01) return;
                if (!item.isForm && item.remainingAmount <= 0.01 && Math.abs(custBalance) <= 0.01) return;
            }
        }

        // 3. Filter by date range (from / to)
        const rawDate = item.formDate || (debtor.createdAt ? debtor.createdAt.split(' ')[0] : '');
        const itemDate = (rawDate && rawDate !== '—') ? rawDate.split(' ')[0] : '';

        if (dateFromVal !== "") {
            if (!itemDate || itemDate < dateFromVal) return;
        }
        if (dateToVal !== "") {
            if (!itemDate || itemDate > dateToVal) return;
        }

        flatRows.push({
            debtorId: debtor.id,
            debtorName: custName,
            debtorPhone: custPhone,
            debtorBalance: custBalance,
            ...item
        });
    });
});

// Sort rows alphabetically by Customer Name
flatRows.sort((a, b) => a.debtorName.localeCompare(b.debtorName, 'ar'));

if (flatRows.length === 0) {
    if (dom.debtorsTableContainer) dom.debtorsTableContainer.style.display = "none";
    if (dom.emptyStateDebtors) dom.emptyStateDebtors.style.display = "flex";
    if (dom.panelResultsInfo) dom.panelResultsInfo.classList.remove("visible");
    return;
}

if (dom.debtorsTableContainer) dom.debtorsTableContainer.style.display = "block";
if (dom.emptyStateDebtors) dom.emptyStateDebtors.style.display = "none";

flatRows.forEach((row, idx) => {
    const tr = document.createElement("tr");
    if (state.activeDebtorId === row.debtorId) {
        tr.classList.add("active-row");
    }

    const words = row.debtorName ? row.debtorName.trim().split(/\s+/) : ['م'];
    const initials = words.slice(0, 2).map(w => w[0]).join('');

    const isForm = row.isForm;
    const formBadgeHtml = isForm
        ? `<span class="form-num-badge" onclick="event.stopPropagation(); window.location.href='forms.php?formId=${row.formId}'" title="عرض الاستمارة #${row.formId}"><i class="fa-solid fa-file-invoice"></i> #${escapeHTML(row.formId)}</span>`
        : `<span class="form-num-badge manual"><i class="fa-solid fa-pen-clip"></i> ${escapeHTML(row.formNumber)}</span>`;

    let payBtnHtml = "";
    if (isForm && row.remainingAmount > 0.01) {
        payBtnHtml = `
        <button class="txn-pay-btn" onclick="event.stopPropagation(); openPayFormModal('${row.formId}', '${row.debtorId}', ${row.remainingAmount}, true)" title="سداد / دفعة جزئية للاستمارة #${row.formId}" style="padding:4px 10px;font-size:11px;border-radius:var(--radius-sm);">
            <i class="fa-solid fa-money-bill-wave"></i> سداد / دفعة
        </button>`;
    } else if (!isForm && (row.remainingAmount > 0.01 || Math.abs(row.debtorBalance) > 0.01)) {
        const remAmt = row.remainingAmount > 0.01 ? row.remainingAmount : Math.abs(row.debtorBalance);
        payBtnHtml = `
        <button class="txn-pay-btn" onclick="event.stopPropagation(); openPayFormModal(null, '${row.debtorId}', ${remAmt}, false)" title="تسديد دفعة حساب المدين" style="padding:4px 10px;font-size:11px;border-radius:var(--radius-sm);background:var(--success-light, rgba(16,185,129,0.12));color:var(--success);border:1px solid rgba(16,185,129,0.3);">
            <i class="fa-solid fa-hand-holding-dollar"></i> تسديد دفعة
        </button>`;
    }

    const historyBtnHtml = `
    <button class="txn-history-btn" onclick="event.stopPropagation(); selectDebtor('${row.debtorId}')" title="عرض تفاصيل الحركات والسجل الكامل" style="padding:4px 10px;font-size:11px;border-radius:var(--radius-sm);background:var(--primary-light, rgba(59,130,246,0.12));color:var(--primary);border:1px solid rgba(59,130,246,0.3);cursor:pointer;display:inline-flex;align-items:center;gap:4px;font-weight:700;">
        <i class="fa-solid fa-clock-rotate-left"></i> تفاصيل الحركات
    </button>`;

    tr.innerHTML = `
        <td class="td-index">${idx + 1}</td>
        <td>
            <div class="td-cust-info" onclick="selectDebtor('${row.debtorId}')" style="cursor:pointer;" title="عرض سجل حساب المدين">
                <div class="td-cust-avatar">${escapeHTML(initials)}</div>
                <div>
                    <div class="td-cust-name">${escapeHTML(row.debtorName)}</div>
                    <div class="td-cust-phone"><i class="fa-solid fa-phone fa-xs"></i> ${escapeHTML(row.debtorPhone || '—')}</div>
                </div>
            </div>
        </td>
        <td style="text-align:center;">${formBadgeHtml}</td>
        <td style="text-align:center;font-size:12px;color:var(--text-secondary);">${escapeHTML(row.formDate || '—')}</td>
        <td class="money-cell total-form">${formatCurrency(row.totalAmount)} ${getCurrency()}</td>
        <td class="money-cell ${row.remainingAmount > 0.01 ? 'remain-form' : 'paid-form'}">
            ${formatCurrency(row.remainingAmount)} ${getCurrency()}
        </td>
        <td style="text-align:center;">
            <span class="money-cell cust-balance ${row.remainingAmount <= 0.01 ? 'zero' : ''}">
                ${formatCurrency(row.remainingAmount)} ${getCurrency()}
            </span>
        </td>
        <td>
            <div class="table-actions-cell" style="display:flex;align-items:center;justify-content:center;gap:6px;">
                ${historyBtnHtml}
                ${payBtnHtml}
            </div>
        </td>
    `;

    dom.debtorsTableBody.appendChild(tr);
});

if (dom.panelResultsInfo && dom.panelResultsCount) {
    if (s !== "" || filterVal !== "all" || isDateFiltered) {
        dom.panelResultsInfo.classList.add("visible");
        dom.panelResultsCount.textContent = flatRows.length;
    } else {
        dom.panelResultsInfo.classList.remove("visible");
    }
}
}

// -------------------------------------------------------------
// 9. Master-Detail Interaction (Debtor Selection → History Modal)
// -------------------------------------------------------------
function selectDebtor(debtorId) {
state.activeDebtorId = debtorId;
const debtor = state.debtors.find(x => x.id === debtorId);
if (!debtor) { clearSelection(); return; }

// Update active table row highlight
if (dom.debtorsTableBody) {
    const rows = dom.debtorsTableBody.querySelectorAll('tr');
    rows.forEach(r => r.classList.remove('active-row'));
}

// Populate history modal header
const words    = debtor.name ? debtor.name.trim().split(/\s+/) : ['م'];
const initials = words.slice(0, 2).map(w => w[0]).join('');
if (dom.histAvatar) dom.histAvatar.textContent = initials;
if (dom.histName)   dom.histName.textContent   = debtor.name;
if (dom.histPhone) {
dom.histPhone.innerHTML = `<i class="fa-solid fa-phone fa-xs"></i> ${escapeHTML(debtor.phone || '—')}`;
}
const balance = parseFloat(debtor.balance) || 0;
const isNeg   = balance > 0.01;
if (dom.histBalance) {
dom.histBalance.textContent = `${formatCurrency(Math.abs(balance))} ${getCurrency()}`;
dom.histBalance.className = `hist-balance-pill ${isNeg ? 'negative' : 'positive'}`;
}

// Open history modal
if (dom.historyModal) dom.historyModal.classList.add("open");

// Reset filter and show feed
const txnFilter = document.getElementById("hist-txn-filter");
if (txnFilter) txnFilter.value = "all";
if (dom.debtTransactionsFeed)   dom.debtTransactionsFeed.style.display = "flex";
if (dom.emptyStateTransactions) dom.emptyStateTransactions.style.display = "none";

renderTransactionsFeed(debtorId);
}

function closeHistoryModal() {
if (dom.historyModal) dom.historyModal.classList.remove("open");
state.debtEntries    = [];
state.activeDebtorId = null;
lastFeedJson = "";
if (dom.debtorsTableBody) {
    const rows = dom.debtorsTableBody.querySelectorAll('tr');
    rows.forEach(r => r.classList.remove('active-row'));
}
}

function clearSelection() {
closeHistoryModal();
}

// -------------------------------------------------------------
// 10. Render Debt Entries (Timeline Feed)
// -------------------------------------------------------------
let lastFeedJson = "";
function renderTransactionsFeed(debtorId, isSilent = false) {
if (!isSilent) {
    dom.debtTransactionsFeed.innerHTML = `
    <div style="text-align:center;padding:30px;color:var(--text-secondary);">
    <i class="fa-solid fa-spinner fa-spin" style="font-size:24px;margin-bottom:8px;"></i>
    <p>جاري تحميل سجل الحركات...</p>
    </div>`;
}

const activeDebtor = state.debtors.find(x => x.id === debtorId);
if (!activeDebtor) return;

fetch(`api/debts.php?action=get_transactions&debtor_id=${debtorId}`)
.then(r => r.json())
.then(res => {
if (res.status !== 'success') {
    if (!isSilent) showToast('فشل تحميل حركات المدين', 'danger');
    return;
}

const feedJson = JSON.stringify({
    transactions: res.transactions,
    hasForms: res.hasForms,
    formsSummary: res.formsSummary
});

if (feedJson === lastFeedJson && isSilent) {
    return; // Skip re-render
}
lastFeedJson = feedJson;

state.debtEntries = res.transactions;
state.currentHasForms = res.hasForms;
state.currentFormsSummary = res.formsSummary;

filterAndRenderTransactions();
})
.catch(() => showToast('فشل الاتصال بالخادم لتحميل سجل الحركات', 'danger'));
}

window.filterAndRenderTransactions = function() {
    if (!state.activeDebtorId) return;

    const txnFilter = document.getElementById("hist-txn-filter");
    const filterVal = txnFilter ? txnFilter.value : "all";

    dom.debtTransactionsFeed.innerHTML = "";

    // 1. Show summary report banner if customer has forms
    if (state.currentHasForms && state.currentFormsSummary) {
        const totalCost = state.currentFormsSummary.totalCost || 0;
        const totalPaid = state.currentFormsSummary.totalPaid || 0;
        const remaining = state.currentFormsSummary.remaining || 0;

        const banner = document.createElement("div");
        banner.className = "hist-summary-banner";
        banner.style.cssText = "margin:0 0 16px 0;background:var(--bg-input);border:1px solid var(--border-color);border-radius:var(--radius-md);padding:14px;box-shadow:var(--shadow-sm);";

        const isFullyPaid = remaining <= 0.01;
        const statusColor = isFullyPaid ? 'var(--success)' : 'var(--danger)';
        const statusText = isFullyPaid ? 'مسددة بالكامل' : 'يوجد مبالغ مستحقة';

        banner.innerHTML = `
            <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:10px;">
                <div style="display:flex;align-items:center;gap:8px;">
                    <i class="fa-solid fa-file-invoice-dollar" style="font-size:16px;color:var(--primary);"></i>
                    <span style="font-weight:800;font-size:13px;color:var(--text-primary);">ملخص فواتير الاستمارات</span>
                </div>
                <span style="font-size:11px;font-weight:700;padding:2px 8px;border-radius:12px;background:rgba(0,0,0,0.04);color:${statusColor};border:1px solid ${statusColor};">
                    ${statusText}
                </span>
            </div>
            <div style="display:grid;grid-template-columns:repeat(3, 1fr);gap:8px;text-align:center;background:var(--bg-card);padding:10px;border-radius:var(--radius-sm);border:1px solid var(--border-color);">
                <div>
                    <div style="font-size:10.5px;color:var(--text-secondary);">إجمالي قيمة الفواتير</div>
                    <div style="font-size:13px;font-weight:800;color:var(--text-primary);margin-top:2px;">${formatCurrency(totalCost)} ${getCurrency()}</div>
                </div>
                <div>
                    <div style="font-size:10.5px;color:var(--text-secondary);">إجمالي المبالغ المسددة</div>
                    <div style="font-size:13px;font-weight:800;color:var(--success);margin-top:2px;">${formatCurrency(totalPaid)} ${getCurrency()}</div>
                </div>
                <div>
                    <div style="font-size:10.5px;color:var(--text-secondary);">الرصيد المتبقي المستحق</div>
                    <div style="font-size:13px;font-weight:800;color:${remaining > 0.01 ? 'var(--danger)' : 'var(--success)'};margin-top:2px;">${formatCurrency(remaining)} ${getCurrency()}</div>
                </div>
            </div>
        `;
        dom.debtTransactionsFeed.appendChild(banner);
    }

    // 2. Filter transactions based on selected option
    let filteredTxs = [...state.debtEntries];
    if (filterVal === "unpaid_forms") {
        filteredTxs = filteredTxs.filter(tx => tx.formId && tx.formStatus !== "1" && tx.formStatus !== "completed");
    } else if (filterVal === "paid_forms") {
        filteredTxs = filteredTxs.filter(tx => tx.formId && (tx.formStatus === "1" || tx.formStatus === "completed"));
    } else if (filterVal === "manual_debts") {
        filteredTxs = filteredTxs.filter(tx => !tx.formId);
    }
    // "all" includes EVERY transaction (no exclusions!)

    if (filteredTxs.length === 0) {
        dom.debtTransactionsFeed.innerHTML += `
            <div class="txn-no-entries" style="text-align:center;padding:40px 20px;color:var(--text-secondary);">
                <i class="fa-solid fa-folder-open" style="font-size:32px;color:var(--text-muted);margin-bottom:10px;display:block;"></i>
                <p style="font-size:13px;margin:0;">لا توجد حركات تطابق الفلتر المحدد.</p>
            </div>
        `;
        return;
    }

    filteredTxs.forEach(tx => {
        const isDebt = tx.type === "debt" || tx.type === "withdrawal";
        const iconClass = isDebt ? "fa-arrow-trend-up" : "fa-arrow-trend-down";
        const typeClass = isDebt ? "debt" : "repayment";
        const prefix = isDebt ? "+" : "-";

        const item = document.createElement("div");
        item.className = "txn-item";
        item.style.cssText = "display:flex;align-items:center;gap:12px;padding:12px 14px;border-bottom:1px solid var(--border-color);background:var(--bg-card);margin-bottom:8px;border-radius:var(--radius-sm);transition:var(--transition);";

        let statusBadgeHtml = "";
        if (tx.formId) {
            if (tx.formStatus === '1' || tx.formStatus === 'completed') {
                statusBadgeHtml = `<span style="font-size:10px;font-weight:700;padding:2px 6px;border-radius:4px;background:var(--success-light);color:var(--success);">مسددة بالكامل</span>`;
            } else if (tx.formStatus === '2') {
                statusBadgeHtml = `<span style="font-size:10px;font-weight:700;padding:2px 6px;border-radius:4px;background:rgba(245,158,11,0.12);color:#d97706;">مدفوعة جزئياً</span>`;
            } else {
                statusBadgeHtml = `<span style="font-size:10px;font-weight:700;padding:2px 6px;border-radius:4px;background:var(--danger-light);color:var(--danger);">غير مدفوعة</span>`;
            }
        } else {
            statusBadgeHtml = isDebt ? `<span style="font-size:10px;font-weight:700;padding:2px 6px;border-radius:4px;background:rgba(239,68,68,0.1);color:var(--danger);">دين يدوي</span>`
                                     : `<span style="font-size:10px;font-weight:700;padding:2px 6px;border-radius:4px;background:var(--success-light);color:var(--success);">سداد</span>`;
        }

        let actionButtonHtml = "";
        if (tx.formId) {
            let payButtonHtml = "";
            if (tx.id === 'form_cost_' + tx.formId && tx.formStatus !== '1' && tx.formStatus !== 'completed') {
                payButtonHtml = `
                    <button class="txn-pay-btn" onclick="event.stopPropagation(); openPayFormModal('${tx.formId}', '${tx.debtorId}')" title="سداد / دفع جزئي" style="padding:4px 10px;font-size:11px;border-radius:6px;border:1px solid rgba(16,185,129,0.3);background:var(--success-light);color:var(--success);cursor:pointer;display:flex;align-items:center;gap:4px;font-weight:700;">
                        <i class="fa-solid fa-money-bill-wave"></i> سداد
                    </button>
                `;
            }
            let receiptBtnHtml = (!isDebt) ? `
                <button class="row-action-btn" onclick="event.stopPropagation(); printTransactionReceipt('${tx.id}')" title="طباعة وصل قبض" style="width:30px;height:30px;border-radius:6px;border:1px solid var(--border-color);background:var(--bg-input);color:var(--success);cursor:pointer;display:flex;align-items:center;justify-content:center;">
                    <i class="fa-solid fa-receipt"></i>
                </button>
            ` : '';
            actionButtonHtml = `
                <div style="display:flex;gap:6px;align-items:center;">
                    ${payButtonHtml}
                    ${receiptBtnHtml}
                    <button class="row-action-btn" onclick="event.stopPropagation(); window.location.href='forms.php?formId=${tx.formId}'" title="عرض الفاتورة #${tx.formId}" style="width:30px;height:30px;border-radius:6px;border:1px solid var(--border-color);background:var(--bg-input);color:var(--primary);cursor:pointer;display:flex;align-items:center;justify-content:center;">
                        <i class="fa-solid fa-file-invoice"></i>
                    </button>
                </div>
            `;
        } else {
            let receiptBtnHtml = (!isDebt) ? `
                <button class="row-action-btn" onclick="event.stopPropagation(); printTransactionReceipt('${tx.id}')" title="طباعة وصل قبض" style="width:30px;height:30px;border-radius:6px;border:1px solid var(--border-color);background:var(--bg-input);color:var(--success);cursor:pointer;display:flex;align-items:center;justify-content:center;">
                    <i class="fa-solid fa-receipt"></i>
                </button>
            ` : '';
            actionButtonHtml = `
                <div style="display:flex;gap:6px;align-items:center;">
                    ${receiptBtnHtml}
                    <button class="txn-del-btn" onclick="openDeleteTxEntryModal('${tx.id}')" title="حذف الحركة" style="width:30px;height:30px;border-radius:6px;border:1px solid var(--border-color);background:var(--bg-input);color:var(--danger);cursor:pointer;display:flex;align-items:center;justify-content:center;">
                        <i class="fa-solid fa-trash-can"></i>
                    </button>
                </div>
            `;
        }

        item.innerHTML = `
            <div class="txn-dot ${typeClass}" style="width:36px;height:36px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:14px;flex-shrink:0;">
                <i class="fa-solid ${iconClass}"></i>
            </div>
            <div class="txn-body" style="flex:1;min-width:0;display:flex;flex-direction:column;gap:2px;">
                <div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;">
                    <span class="txn-desc" style="font-size:13px;font-weight:700;color:var(--text-primary);">${escapeHTML(tx.description)}</span>
                    ${statusBadgeHtml}
                </div>
                <span class="txn-date" style="font-size:11px;color:var(--text-secondary);"><i class="fa-regular fa-calendar"></i> ${escapeHTML(tx.date)}</span>
            </div>
            <span class="txn-amount ${typeClass}" style="font-size:14px;font-weight:800;direction:ltr;white-space:nowrap;margin:0 8px;">${prefix} ${formatCurrency(tx.amount)} ${getCurrency()}</span>
            ${actionButtonHtml}
        `;
        dom.debtTransactionsFeed.appendChild(item);
    });
};

// -------------------------------------------------------------
// 10.5. Pay Specific Form Helpers
// -------------------------------------------------------------
function getFormRemainingAmount(formId) {
    let cost = 0;
    let paid = 0;
    state.debtEntries.forEach(tx => {
        if (tx.formId && String(tx.formId) === String(formId)) {
            if (tx.id === 'form_cost_' + formId) {
                cost = parseFloat(tx.amount) || 0;
            } else if (tx.type === 'repayment') {
                paid += parseFloat(tx.amount) || 0;
            } else if (tx.type === 'withdrawal') {
                paid -= parseFloat(tx.amount) || 0;
            }
        }
    });
    return Math.max(0, cost - paid);
}

window.openPayFormModal = function(formId, debtorId, defaultRemaining = null, isFormItem = true) {
    let remaining = 0;
    if (isFormItem && formId) {
        remaining = getFormRemainingAmount(formId);
        if (remaining <= 0.01 && defaultRemaining) remaining = parseFloat(defaultRemaining);
    } else {
        remaining = defaultRemaining ? parseFloat(defaultRemaining) : 0;
    }

    if (remaining <= 0.01) {
        showToast("لا يوجد رصيد متبقي مستحق للسداد", "warning");
        return;
    }

    const modal = document.getElementById("pay-form-modal");
    const labelId = document.getElementById("pay-form-id-label");
    const labelAmount = document.getElementById("pay-form-amount-label");
    const inputId = document.getElementById("pay-form-id-input");
    const inputMaxAmount = document.getElementById("pay-form-max-amount-input");
    const typeSelect = document.getElementById("pay-form-type-select");
    const payAmountInput = document.getElementById("pay-form-pay-amount");
    const descInput = document.getElementById("pay-form-desc-input");
    
    if (!modal) return;
    
    labelId.textContent = isFormItem && formId ? `#${formId}` : (debtorId ? 'حساب مدين' : '—');
    labelAmount.textContent = `${formatCurrency(remaining)} ${getCurrency()}`;
    inputId.value = formId || '';
    if (inputMaxAmount) inputMaxAmount.value = remaining;
    
    state.payFormDebtorId = debtorId;
    state.payIsFormItem = isFormItem;
    
    if (typeSelect) typeSelect.value = "full";
    if (payAmountInput) {
        payAmountInput.value = Math.round(remaining);
    }
    if (descInput) descInput.value = (isFormItem && formId) ? `سداد استمارة #${formId}` : `تسديد دفعة دين`;
    
    const select = document.getElementById("pay-form-safe-select");
    if (select) {
        select.innerHTML = dom.txSafeIdSelect.innerHTML;
        if (select.options.length > 1) {
            select.selectedIndex = 1;
        }
    }
    
    const dateInput = document.getElementById("pay-form-date-input");
    if (dateInput) {
        dateInput.value = getWorkDayDate(new Date());
    }

    const maxVal = parseFloat(remaining);

    const updatePayTypeAndAmount = function() {
        if (!payAmountInput) return;
        let rawVal = payAmountInput.value.replace(/,/g, '').trim();
        let numVal = parseFloat(rawVal);

        if (!isNaN(numVal) && maxVal > 0) {
            // Prevent amount from exceeding remaining (balance will never turn negative)
            if (numVal > maxVal) {
                numVal = maxVal;
                payAmountInput.value = Math.round(maxVal);
                showToast(`تم ضبط المبلغ على الحد الأقصى المتبقي المستحق (${formatCurrency(maxVal)} ${getCurrency()})`, "warning");
            }

            // Convert payment type from full to partial if amount is less than total remaining
            if (maxVal - numVal > 0.5) {
                if (typeSelect && typeSelect.value !== "partial") {
                    typeSelect.value = "partial";
                }
            } else {
                if (typeSelect && typeSelect.value !== "full") {
                    typeSelect.value = "full";
                }
            }
        }
    };

    if (payAmountInput) {
        payAmountInput.oninput = updatePayTypeAndAmount;
        payAmountInput.onchange = updatePayTypeAndAmount;
    }

    if (typeSelect) {
        typeSelect.onchange = function() {
            if (typeSelect.value === "full") {
                if (payAmountInput) payAmountInput.value = Math.round(remaining);
            } else {
                if (payAmountInput) {
                    payAmountInput.focus();
                    payAmountInput.select();
                }
            }
        };
    }
    
    modal.classList.add("open");
};

function closePayFormModal() {
    const modal = document.getElementById("pay-form-modal");
    if (modal) modal.classList.remove("open");
}

function handlePayFormConfirm() {
    const formId = document.getElementById("pay-form-id-input").value;
    const safeSelect = document.getElementById("pay-form-safe-select");
    const safeId = safeSelect ? safeSelect.value : "";
    const safeName = (safeSelect && safeSelect.selectedIndex >= 0) ? safeSelect.options[safeSelect.selectedIndex].text : "الخزنة الرئيسية";
    const date = document.getElementById("pay-form-date-input").value;
    const payAmountInput = document.getElementById("pay-form-pay-amount");
    const descInput = document.getElementById("pay-form-desc-input");
    const debtorId = state.payFormDebtorId;
    const isFormItem = state.payIsFormItem !== false;
    
    if (!safeId) {
        showToast("يرجى اختيار الخزنة المناسبة للمعاملة", "warning");
        return;
    }

    const amountStr = payAmountInput ? payAmountInput.value.replace(/,/g, '') : '0';
    const amount = parseFloat(amountStr);
    if (isNaN(amount) || amount <= 0) {
        showToast("يرجى إدخال مبلغ تسديد صالح أكبر من الصفر", "warning");
        return;
    }

    const maxAllowed = parseFloat(document.getElementById("pay-form-max-amount-input")?.value || 0);
    if (maxAllowed > 0 && amount > (maxAllowed + 0.01)) {
        showToast(`عذراً، المبلغ المدخل (${formatCurrency(amount)}) أكبر من الدين المتبقي المستحق (${formatCurrency(maxAllowed)}). لا يمكن تسديد مبلغ أكبر من قيمة الدين.`, "danger");
        return;
    }
    
    const confirmBtn = document.getElementById("confirm-pay-form-btn");
    if (confirmBtn) confirmBtn.disabled = true;

    const activeDebtor = state.debtors.find(x => x.id === (debtorId || state.activeDebtorId));
    const customerName = activeDebtor ? activeDebtor.name : (dom.histName ? dom.histName.textContent : 'الزبون');
    const customerPhone = activeDebtor ? activeDebtor.phone : (dom.histPhone ? dom.histPhone.textContent : '');
    const userDesc = descInput && descInput.value.trim() ? descInput.value.trim() : '';
    
    if (isFormItem && formId) {
        fetch('api/debts.php?action=pay_form_full', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                formId: parseInt(formId),
                safeId: parseInt(safeId),
                debtorId: debtorId,
                date: date,
                amount: amount,
                description: userDesc
            })
        })
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success') {
                showToast(res.message || "تم التسديد بنجاح!");
                closePayFormModal();

                const remainingBefore = getFormRemainingAmount(formId);
                const remainingAfter = Math.max(0, remainingBefore - amount);

                printPaymentReceipt({
                    receiptNo: res.tx_id || formId,
                    date: date || new Date().toISOString().split('T')[0],
                    customerName: customerName,
                    customerPhone: customerPhone,
                    amount: amount,
                    isFull: res.isFull !== undefined ? res.isFull : (remainingAfter <= 0.01),
                    safeName: safeName,
                    description: userDesc || `سداد استمارة #${formId}`,
                    remainingBalance: remainingAfter,
                    formId: formId
                });

                loadData(true);
                setTimeout(() => {
                    if (state.activeDebtorId) selectDebtor(state.activeDebtorId);
                }, 300);
            } else {
                showToast(res.message || "فشلت عملية السداد", "danger");
            }
        })
        .catch(() => showToast("فشل الاتصال بالخادم لتأكيد السداد", "danger"))
        .finally(() => {
            if (confirmBtn) confirmBtn.disabled = false;
        });
    } else {
        // Direct debt repayment
        fetch('api/debts.php?action=save_transaction', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                debtorId: debtorId,
                safeId: parseInt(safeId),
                type: 'repayment',
                date: date,
                amount: amount,
                description: userDesc || 'تسديد دفعة دين'
            })
        })
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success') {
                showToast(res.message || "تم تسديد الدفعة بنجاح!");
                closePayFormModal();

                const currentBal = activeDebtor ? parseFloat(activeDebtor.balance || 0) : 0;
                const remainingAfter = Math.max(0, currentBal - amount);

                printPaymentReceipt({
                    receiptNo: res.tx_id || Date.now(),
                    date: date || new Date().toISOString().split('T')[0],
                    customerName: customerName,
                    customerPhone: customerPhone,
                    amount: amount,
                    isFull: remainingAfter <= 0.01,
                    safeName: safeName,
                    description: userDesc || 'تسديد دفعة دين',
                    remainingBalance: remainingAfter
                });

                loadData(true);
                setTimeout(() => {
                    if (state.activeDebtorId) selectDebtor(state.activeDebtorId);
                }, 300);
            } else {
                showToast(res.message || "فشلت عملية السداد", "danger");
            }
        })
        .catch(() => showToast("فشل الاتصال بالخادم لتأكيد السداد", "danger"))
        .finally(() => {
            if (confirmBtn) confirmBtn.disabled = false;
        });
    }
}

let allRegisteredCustomers = [];

function renderCustomerSuggestions(query = '') {
    const dropdown = document.getElementById('customer-suggestions-dropdown');
    if (!dropdown) return;

    const trimmed = (query || '').trim().toLowerCase();
    const filtered = allRegisteredCustomers.filter(c => {
        if (!c.name) return false;
        const nameMatch = c.name.toLowerCase().includes(trimmed);
        const phoneMatch = c.phone ? c.phone.includes(trimmed) : false;
        return nameMatch || phoneMatch;
    });

    if (filtered.length === 0) {
        dropdown.innerHTML = '<div style="padding:12px; text-align:center; color:var(--text-muted); font-size:12.5px;">لا يوجد زبائن مطايقين للبحث</div>';
        return;
    }

    dropdown.innerHTML = filtered.map(c => {
        const escapedName = escapeHTML(c.name);
        const phoneText = c.phone ? escapeHTML(c.phone) : 'بدون هاتف';
        const rawName = c.name.replace(/'/g, "\\'").replace(/"/g, '&quot;');
        const rawPhone = (c.phone || '').replace(/'/g, "\\'").replace(/"/g, '&quot;');
        return `
        <div class="autocomplete-item" onclick="selectRegisteredCustomer('${rawName}', '${rawPhone}')" style="padding:10px 14px; cursor:pointer; font-size:13px; border-bottom:1px solid var(--border-color); display:flex; justify-content:space-between; align-items:center; transition:var(--transition);" onmouseover="this.style.background='var(--primary-light)';this.style.color='var(--primary)';" onmouseout="this.style.background='transparent';this.style.color='var(--text-primary)';">
            <div style="font-weight:700;"><i class="fa-solid fa-user" style="margin-left:8px; color:var(--primary); font-size:12px;"></i>${escapedName}</div>
            <div style="font-size:11.5px; color:var(--text-secondary);"><i class="fa-solid fa-phone" style="margin-left:4px; font-size:10px;"></i>${phoneText}</div>
        </div>`;
    }).join('');
}

window.selectRegisteredCustomer = function(name, phone) {
    const searchInput = document.getElementById('debtor-customer-search');
    const dropdown = document.getElementById('customer-suggestions-dropdown');
    
    if (searchInput) searchInput.value = name;
    if (dom.debtorNameInput) dom.debtorNameInput.value = name;
    if (dom.debtorPhoneInput) dom.debtorPhoneInput.value = phone || '';
    if (dom.debtorCustomerSelect) dom.debtorCustomerSelect.value = name;
    
    if (dropdown) dropdown.style.display = 'none';
};

function loadCustomersDropdown() {
    fetch('api/customers.php?action=list')
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success' && Array.isArray(res.data)) {
                allRegisteredCustomers = res.data;
                let optionsHtml = '<option value="">-- اختر عميلاً مسجلاً أو أدخل اسماً مخصصاً --</option>';
                let datalistHtml = '';
                
                res.data.forEach(c => {
                    if (c.name) {
                        const escapedName = escapeHTML(c.name);
                        const phoneAttr = escapeHTML(c.phone || '');
                        const phoneText = c.phone ? ` (${escapeHTML(c.phone)})` : '';
                        optionsHtml += `<option value="${escapedName}" data-phone="${phoneAttr}">${escapedName}${phoneText}</option>`;
                        datalistHtml += `<option value="${escapedName}">`;
                    }
                });
                
                if (dom.debtorCustomerSelect) dom.debtorCustomerSelect.innerHTML = optionsHtml;
                if (dom.customersDatalist) dom.customersDatalist.innerHTML = datalistHtml;
            }
        })
        .catch(err => console.error("Failed to fetch customers list:", err));
}

// -------------------------------------------------------------
// 11. Modal Controls - Debtor
// -------------------------------------------------------------
window.openEditDebtorModal = function(id) {
    const debtor = state.debtors.find(x => x.id === id);
    if (!debtor) return;

    clearDebtorValidationErrors();
    dom.debtorModalTitle.textContent = "تعديل بيانات المدين";
    dom.debtorIdInput.value = debtor.id;
    dom.debtorNameInput.value = debtor.name;
    dom.debtorPhoneInput.value = debtor.phone;

    if (dom.debtorAmountGroup) dom.debtorAmountGroup.style.display = "none";
    if (dom.customerSelectGroup) dom.customerSelectGroup.style.display = "none";

    dom.debtorModal.classList.add("open");
};

function openAddDebtorModal() {
    clearDebtorValidationErrors();
    dom.debtorModalTitle.textContent = "إضافة مدين جديد";
    dom.debtorForm.reset();
    dom.debtorIdInput.value = "";

    const searchInput = document.getElementById('debtor-customer-search');
    const dropdown = document.getElementById('customer-suggestions-dropdown');
    if (searchInput) searchInput.value = "";
    if (dropdown) dropdown.style.display = "none";

    if (dom.debtorAmountInput) dom.debtorAmountInput.value = "";
    if (dom.debtorCustomerSelect) dom.debtorCustomerSelect.value = "";
    if (dom.debtorAmountGroup) dom.debtorAmountGroup.style.display = "block";
    if (dom.customerSelectGroup) dom.customerSelectGroup.style.display = "block";

    loadCustomersDropdown();
    dom.debtorModal.classList.add("open");
}

function closeDebtorModal() {
    dom.debtorModal.classList.remove("open");
    dom.debtorForm.reset();
    clearDebtorValidationErrors();
}

function clearDebtorValidationErrors() {
    dom.debtorNameInput.closest(".form-group").classList.remove("has-error");
    dom.debtorPhoneInput.closest(".form-group").classList.remove("has-error");
    if (dom.debtorAmountInput) dom.debtorAmountInput.closest(".form-group").classList.remove("has-error");
}

// Debtor Form Submit
function handleDebtorFormSubmit(e) {
    e.preventDefault();
    const id = dom.debtorIdInput.value;
    const name = dom.debtorNameInput.value.trim();
    const phone = dom.debtorPhoneInput.value.trim();
    const amount = dom.debtorAmountInput ? (parseFloat(dom.debtorAmountInput.value.replace(/,/g, '')) || 0) : 0;

    let isValid = true;
    clearDebtorValidationErrors();

    if (!name || name.length < 3) {
        dom.debtorNameInput.closest(".form-group").classList.add("has-error");
        isValid = false;
    }

    if (!isValid) return;

    const saveBtn = document.getElementById("save-debtor-btn");
    if (saveBtn) saveBtn.disabled = true;

    fetch('api/debts.php?action=save_debtor', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id, name, phone, amount })
    })
    .then(r => r.json())
    .then(res => {
        if (res.status === 'success') {
            showToast(res.message || 'تم حفظ بيانات المدين بنجاح!');
            closeDebtorModal();
            loadData();
        } else {
            showToast(res.message || 'فشل الحفظ', 'danger');
        }
    })
    .catch(() => showToast('فشل الاتصال بالخادم لحفظ بيانات المدين', 'danger'))
.finally(() => { if (saveBtn) saveBtn.disabled = false; });
}

// Delete Debtor Trigger
window.openDeleteDebtorModal = function(id) {
const debtor = state.debtors.find(x => x.id === id);
if (!debtor) return;

state.deleteTargetType = "debtor";
state.deleteTargetId = id;
dom.deleteTitle.textContent = "تأكيد حذف المدين";
dom.deleteDesc.innerHTML = `هل أنت متأكد من رغبتك في حذف المدين <strong>"${escapeHTML(debtor.name)}"</strong>؟<br>سجل الديون والسدادات المرتبطة به سيُحذف بالكامل.`;
dom.deleteConfirmModal.classList.add("open");
};

// -------------------------------------------------------------
// 12. Modal Controls - Transaction
// -------------------------------------------------------------
function openAddTxModal() {
if (!state.activeDebtorId) return;
clearTxValidationErrors();
dom.transactionForm.reset();

    const today = new Date();
    const yyyy = today.getFullYear();
    const mm = String(today.getMonth() + 1).padStart(2, '0');
    const dd = String(today.getDate()).padStart(2, '0');
    dom.txDateInput.value = `${yyyy}-${mm}-${dd}`;
    dom.transactionModal.classList.add("open");
}

function closeTxModal() {
dom.transactionModal.classList.remove("open");
dom.transactionForm.reset();
clearTxValidationErrors();
}

function clearTxValidationErrors() {
dom.txDescriptionInput.closest(".form-group").classList.remove("has-error");
dom.txDateInput.closest(".form-group").classList.remove("has-error");
dom.txAmountInput.closest(".form-group").classList.remove("has-error");
const safeError = document.getElementById("tx-safe-error");
if (safeError) safeError.style.display = "none";
}

// Transaction Form Submit
function handleTxFormSubmit(e) {
e.preventDefault();

const type = dom.txTypeSelect.value;
const safeId = dom.txSafeIdSelect.value;
const description = dom.txDescriptionInput.value.trim();
const date = dom.txDateInput.value;
const amount = parseFloat(dom.txAmountInput.value.replace(/,/g, ''));

let isValid = true;
clearTxValidationErrors();


if (!description || description.length < 3) {
dom.txDescriptionInput.closest(".form-group").classList.add("has-error");
isValid = false;
}

if (!date) {
dom.txDateInput.closest(".form-group").classList.add("has-error");
isValid = false;
}

if (isNaN(amount) || amount <= 0) {
dom.txAmountInput.closest(".form-group").classList.add("has-error");
isValid = false;
}

if (!isValid) return;

const saveBtn = document.getElementById("save-tx-btn");
if (saveBtn) saveBtn.disabled = true;

fetch('api/debts.php?action=save_transaction', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
debtorId: state.activeDebtorId,
safeId,
description,
type,
date,
amount
})
})
.then(r => r.json())
.then(res => {
if (res.status === 'success') {
showToast(res.message || 'تم تسجيل الحركة بنجاح!');
closeTxModal();

if (type === 'repayment') {
    const safeSelect = dom.txSafeIdSelect;
    const safeName = (safeSelect && safeSelect.selectedIndex >= 0) ? safeSelect.options[safeSelect.selectedIndex].text : 'الخزنة الرئيسية';
    const activeDebtor = state.debtors.find(x => x.id === state.activeDebtorId);
    const customerName = activeDebtor ? activeDebtor.name : (dom.histName ? dom.histName.textContent : 'الزبون');
    const customerPhone = activeDebtor ? activeDebtor.phone : (dom.histPhone ? dom.histPhone.textContent : '');
    const currentBal = activeDebtor ? parseFloat(activeDebtor.balance || 0) : 0;
    const remainingAfter = Math.max(0, currentBal - amount);

    printPaymentReceipt({
        receiptNo: res.tx_id || Date.now(),
        date: date || new Date().toISOString().split('T')[0],
        customerName: customerName,
        customerPhone: customerPhone,
        amount: amount,
        isFull: remainingAfter <= 0.01,
        safeName: safeName,
        description: description || 'تسديد دفعة دين',
        remainingBalance: remainingAfter
    });
}

loadData();
// Reload active debtor transactions after database update
setTimeout(() => {
if (state.activeDebtorId) selectDebtor(state.activeDebtorId);
}, 300);
} else {
showToast(res.message || 'فشل التسجيل', 'danger');
}
})
.catch(() => showToast('فشل الاتصال بالخادم لتسجيل الحركة', 'danger'))
.finally(() => { if (saveBtn) saveBtn.disabled = false; });
}

// Delete individual transaction trigger
window.openDeleteTxEntryModal = function(id) {
const entry = state.debtEntries.find(x => x.id === id);
if (!entry) return;

state.deleteTargetType = "entry";
state.deleteTargetId = id;
dom.deleteTitle.textContent = "تأكيد حذف حركة الدين";
dom.deleteDesc.innerHTML = `هل أنت متأكد من رغبتك في حذف العملية <strong>"${escapeHTML(entry.description)}"</strong> بمبلغ <strong>${formatCurrency(entry.amount)} ${getCurrency()}</strong>؟`;
dom.deleteConfirmModal.classList.add("open");
};

// -------------------------------------------------------------
// 13. Delete Execution Handler
// -------------------------------------------------------------
function closeDeleteModal() {
dom.deleteConfirmModal.classList.remove("open");
state.deleteTargetType = null;
state.deleteTargetId = null;
}

function handleDeleteConfirm() {
if (!state.deleteTargetId || !state.deleteTargetType) return;
const id = state.deleteTargetId;

const confirmBtn = dom.confirmDeleteBtn;
if (confirmBtn) confirmBtn.disabled = true;

if (state.deleteTargetType === "debtor") {
fetch('api/debts.php?action=delete_debtor', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id })
})
.then(r => r.json())
.then(res => {
if (res.status === 'success') {
showToast(res.message || 'تم حذف المدين بنجاح', 'danger');
if (state.activeDebtorId === id) {
clearSelection();
}
closeDeleteModal();
loadData();
} else {
showToast(res.message || 'فشل حذف المدين', 'danger');
closeDeleteModal();
}
})
.catch(() => {
showToast('فشل الاتصال بالخادم لحذف المدين', 'danger');
closeDeleteModal();
})
.finally(() => { if (confirmBtn) confirmBtn.disabled = false; });
} else if (state.deleteTargetType === "entry") {
fetch('api/debts.php?action=delete_transaction', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id })
})
.then(r => r.json())
.then(res => {
if (res.status === 'success') {
showToast(res.message || 'تم حذف الحركة بنجاح', 'danger');
closeDeleteModal();
loadData();
setTimeout(() => {
if (state.activeDebtorId) selectDebtor(state.activeDebtorId);
}, 300);
} else {
showToast(res.message || 'فشل حذف الحركة', 'danger');
closeDeleteModal();
}
})
.catch(() => {
showToast('فشل الاتصال بالخادم لحذف الحركة', 'danger');
closeDeleteModal();
})
.finally(() => { if (confirmBtn) confirmBtn.disabled = false; });
}
}



// -------------------------------------------------------------
// 14. Event Listeners Setup
// -------------------------------------------------------------
function setupEventListeners() {
// Open Debtor Modal
dom.openAddDebtorBtn.addEventListener("click", openAddDebtorModal);
dom.emptyStateAddDebtorBtn.addEventListener("click", openAddDebtorModal);

// Customer Selector Search & Dynamic Autocomplete Suggestions
const customerSearchInput = document.getElementById('debtor-customer-search');
const customerSuggestionsDropdown = document.getElementById('customer-suggestions-dropdown');
const toggleCustomerDropdownBtn = document.getElementById('toggle-customer-dropdown-btn');

if (customerSearchInput && customerSuggestionsDropdown) {
    customerSearchInput.addEventListener('input', function() {
        renderCustomerSuggestions(this.value);
        customerSuggestionsDropdown.style.display = 'block';
    });

    customerSearchInput.addEventListener('focus', function() {
        renderCustomerSuggestions(this.value);
        customerSuggestionsDropdown.style.display = 'block';
    });
}

if (toggleCustomerDropdownBtn && customerSuggestionsDropdown) {
    toggleCustomerDropdownBtn.addEventListener('click', function(e) {
        e.stopPropagation();
        if (customerSuggestionsDropdown.style.display === 'block') {
            customerSuggestionsDropdown.style.display = 'none';
        } else {
            renderCustomerSuggestions(customerSearchInput ? customerSearchInput.value : '');
            customerSuggestionsDropdown.style.display = 'block';
        }
    });
}

document.addEventListener('click', function(e) {
    if (customerSuggestionsDropdown && !customerSuggestionsDropdown.contains(e.target) && e.target !== customerSearchInput && e.target !== toggleCustomerDropdownBtn) {
        customerSuggestionsDropdown.style.display = 'none';
    }
});

// Auto-lookup phone number when typing debtor name directly
if (dom.debtorNameInput) {
    dom.debtorNameInput.addEventListener('input', function() {
        const nameVal = this.value.trim().toLowerCase();
        if (nameVal && Array.isArray(allRegisteredCustomers)) {
            const matched = allRegisteredCustomers.find(c => c.name && c.name.trim().toLowerCase() === nameVal);
            if (matched && matched.phone && dom.debtorPhoneInput && !dom.debtorPhoneInput.value) {
                dom.debtorPhoneInput.value = matched.phone;
            }
        }
    });
}

// History Modal
const closeHistBtn = document.getElementById("close-history-modal-btn");
if (closeHistBtn) closeHistBtn.addEventListener("click", closeHistoryModal);
if (dom.histAddTxBtn) dom.histAddTxBtn.addEventListener("click", openAddTxModal);

// Close Debtor / Tx Modals
dom.closeDebtorModalBtn.addEventListener("click", closeDebtorModal);
dom.cancelDebtorModalBtn.addEventListener("click", closeDebtorModal);
dom.closeTxModalBtn.addEventListener("click", closeTxModal);
dom.cancelTxModalBtn.addEventListener("click", closeTxModal);
dom.cancelDeleteBtn.addEventListener("click", closeDeleteModal);

// Pay Form Modal Close
const closePayFormModalBtn = document.getElementById("close-pay-form-modal-btn");
const cancelPayFormBtn = document.getElementById("cancel-pay-form-btn");
const confirmPayFormBtn = document.getElementById("confirm-pay-form-btn");

if (closePayFormModalBtn) closePayFormModalBtn.addEventListener("click", closePayFormModal);
if (cancelPayFormBtn) cancelPayFormBtn.addEventListener("click", closePayFormModal);
if (confirmPayFormBtn) confirmPayFormBtn.addEventListener("click", handlePayFormConfirm);

// Confirm Delete
dom.confirmDeleteBtn.addEventListener("click", handleDeleteConfirm);

// Form Submits
dom.debtorForm.addEventListener("submit", handleDebtorFormSubmit);
dom.transactionForm.addEventListener("submit", handleTxFormSubmit);

// Format input amount with commas dynamically
const formatInputWithCommas = function (e) {
    let cursorPosition = this.selectionStart;
    let originalLength = this.value.length;

    // Remove any commas and non-digits first
    let value = this.value.replace(/,/g, '');
    
    // Split decimal part if any
    let parts = value.split('.');
    
    // Remove non-digit characters from the integer part
    parts[0] = parts[0].replace(/\D/g, '');
    
    // Add commas to the integer part
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    
    // Reassemble value
    if (parts.length > 1) {
        parts[1] = parts[1].replace(/\D/g, '').substring(0, 2);
        this.value = parts[0] + '.' + parts[1];
    } else {
        this.value = parts[0];
    }

    // Adjust cursor position
    let newLength = this.value.length;
    cursorPosition = cursorPosition + (newLength - originalLength);
    this.setSelectionRange(cursorPosition, cursorPosition);
};

if (dom.txAmountInput) dom.txAmountInput.addEventListener("input", formatInputWithCommas);
if (dom.debtorAmountInput) dom.debtorAmountInput.addEventListener("input", formatInputWithCommas);
if (dom.payFormPayAmountInput) dom.payFormPayAmountInput.addEventListener("input", formatInputWithCommas);

// Search input live filter
dom.searchInput.addEventListener("input", () => applyDebtorsFilter());

// Theme Switch
dom.themeToggle.addEventListener("click", toggleTheme);

// Close on overlay click
const payFormModal = document.getElementById("pay-form-modal");
window.addEventListener("click", (e) => {
if (e.target === dom.historyModal)      closeHistoryModal();
if (e.target === dom.debtorModal)       closeDebtorModal();
if (e.target === dom.transactionModal)  closeTxModal();
if (e.target === dom.deleteConfirmModal) closeDeleteModal();
if (e.target === payFormModal)          closePayFormModal();
});

// Close on Escape
window.addEventListener("keydown", (e) => {
if (e.key === "Escape") {
closeHistoryModal();
closeDebtorModal();
closeTxModal();
closeDeleteModal();
closePayFormModal();
}
});
}

// -------------------------------------------------------------
// 15. Helpers
// -------------------------------------------------------------
function escapeHTML(str) {
if (!str) return "";
return str.replace(/[&<>'"]/g, 
tag => ({
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
"'": '&#39;',
'"': '&quot;'
}[tag] || tag)
);
}
// -------------------------------------------------------------
// 17. Print All Debtors
// -------------------------------------------------------------
window.printAllDebtors = function() {
    const btn = document.getElementById('print-all-debtors-btn');
    if (btn) { btn.disabled = true; btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> جارٍ التحضير...'; }

    fetch('api/debts.php?action=get_print_data')
        .then(r => r.json())
        .then(res => {
            if (btn) { btn.disabled = false; btn.innerHTML = '<i class="fa-solid fa-print"></i> طباعة الكل'; }
            if (res.status !== 'success' || !res.debtors || res.debtors.length === 0) {
                showToast('لا توجد ديون مستحقة للطباعة', 'warning');
                return;
            }
            openPrintWindow(res.debtors);
        })
        .catch(() => {
            if (btn) { btn.disabled = false; btn.innerHTML = '<i class="fa-solid fa-print"></i> طباعة الكل'; }
            showToast('فشل الاتصال بالخادم', 'danger');
        });
};

function formatNum(n) {
    return Number(n).toLocaleString('ar-IQ');
}

function openPrintWindow(debtors) {
    const cur = getCurrency();
    const today = new Date().toLocaleDateString('ar-IQ', { year:'numeric', month:'long', day:'numeric' });

    let flatRows = [];
    let grandTotalRemaining = 0;
    let grandTotalAmount = 0;
    let customerSet = new Set();

    debtors.forEach(d => {
        const custName = d.name || '';
        const custPhone = d.phone || '';
        const custBalance = parseFloat(d.balance) || 0;
        if (custBalance > 0.01) {
            customerSet.add(custName);
        }

        const items = d.items && d.items.length > 0 ? d.items : [];
        if (items.length === 0 && Math.abs(custBalance) > 0.01) {
            flatRows.push({
                debtorName: custName,
                debtorPhone: custPhone,
                debtorBalance: custBalance,
                formId: null,
                formNumber: 'دين يدوي',
                formDate: d.createdAt ? d.createdAt.split(' ')[0] : '—',
                totalAmount: Math.abs(custBalance),
                remainingAmount: Math.abs(custBalance),
                isForm: false
            });
            grandTotalRemaining += Math.abs(custBalance);
            grandTotalAmount += Math.abs(custBalance);
        } else {
            items.forEach(item => {
                const isForm = item.type === 'form' || item.isForm;
                const remaining = item.remaining !== undefined ? parseFloat(item.remaining) : parseFloat(item.remainingAmount || 0);
                
                // Skip fully paid forms, but NEVER skip manual debts/balances if balance or remaining > 0.01
                if (isForm && remaining <= 0.01) return;
                if (!isForm && remaining <= 0.01 && Math.abs(custBalance) <= 0.01) return;

                const rowRem = remaining > 0.01 ? remaining : Math.abs(custBalance);
                const totalAmt = item.grandTotal !== undefined ? parseFloat(item.grandTotal) : (item.totalAmount !== undefined ? parseFloat(item.totalAmount) : parseFloat(item.amount || rowRem));

                flatRows.push({
                    debtorName: custName,
                    debtorPhone: custPhone,
                    debtorBalance: custBalance,
                    formId: item.formId || null,
                    formNumber: item.formId ? `#${item.formId}` : (item.formNumber || 'دين يدوي'),
                    formDate: item.date || item.formDate || '—',
                    totalAmount: totalAmt,
                    remainingAmount: rowRem,
                    isForm: isForm
                });

                grandTotalRemaining += rowRem;
                grandTotalAmount += totalAmt;
            });
        }
    });

    flatRows.sort((a, b) => a.debtorName.localeCompare(b.debtorName, 'ar'));

    let tbodyHtml = '';
    flatRows.forEach((row, idx) => {
        const initials = row.debtorName.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('');
        const isForm = row.isForm;
        const formBadgeHtml = isForm
            ? `<span class="form-badge form-type"><i class="fa-solid fa-file-invoice"></i> #${row.formId}</span>`
            : `<span class="form-badge manual-type">دين يدوي</span>`;

        tbodyHtml += `
            <tr>
                <td class="td-center td-num">${idx + 1}</td>
                <td>
                    <div class="cust-info">
                        <div class="cust-avatar">${initials}</div>
                        <div>
                            <div class="cust-name">${escapeHTML(row.debtorName)}</div>
                            ${row.debtorPhone ? `<div class="cust-phone">📞 ${escapeHTML(row.debtorPhone)}</div>` : ''}
                        </div>
                    </div>
                </td>
                <td class="td-center">${formBadgeHtml}</td>
                <td class="td-center td-date">${escapeHTML(row.formDate)}</td>
                <td class="td-money">${formatNum(row.totalAmount)} ${cur}</td>
                <td class="td-money remain-col">${formatNum(row.remainingAmount)} ${cur}</td>
                <td class="td-center">
                    <span class="balance-pill">${formatNum(Math.abs(row.debtorBalance))} ${cur}</span>
                </td>
            </tr>
        `;
    });

    const html = `<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<title>سجل الديون والتحصيلات المستحقة – ${today}</title>
<style>
    @page { size: A4 portrait; margin: 12mm 10mm; }
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body {
        font-family: 'Segoe UI', Tahoma, Arial, sans-serif;
        font-size: 11px;
        color: #1e293b;
        background: #fff;
        direction: rtl;
    }
    
    .print-container { padding: 10px; }
    
    /* Header */
    .print-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 3px solid #b91c1c;
        padding-bottom: 12px;
        margin-bottom: 16px;
    }
    .brand-logo {
        display: flex;
        align-items: center;
        gap: 12px;
    }
    .brand-icon {
        width: 44px; height: 44px;
        border-radius: 12px;
        background: linear-gradient(135deg, #b91c1c, #dc2626);
        color: #fff;
        font-size: 20px;
        display: flex; align-items: center; justify-content: center;
    }
    .brand-title h1 { font-size: 17px; font-weight: 800; color: #b91c1c; margin: 0; }
    .brand-title p { font-size: 11px; color: #64748b; margin-top: 2px; }
    .meta-info { text-align: right; font-size: 10.5px; color: #475569; line-height: 1.6; }
    .meta-info strong { color: #0f172a; }

    /* Summary Bar */
    .kpi-strip {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 12px;
        margin-bottom: 16px;
    }
    .kpi-box {
        border-radius: 8px;
        padding: 10px 14px;
        text-align: center;
        border: 1px solid #e2e8f0;
    }
    .kpi-box.danger  { background: #fef2f2; border-color: #fecaca; }
    .kpi-box.primary { background: #eff6ff; border-color: #bfdbfe; }
    .kpi-box.success { background: #f0fdf4; border-color: #bbf7d0; }
    .kpi-box .lbl { font-size: 10px; color: #64748b; margin-bottom: 3px; }
    .kpi-box .val { font-size: 15px; font-weight: 800; }
    .kpi-box.danger .val  { color: #b91c1c; }
    .kpi-box.primary .val { color: #1d4ed8; }
    .kpi-box.success .val { color: #15803d; }

    /* Main Debts Table */
    .print-debts-table {
        width: 100%;
        border-collapse: collapse;
        font-size: 11px;
        border: 1px solid #cbd5e1;
        margin-bottom: 16px;
    }
    .print-debts-table thead tr {
        background: #f1f5f9;
        border-bottom: 2px solid #94a3b8;
    }
    .print-debts-table th {
        padding: 10px 8px;
        font-weight: 800;
        font-size: 11px;
        color: #334155;
        text-align: center;
        border: 1px solid #cbd5e1;
    }
    .print-debts-table td {
        padding: 8px 10px;
        border: 1px solid #e2e8f0;
        vertical-align: middle;
    }
    .print-debts-table tbody tr:nth-child(even) {
        background: #f8fafc;
    }
    .td-center { text-align: center; }
    .td-num { font-weight: 700; color: #64748b; font-size: 10px; width: 30px; }
    .td-date { font-size: 10px; color: #64748b; }
    .td-money { text-align: center; font-weight: 800; direction: ltr; white-space: nowrap; }
    .remain-col { color: #b91c1c; font-size: 12px; }

    .cust-info { display: flex; align-items: center; gap: 8px; }
    .cust-avatar {
        width: 28px; height: 28px;
        border-radius: 50%;
        background: linear-gradient(135deg, #1e293b, #475569);
        color: #fff; font-size: 10px; font-weight: 800;
        display: flex; align-items: center; justify-content: center;
        flex-shrink: 0;
    }
    .cust-name { font-weight: 800; color: #0f172a; font-size: 11.5px; }
    .cust-phone { font-size: 9.5px; color: #64748b; margin-top: 1px; }

    .form-badge {
        display: inline-block;
        padding: 3px 8px;
        border-radius: 4px;
        font-size: 10px;
        font-weight: 800;
    }
    .form-badge.form-type { background: #dbeafe; color: #1d4ed8; }
    .form-badge.manual-type { background: #f1f5f9; color: #475569; }

    .balance-pill {
        display: inline-block;
        padding: 3px 8px;
        border-radius: 6px;
        background: #fef2f2;
        color: #b91c1c;
        font-weight: 800;
        font-size: 11px;
        direction: ltr;
    }

    /* Table Footer */
    .print-debts-table tfoot tr {
        background: #0f172a;
        color: #fff;
    }
    .print-debts-table tfoot td {
        padding: 10px;
        font-weight: 800;
        font-size: 12px;
        border: 1px solid #1e293b;
    }
    .total-title { text-align: right; }
    .total-val-highlight { color: #fca5a5 !important; font-size: 13px; }

    .print-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 10px;
        color: #94a3b8;
        border-top: 1px solid #e2e8f0;
        padding-top: 10px;
    }
</style>
</head>
<body>
<div class="print-container">
    <div class="print-header">
        <div class="brand-logo">
            <div class="brand-icon">🧾</div>
            <div class="brand-title">
                <h1>${getOrgName()} — سجل الديون والتحصيلات المستحقة</h1>
                <p>تقرير تفصيلي بمطابقة الجدول الرئيسي للديون</p>
            </div>
        </div>
        <div class="meta-info">
            <div>📅 تاريخ الطباعة: <strong>${today}</strong></div>
            <div>👥 عدد المدينين النشطين: <strong>${customerSet.size}</strong></div>
            <div>📋 إجمالي بنود السجلات: <strong>${flatRows.length}</strong></div>
        </div>
    </div>

    <div class="kpi-strip">
        <div class="kpi-box danger">
            <div class="lbl">إجمالي الديون المتبقية</div>
            <div class="val">${formatNum(grandTotalRemaining)} ${cur}</div>
        </div>
        <div class="kpi-box primary">
            <div class="lbl">عدد المدينين النشطين</div>
            <div class="val">${customerSet.size}</div>
        </div>
        <div class="kpi-box success">
            <div class="lbl">إجمالي قيمة الفواتير والديون</div>
            <div class="val">${formatNum(grandTotalAmount)} ${cur}</div>
        </div>
    </div>

    <table class="print-debts-table">
        <thead>
            <tr>
                <th style="width:30px;">ت</th>
                <th style="text-align:right;">الزبون / الهاتف</th>
                <th style="width:110px;">رقم الاستمارة/النوع</th>
                <th style="width:90px;">التاريخ</th>
                <th style="width:120px;">قيمة الفاتورة/الدين</th>
                <th style="width:120px;">المتبقي المستحق</th>
                <th style="width:120px;">إجمالي رصيد الزبون</th>
            </tr>
        </thead>
        <tbody>
            ${tbodyHtml}
        </tbody>
        <tfoot>
            <tr>
                <td colspan="4" class="total-title">الإجمالي المستحق الكلي لجميع الديون:</td>
                <td class="td-money">${formatNum(grandTotalAmount)} ${cur}</td>
                <td class="td-money total-val-highlight">${formatNum(grandTotalRemaining)} ${cur}</td>
                <td></td>
            </tr>
        </tfoot>
    </table>

    <div class="print-footer">
        <div>نظام ${getOrgName()} لإدارة الديون والتحصيلات</div>
        <div>طباعة مباشرة لجدول الديون</div>
    </div>
</div>
<script>
    window.onload = function() {
        setTimeout(function() {
            window.print();
        }, 500);
    };
<\/script>
</body>
</html>`;

    const win = window.open('', '_blank', 'width=950,height=750');
    if (win) {
        win.document.write(html);
        win.document.close();
    } else {
        showToast('يرجى السماح بالنوافذ المنبثقة للطباعة', 'warning');
    }
}


function escapeHTML(str) {
    if (!str) return "";
    return str.replace(/[&<>'"]/g, 
        tag => ({
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            "'": '&#39;',
            '"': '&quot;'
        }[tag] || tag)
    );
}

// -------------------------------------------------------------
// 18. Export Debts to Excel
// -------------------------------------------------------------
window.exportDebtsToExcel = function() {
    const filterSelect = document.getElementById("type-filter");
    const filterVal = filterSelect ? filterSelect.value : "all";
    const s = state.searchTerm;
    const dateFromVal = document.getElementById("date-from") ? document.getElementById("date-from").value.trim() : "";
    const dateToVal = document.getElementById("date-to") ? document.getElementById("date-to").value.trim() : "";
    const isDateFiltered = dateFromVal !== "" || dateToVal !== "";

    let rowsToExport = [];

    state.debtors.forEach(debtor => {
        const custName = debtor.name || '';
        const custPhone = debtor.phone || '';
        const custBalance = parseFloat(debtor.balance) || 0;
        
        const items = debtor.items && debtor.items.length > 0 ? debtor.items : [
            {
                id: 'debtor_' + debtor.id,
                formId: null,
                formNumber: debtor.unpaidFormsCount > 0 ? `${debtor.unpaidFormsCount} استمارة` : 'دين يدوي',
                formDate: debtor.createdAt ? debtor.createdAt.split(' ')[0] : '—',
                totalAmount: Math.abs(custBalance),
                totalPaid: parseFloat(debtor.totalRepaid) || 0,
                remainingAmount: Math.abs(custBalance),
                isForm: false
            }
        ];

        items.forEach(item => {
            if (s !== "") {
                const nameMatch = custName.toLowerCase().includes(s);
                const phoneMatch = custPhone.includes(s);
                const formMatch = (item.formNumber && item.formNumber.toLowerCase().includes(s)) || (item.formId && String(item.formId).includes(s));
                if (!nameMatch && !phoneMatch && !formMatch) return;
            }

            if (filterVal === "active_forms") {
                if (!item.isForm || item.remainingAmount <= 0.01) return;
            } else if (filterVal === "paid_forms") {
                if (!item.isForm || item.remainingAmount > 0.01) return;
            } else if (filterVal === "manual_debts") {
                if (item.isForm) return;
            } else if (filterVal === "all") {
                if (s === "" && !isDateFiltered) {
                    if (item.isForm && item.remainingAmount <= 0.01) return;
                    if (!item.isForm && item.remainingAmount <= 0.01 && Math.abs(custBalance) <= 0.01) return;
                }
            }

            const rawDate = item.formDate || (debtor.createdAt ? debtor.createdAt.split(' ')[0] : '');
            const itemDate = (rawDate && rawDate !== '—') ? rawDate.split(' ')[0] : '';
            if (dateFromVal !== "") {
                if (!itemDate || itemDate < dateFromVal) return;
            }
            if (dateToVal !== "") {
                if (!itemDate || itemDate > dateToVal) return;
            }

            rowsToExport.push({
                debtorName: custName,
                debtorPhone: custPhone,
                debtorBalance: custBalance,
                ...item
            });
        });
    });

    if (rowsToExport.length === 0) {
        showToast("لا توجد بيانات ديون لتصديرها", "warning");
        return;
    }

    // Sort alphabetically by Customer Name
    rowsToExport.sort((a, b) => a.debtorName.localeCompare(b.debtorName, 'ar'));

    // CSV header with UTF-8 BOM for Arabic Excel
    let csvContent = "\uFEFF";
    csvContent += "ت,اسم الزبون,رقم الهاتف,رقم الاستمارة (الحسبة),تاريخ الاستمارة (الحسبة),المبلغ الكلي للاستمارة,مبلغ المتبقي للاستمارة,مبلغ المتبقي للسجل\n";

    rowsToExport.forEach((r, idx) => {
        const serial = idx + 1;
        const name = `"${(r.debtorName || "").replace(/"/g, '""')}"`;
        const phone = `"${(r.debtorPhone || "").replace(/"/g, '""')}"`;
        const formNum = `"${(r.formNumber || (r.formId ? '#' + r.formId : 'دين يدوي')).replace(/"/g, '""')}"`;
        const formDate = `"${(r.formDate || "").replace(/"/g, '""')}"`;
        const totalAmt = r.totalAmount || 0;
        const remainAmt = r.remainingAmount || 0;

        csvContent += `${serial},${name},${phone},${formNum},${formDate},${totalAmt},${remainAmt},${remainAmt}\n`;
    });

    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    const today = new Date().toISOString().split('T')[0];
    link.setAttribute("href", url);
    link.setAttribute("download", `سجل_الديون_والتحصيلات_${today}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    showToast("تم تصدير ملف إكسل بنجاح", "success");
};

// -------------------------------------------------------------
// 19. Customer Payment Receipt Printing Functions
// -------------------------------------------------------------
window.printPaymentReceipt = function(data) {
    const cur = getCurrency();
    const orgName = getOrgName();
    const receiptNo = data.receiptNo || ('REC-' + Math.floor(100000 + Math.random() * 900000));
    const dateStr = data.date || new Date().toISOString().split('T')[0];
    const customerName = data.customerName || 'الزبون';
    const customerPhone = data.customerPhone || '';
    const amount = parseFloat(data.amount || 0);
    const safeName = data.safeName || 'الخزنة الرئيسية';
    const description = data.description || 'تسديد دفعة حساب';
    const isFull = data.isFull === true;
    const remainingBalance = (data.remainingBalance !== undefined && data.remainingBalance !== null) ? parseFloat(data.remainingBalance) : null;
    const formId = data.formId ? `#${data.formId}` : null;

    const html = `<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<title>وصل قبض زبون – ${escapeHTML(customerName)}</title>
<style>
    @page { size: A5 landscape; margin: 8mm; }
    @media print {
        body { -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
        .no-print { display: none !important; }
    }
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        font-size: 12px;
        color: #0f172a;
        background: #f8fafc;
        direction: rtl;
        padding: 12px;
    }
    .receipt-card {
        background: #ffffff;
        border: 2px solid #1e293b;
        border-radius: 12px;
        padding: 20px 24px;
        max-width: 720px;
        margin: 0 auto;
        box-shadow: 0 4px 15px rgba(0,0,0,0.05);
        position: relative;
    }
    .receipt-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 2px solid #16a34a;
        padding-bottom: 12px;
        margin-bottom: 16px;
    }
    .brand-info {
        display: flex;
        align-items: center;
        gap: 12px;
    }
    .brand-icon {
        width: 44px; height: 44px;
        border-radius: 10px;
        background: linear-gradient(135deg, #16a34a, #15803d);
        color: #ffffff;
        font-size: 22px;
        display: flex; align-items: center; justify-content: center;
    }
    .brand-title {
        font-size: 17px;
        font-weight: 800;
        color: #0f172a;
        margin: 0;
    }
    .brand-subtitle {
        font-size: 11px;
        color: #64748b;
        margin-top: 2px;
    }
    .receipt-title-box {
        text-align: center;
    }
    .receipt-title-main {
        font-size: 20px;
        font-weight: 900;
        color: #15803d;
        letter-spacing: 0.5px;
    }
    .receipt-type-tag {
        display: inline-block;
        font-size: 10.5px;
        font-weight: 800;
        padding: 2px 10px;
        border-radius: 12px;
        background: ${isFull ? '#dcfce7' : '#fef3c7'};
        color: ${isFull ? '#15803d' : '#b45309'};
        border: 1px solid ${isFull ? '#86efac' : '#fde68a'};
        margin-top: 3px;
    }
    .meta-details {
        text-align: right;
        font-size: 11.5px;
        color: #475569;
        line-height: 1.6;
    }
    .meta-details strong { color: #0f172a; font-weight: 800; }

    .receipt-body {
        margin-bottom: 16px;
    }
    .info-table {
        width: 100%;
        border-collapse: separate;
        border-spacing: 0 8px;
        margin-bottom: 14px;
    }
    .info-table td {
        padding: 10px 14px;
        background: #f8fafc;
        border-top: 1px solid #e2e8f0;
        border-bottom: 1px solid #e2e8f0;
    }
    .info-table td:first-child {
        border-right: 1px solid #e2e8f0;
        border-top-right-radius: 8px;
        border-bottom-right-radius: 8px;
        font-weight: 800;
        color: #475569;
        width: 140px;
        font-size: 12.5px;
    }
    .info-table td:last-child {
        border-left: 1px solid #e2e8f0;
        border-top-left-radius: 8px;
        border-bottom-left-radius: 8px;
        font-weight: 700;
        color: #0f172a;
        font-size: 13px;
    }

    .amount-card {
        background: linear-gradient(135deg, #15803d 0%, #16a34a 100%);
        color: #ffffff;
        border-radius: 10px;
        padding: 14px 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 14px;
    }
    .amount-label {
        font-size: 13.5px;
        font-weight: 700;
        opacity: 0.95;
    }
    .amount-val {
        font-size: 22px;
        font-weight: 900;
        direction: ltr;
    }

    .balance-bar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        background: #f1f5f9;
        border: 1px solid #cbd5e1;
        border-radius: 8px;
        padding: 8px 14px;
        font-size: 12px;
        font-weight: 700;
    }
    .balance-label { color: #475569; }
    .balance-val { color: ${remainingBalance !== null && remainingBalance <= 0.01 ? '#15803d' : '#b91c1c'}; font-size: 13px; font-weight: 800; }

    .receipt-footer {
        display: flex;
        justify-content: space-between;
        align-items: flex-end;
        border-top: 2px dashed #cbd5e1;
        padding-top: 16px;
        margin-top: 16px;
    }
    .sig-box {
        text-align: center;
        width: 180px;
    }
    .sig-title {
        font-size: 11px;
        font-weight: 700;
        color: #64748b;
        margin-bottom: 35px;
    }
    .sig-line {
        border-bottom: 1.5px solid #64748b;
    }
    .system-stamp {
        text-align: center;
        font-size: 10px;
        color: #94a3b8;
    }
</style>
</head>
<body>
<div class="receipt-card">
    <div class="receipt-header">
        <div class="brand-info">
            <div class="brand-icon">🧾</div>
            <div>
                <h1 class="brand-title">${escapeHTML(orgName)}</h1>
                <div class="brand-subtitle">سند / وصل استلام مبلغ من حساب زبون</div>
            </div>
        </div>
        <div class="receipt-title-box">
            <div class="receipt-title-main">وصل قبض</div>
            <div class="receipt-type-tag">${isFull ? 'سداد كامل' : 'دفعة جزئية'}</div>
        </div>
        <div class="meta-details">
            <div>رقم الوصل: <strong>#${escapeHTML(String(receiptNo))}</strong></div>
            <div>التاريخ: <strong>${escapeHTML(dateStr)}</strong></div>
            ${formId ? `<div>الاستمارة: <strong>${escapeHTML(formId)}</strong></div>` : ''}
        </div>
    </div>

    <div class="receipt-body">
        <table class="info-table">
            <tr>
                <td>استلمنا من السيد:</td>
                <td>${escapeHTML(customerName)} ${customerPhone ? `<span style="font-size:11px;color:#64748b;font-weight:400;">(${escapeHTML(customerPhone)})</span>` : ''}</td>
            </tr>
            <tr>
                <td>البيان:</td>
                <td>${escapeHTML(description)}</td>
            </tr>
            <tr>
                <td>الخزنة:</td>
                <td>${escapeHTML(safeName)}</td>
            </tr>
        </table>

        <div class="amount-card">
            <span class="amount-label">المبلغ المقبوض:</span>
            <span class="amount-val">${formatNum(amount)} ${cur}</span>
        </div>

        ${remainingBalance !== null ? `
        <div class="balance-bar">
            <span class="balance-label">الرصيد المتبقي المستحق على الزبون بعد هذا السداد:</span>
            <span class="balance-val">${formatNum(remainingBalance)} ${cur}</span>
        </div>
        ` : ''}
    </div>

    <div class="receipt-footer">
        <div class="sig-box">
            <div class="sig-title">توقيع الزبون</div>
            <div class="sig-line"></div>
        </div>
        <div class="system-stamp">
            تمت هذه العملية إلكترونياً عبر نظام ${escapeHTML(orgName)}
        </div>
        <div class="sig-box">
            <div class="sig-title">أمين الصندوق / المستلم</div>
            <div class="sig-line"></div>
        </div>
    </div>
</div>
<script>
    window.onload = function() {
        setTimeout(function() {
            window.print();
        }, 400);
    };
<\/script>
</body>
</html>`;

    const printWin = window.open('', '_blank', 'width=800,height=600');
    if (printWin) {
        printWin.document.write(html);
        printWin.document.close();
    } else {
        showToast('يرجى السماح بالنوافذ المنبثقة لطباعة وصل القبض', 'warning');
    }
};

window.printTransactionReceipt = function(txId) {
    const tx = state.debtEntries.find(x => String(x.id) === String(txId));
    if (!tx) {
        showToast('تعذر العثور على بيانات هذه الحركة للطباعة', 'warning');
        return;
    }

    const debtor = state.debtors.find(x => x.id === state.activeDebtorId);
    const debtorName = debtor ? debtor.name : (dom.histName ? dom.histName.textContent : 'الزبون');
    const debtorPhone = debtor ? debtor.phone : (dom.histPhone ? dom.histPhone.textContent : '');

    let safeName = 'الخزنة الرئيسية';
    if (dom.txSafeIdSelect) {
        const opt = Array.from(dom.txSafeIdSelect.options).find(o => String(o.value) === String(tx.safeId));
        if (opt && opt.text) safeName = opt.text;
    }

    printPaymentReceipt({
        receiptNo: tx.id.startsWith('form_') ? tx.formId : tx.id,
        date: tx.date || (tx.createdAt ? tx.createdAt.split(' ')[0] : new Date().toISOString().split('T')[0]),
        customerName: debtorName,
        customerPhone: debtorPhone,
        amount: parseFloat(tx.amount || 0),
        isFull: tx.formStatus === '1' || tx.formStatus === 'completed',
        safeName: safeName,
        description: tx.description || 'تسديد دفعة دين',
        formId: tx.formId || null
    });
};
