// Business Logic and UI Interactions for Customers (العملاء) Management Page

// -------------------------------------------------------------
// 1. App State
// -------------------------------------------------------------
let state = {
    customers: [],
    filteredCustomers: [],
    currentPage: 1,
    entriesPerPage: 10,
    searchTerm: "",
    deleteTargetId: null
};

// -------------------------------------------------------------
// 2. DOM Elements Selection
// -------------------------------------------------------------
const dom = {
    tbody: document.getElementById("customers-tbody"),
    emptyState: document.getElementById("empty-state-view"),
    table: document.getElementById("customers-table"),

    // Stats
    statTotal: document.getElementById("stat-total"),
    statActive: document.getElementById("stat-active"),
    statSuspended: document.getElementById("stat-suspended"),

    // Search & Filters
    searchInput: document.getElementById("search-input"),
    searchBtn: document.getElementById("search-btn"),
    searchClearBtn: document.getElementById("search-clear-btn"),
    searchResultsBadge: document.getElementById("search-results-badge"),
    entriesSelect: document.getElementById("entries-count"),

    // Pagination
    paginationInfo: document.getElementById("pagination-info-text"),
    paginationControls: document.getElementById("pagination-controls"),

    // Modals
    customerModal: document.getElementById("customer-modal"),
    deleteConfirmModal: document.getElementById("delete-confirm-modal"),

    // Form
    customerForm: document.getElementById("customer-form"),
    customerIdInput: document.getElementById("customer-id"),
    customerNameInput: document.getElementById("customer-name"),
    customerPhoneInput: document.getElementById("customer-phone"),
    customerStatusSelect: document.getElementById("customer-status"),
    customerNotesInput: document.getElementById("customer-notes"),
    modalTitle: document.getElementById("modal-title"),

    // Buttons
    openAddModalBtn: document.getElementById("open-add-modal-btn"),
    emptyStateAddBtn: document.getElementById("empty-state-add-btn"),
    closeModalBtn: document.getElementById("close-modal-btn"),
    cancelModalBtn: document.getElementById("cancel-modal-btn"),
    cancelDeleteBtn: document.getElementById("cancel-delete-btn"),
    confirmDeleteBtn: document.getElementById("confirm-delete-btn"),
    deleteItemName: document.getElementById("delete-item-name"),

    // Theme Toggle
    themeToggle: document.getElementById("theme-toggle"),

    // Toast Container
    toastContainer: document.getElementById("toast-container")
};

let lastStates = {};
function checkSystemStateAndRefresh(targetTables, refreshCallback) {
    fetch('api/check_state.php?_t=' + Date.now())
        .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. App Initialization
// -------------------------------------------------------------
document.addEventListener("DOMContentLoaded", () => {
    loadData();
    initTheme();
    setupEventListeners();

    fetch('api/check_state.php?_t=' + Date.now())
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success' && res.states) {
                lastStates = res.states;
            }
        }).catch(() => {});

    setInterval(() => {
        checkSystemStateAndRefresh(['customers'], loadData);
    }, 3000);
});

// Load data from MySQL database
function loadData() {
    fetch('api/customers.php?action=list')
        .then(response => response.json())
        .then(res => {
            if (res.status === 'success') {
                state.customers = res.data;
                applyFilters();
                updateStats();
            } else {
                showToast(res.message || "حدث خطأ أثناء تحميل البيانات", "danger");
            }
        })
        .catch(err => {
            console.error(err);
            showToast("فشل الاتصال بقاعدة البيانات", "danger");
        });
}

// -------------------------------------------------------------
// 4. Stats Update
// -------------------------------------------------------------
function updateStats() {
    const total = state.customers.length;
    const active = state.customers.filter(c => c.status === 'active').length;
    const suspended = total - active;

    if (dom.statTotal) dom.statTotal.textContent = total;
    if (dom.statActive) dom.statActive.textContent = active;
    if (dom.statSuspended) dom.statSuspended.textContent = suspended;
}

// -------------------------------------------------------------
// 5. Dark/Light Theme Management
// -------------------------------------------------------------
function initTheme() {
    const savedTheme = localStorage.getItem("dashboard_theme");
    if (savedTheme === "dark") {
        document.body.classList.add("dark-theme");
        if (dom.themeToggle) dom.themeToggle.innerHTML = '<i class="fa-solid fa-sun"></i>';
    } else {
        document.body.classList.remove("dark-theme");
        if (dom.themeToggle) 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");
        if (dom.themeToggle) dom.themeToggle.innerHTML = '<i class="fa-solid fa-moon"></i>';
        localStorage.setItem("dashboard_theme", "light");
        showToast("تم تفعيل الوضع المضيء", "info");
    } else {
        document.body.classList.add("dark-theme");
        if (dom.themeToggle) dom.themeToggle.innerHTML = '<i class="fa-solid fa-sun"></i>';
        localStorage.setItem("dashboard_theme", "dark");
        showToast("تم تفعيل الوضع الداكن", "info");
    }
}

// -------------------------------------------------------------
// 6. Toast Notification System
// -------------------------------------------------------------
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();
    }, 3500);
}

// -------------------------------------------------------------
// 7. Search, Filtering and Pagination Logic
// -------------------------------------------------------------
function applyFilters() {
    state.searchTerm = dom.searchInput ? dom.searchInput.value.trim().toLowerCase() : "";

    if (state.searchTerm === "") {
        state.filteredCustomers = [...state.customers];
        if (dom.searchResultsBadge) dom.searchResultsBadge.style.display = "none";
    } else {
        state.filteredCustomers = state.customers.filter(c => {
            return c.name.toLowerCase().includes(state.searchTerm) ||
                   (c.phone && c.phone.toLowerCase().includes(state.searchTerm));
        });
        if (dom.searchResultsBadge) {
            dom.searchResultsBadge.style.display = "inline-block";
            dom.searchResultsBadge.textContent = `تم إيجاد ${state.filteredCustomers.length} نتيجة`;
        }
    }

    state.entriesPerPage = dom.entriesSelect ? parseInt(dom.entriesSelect.value) : 10;

    const totalPages = Math.ceil(state.filteredCustomers.length / state.entriesPerPage);
    if (state.currentPage > totalPages) {
        state.currentPage = totalPages || 1;
    }

    renderTable();
}

window.doSearch = function() {
    state.currentPage = 1;
    applyFilters();
    if (dom.searchInput) dom.searchInput.focus();
};

window.clearSearch = function() {
    if (dom.searchInput) dom.searchInput.value = "";
    if (dom.searchResultsBadge) dom.searchResultsBadge.style.display = "none";
    state.currentPage = 1;
    applyFilters();
};

// -------------------------------------------------------------
// 8. Dynamic DOM Rendering
// -------------------------------------------------------------
function renderTable() {
    dom.tbody.innerHTML = "";
    const list = state.filteredCustomers;
    const total = list.length;

    if (total === 0) {
        dom.table.style.display = "none";
        dom.emptyState.style.display = "flex";
        if (dom.paginationInfo) dom.paginationInfo.textContent = "يعرض 0 إلى 0 من أصل 0 عميل";
        if (dom.paginationControls) dom.paginationControls.innerHTML = "";
        return;
    }

    dom.table.style.display = "table";
    dom.emptyState.style.display = "none";

    const startIndex = (state.currentPage - 1) * state.entriesPerPage;
    const endIndex = Math.min(startIndex + state.entriesPerPage, total);
    const paginatedList = list.slice(startIndex, endIndex);

    paginatedList.forEach((customer, index) => {
        const serial = startIndex + index + 1;
        const phoneText = customer.phone ? escapeHTML(customer.phone) : '—';
        const formsBadge = (customer.formsCount || 0) > 0
            ? `<span style="background:rgba(99,102,241,0.12); color:var(--primary); padding:3px 10px; border-radius:12px; font-weight:800; font-size:12px;"><i class="fa-solid fa-file-invoice" style="margin-left:4px;"></i>${customer.formsCount} استمارة</span>`
            : `<span style="color:var(--text-muted); font-size:12px;">لا تتوفر استمارات</span>`;

        const isActive = customer.status === 'active';
        const statusBadge = isActive
            ? `<span class="status-badge status-active" style="display:inline-flex;align-items:center;gap:5px;padding:4px 12px;border-radius:20px;font-size:12px;font-weight:700;background:rgba(16,185,129,0.12);color:#10b981;">
                   <i class="fa-solid fa-circle" style="font-size:7px;"></i> مفعّل
               </span>`
            : `<span class="status-badge status-suspended" style="display:inline-flex;align-items:center;gap:5px;padding:4px 12px;border-radius:20px;font-size:12px;font-weight:700;background:rgba(239,68,68,0.12);color:#ef4444;">
                   <i class="fa-solid fa-circle" style="font-size:7px;"></i> معطّل
               </span>`;

        const toggleTitle = isActive ? "تعطيل الحساب" : "تفعيل الحساب";
        const toggleIcon = isActive ? "fa-toggle-on" : "fa-toggle-off";
        const toggleColor = isActive ? "#10b981" : "#94a3b8";

        const tr = document.createElement("tr");
        tr.innerHTML = `
            <td class="serial-col">#${serial}</td>
            <td class="name-col" title="${escapeHTML(customer.name)}" style="font-weight:700;">${escapeHTML(customer.name)}</td>
            <td dir="ltr" style="text-align:right;">${phoneText}</td>
            <td>${formsBadge}</td>
            <td>${statusBadge}</td>
            <td>
                <div class="actions-cell">
                    <button class="btn-icon" onclick="toggleCustomerStatus('${customer.id}', '${customer.status}')"
                        title="${toggleTitle}"
                        style="color:${toggleColor}; font-size:20px; background:none; border:none; cursor:pointer; transition:transform 0.2s;"
                        onmouseover="this.style.transform='scale(1.15)'" onmouseout="this.style.transform='scale(1)'">
                        <i class="fa-solid ${toggleIcon}"></i>
                    </button>
                    <button class="btn-icon" onclick="openCustomerStatement('${customer.id}')" title="كشف الحساب والديون" style="color:var(--primary);">
                        <i class="fa-solid fa-file-invoice-dollar"></i>
                    </button>
                    <button class="btn-icon btn-icon-edit" onclick="openEditModal('${customer.id}')" title="تعديل">
                        <i class="fa-solid fa-pen-to-square"></i>
                    </button>
                    <button class="btn-icon btn-icon-delete" onclick="openDeleteModal('${customer.id}')" title="حذف">
                        <i class="fa-solid fa-trash-can"></i>
                    </button>
                </div>
            </td>
        `;
        dom.tbody.appendChild(tr);
    });

    if (dom.paginationInfo) {
        dom.paginationInfo.textContent = `يعرض ${startIndex + 1} إلى ${endIndex} من أصل ${total} عميل`;
    }

    renderPagination(total);
}

function renderPagination(totalItems) {
    if (!dom.paginationControls) return;
    dom.paginationControls.innerHTML = "";
    const totalPages = Math.ceil(totalItems / state.entriesPerPage);
    if (totalPages <= 1) return;

    // Previous Button
    const prevBtn = document.createElement("button");
    prevBtn.className = "page-btn";
    prevBtn.innerHTML = '<i class="fa-solid fa-chevron-right"></i>';
    prevBtn.disabled = state.currentPage === 1;
    prevBtn.addEventListener("click", () => {
        if (state.currentPage > 1) {
            state.currentPage--;
            renderTable();
        }
    });
    dom.paginationControls.appendChild(prevBtn);

    // Page numbers
    for (let i = 1; i <= totalPages; i++) {
        const pageBtn = document.createElement("button");
        pageBtn.className = `page-btn ${state.currentPage === i ? "active" : ""}`;
        pageBtn.textContent = i;
        pageBtn.addEventListener("click", () => {
            state.currentPage = i;
            renderTable();
        });
        dom.paginationControls.appendChild(pageBtn);
    }

    // Next Button
    const nextBtn = document.createElement("button");
    nextBtn.className = "page-btn";
    nextBtn.innerHTML = '<i class="fa-solid fa-chevron-left"></i>';
    nextBtn.disabled = state.currentPage === totalPages;
    nextBtn.addEventListener("click", () => {
        if (state.currentPage < totalPages) {
            state.currentPage++;
            renderTable();
        }
    });
    dom.paginationControls.appendChild(nextBtn);
}

// -------------------------------------------------------------
// 9. Status Toggle
// -------------------------------------------------------------
window.toggleCustomerStatus = function(id, currentStatus) {
    const newStatus = currentStatus === 'active' ? 'suspended' : 'active';
    const label = newStatus === 'active' ? 'مفعّل' : 'معطّل';

    fetch('api/customers.php?action=toggle_status', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id, status: newStatus })
    })
    .then(r => r.json())
    .then(res => {
        if (res.status === 'success') {
            // Update local state
            const customer = state.customers.find(c => c.id == id);
            if (customer) customer.status = newStatus;
            showToast(`تم تغيير حالة الحساب إلى: ${label}`, newStatus === 'active' ? 'success' : 'warning');
            applyFilters();
            updateStats();
        } else {
            showToast(res.message || "فشل تحديث الحالة", "danger");
        }
    })
    .catch(err => {
        console.error(err);
        showToast("فشل الاتصال بالخادم", "danger");
    });
};

// -------------------------------------------------------------
// 10. Modals Open / Close Control
// -------------------------------------------------------------
window.openEditModal = function(id) {
    const customer = state.customers.find(c => c.id == id);
    if (!customer) return;

    clearValidationErrors();
    dom.modalTitle.textContent = "تعديل بيانات العميل";
    dom.customerIdInput.value = customer.id;
    dom.customerNameInput.value = customer.name;
    dom.customerPhoneInput.value = customer.phone || "";
    dom.customerStatusSelect.value = customer.status || "active";
    dom.customerNotesInput.value = customer.notes || "";

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

function openAddModal() {
    clearValidationErrors();
    dom.modalTitle.textContent = "إضافة عميل جديد";
    dom.customerForm.reset();
    dom.customerIdInput.value = "";
    dom.customerStatusSelect.value = "active";

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

function closeModal() {
    dom.customerModal.classList.remove("open");
    dom.customerForm.reset();
    clearValidationErrors();
}

window.openDeleteModal = function(id) {
    const customer = state.customers.find(c => c.id == id);
    if (!customer) return;

    state.deleteTargetId = id;
    dom.deleteItemName.textContent = customer.name;
    dom.deleteConfirmModal.classList.add("open");
};

function closeDeleteModal() {
    dom.deleteConfirmModal.classList.remove("open");
    state.deleteTargetId = null;
}

// -------------------------------------------------------------
// 11. Form Validation & Submission
// -------------------------------------------------------------
function clearValidationErrors() {
    document.querySelectorAll(".form-group").forEach(el => {
        el.classList.remove("has-error");
    });
}

function validateForm(name, phone) {
    let isValid = true;
    clearValidationErrors();

    // Validate Name (at least 3 characters)
    if (!name || name.trim().length < 3) {
        const nameInput = document.getElementById("customer-name");
        if (nameInput) nameInput.closest(".form-group").classList.add("has-error");
        isValid = false;
    }

    // Validate Phone: if provided, must start with 07 and be exactly 11 digits
    if (phone && phone.trim() !== "") {
        const phoneRegex = /^07[0-9]{9}$/;
        if (!phoneRegex.test(phone.trim())) {
            const phoneInput = document.getElementById("customer-phone");
            if (phoneInput) phoneInput.closest(".form-group").classList.add("has-error");
            isValid = false;
        }
    }

    return isValid;
}

function handleFormSubmit(e) {
    e.preventDefault();

    const id = dom.customerIdInput.value;
    const name = dom.customerNameInput.value.trim();
    const phone = dom.customerPhoneInput.value.trim();
    const status = dom.customerStatusSelect.value;
    const notes = dom.customerNotesInput.value.trim();

    if (!validateForm(name, phone)) {
        if (!name || name.trim().length < 3) {
            showToast("يرجى إدخال اسم الزبون بشكل صحيح (3 أحرف على الأقل)", "warning");
        } else {
            showToast("رقم الهاتف يجب أن يبدأ بـ 07 ويتكون من 11 رقماً", "warning");
        }
        return;
    }

    const saveBtn = document.getElementById("save-btn");
    if (saveBtn) {
        saveBtn.disabled = true;
        saveBtn.querySelector("span").textContent = "جاري الحفظ...";
    }

    fetch('api/customers.php?action=save', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id, name, phone, status, notes })
    })
    .then(r => r.json())
    .then(res => {
        if (res.status === 'success') {
            showToast(res.message || "تم حفظ البيانات بنجاح");
            closeModal();
            loadData();
        } else {
            showToast(res.message || "فشل حفظ البيانات", "danger");
        }
    })
    .catch(err => {
        console.error(err);
        showToast("فشل الاتصال بالخادم لحفظ البيانات", "danger");
    })
    .finally(() => {
        if (saveBtn) {
            saveBtn.disabled = false;
            saveBtn.querySelector("span").textContent = "حفظ البيانات";
        }
    });
}

// -------------------------------------------------------------
// 12. Delete Execution
// -------------------------------------------------------------
function handleDeleteConfirm() {
    if (!state.deleteTargetId) return;

    const id = state.deleteTargetId;

    fetch('api/customers.php?action=delete', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id })
    })
    .then(r => r.json())
    .then(res => {
        if (res.status === 'success') {
            showToast("تم حذف العميل بنجاح", "danger");
            closeDeleteModal();
            loadData();
        } else {
            showToast(res.message || "فشل حذف العميل", "danger");
        }
    })
    .catch(err => {
        console.error(err);
        showToast("فشل الاتصال بالخادم لحذف البيانات", "danger");
    });
}

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

// -------------------------------------------------------------
// 14. Event Listeners Setup
// -------------------------------------------------------------
function setupEventListeners() {
    if (dom.openAddModalBtn) dom.openAddModalBtn.addEventListener("click", openAddModal);
    if (dom.emptyStateAddBtn) dom.emptyStateAddBtn.addEventListener("click", openAddModal);

    if (dom.closeModalBtn) dom.closeModalBtn.addEventListener("click", closeModal);
    if (dom.cancelModalBtn) dom.cancelModalBtn.addEventListener("click", closeModal);
    if (dom.cancelDeleteBtn) dom.cancelDeleteBtn.addEventListener("click", closeDeleteModal);

    if (dom.confirmDeleteBtn) dom.confirmDeleteBtn.addEventListener("click", handleDeleteConfirm);

    if (dom.customerForm) dom.customerForm.addEventListener("submit", handleFormSubmit);

    // Enforce maxlength=11 and numeric-only input on phone field
    if (dom.customerPhoneInput) {
        dom.customerPhoneInput.setAttribute("maxlength", "11");
        dom.customerPhoneInput.setAttribute("inputmode", "numeric");
        dom.customerPhoneInput.setAttribute("pattern", "07[0-9]{9}");
        dom.customerPhoneInput.addEventListener("input", () => {
            // Remove any non-digit characters
            dom.customerPhoneInput.value = dom.customerPhoneInput.value.replace(/[^0-9]/g, "");
            // Enforce max 11 chars
            if (dom.customerPhoneInput.value.length > 11) {
                dom.customerPhoneInput.value = dom.customerPhoneInput.value.slice(0, 11);
            }
        });
    }

    if (dom.searchInput) {
        dom.searchInput.addEventListener("input", () => {
            state.currentPage = 1;
            applyFilters();
        });
    }

    if (dom.searchBtn) {
        dom.searchBtn.addEventListener("click", () => {
            state.currentPage = 1;
            applyFilters();
        });
    }

    if (dom.searchClearBtn) {
        dom.searchClearBtn.addEventListener("click", () => {
            if (dom.searchInput) dom.searchInput.value = "";
            if (dom.searchResultsBadge) dom.searchResultsBadge.style.display = "none";
            state.currentPage = 1;
            applyFilters();
        });
    }

    if (dom.entriesSelect) {
        dom.entriesSelect.addEventListener("change", () => {
            state.currentPage = 1;
            applyFilters();
        });
    }

    if (dom.themeToggle) dom.themeToggle.addEventListener("click", toggleTheme);

    window.addEventListener("click", (e) => {
        if (e.target === dom.customerModal) closeModal();
        if (e.target === dom.deleteConfirmModal) closeDeleteModal();
    });

    window.addEventListener("keydown", (e) => {
        if (e.key === "Escape") {
            closeModal();
            closeDeleteModal();
        }
    });
}

// -------------------------------------------------------------
// 15. Export Functions
// -------------------------------------------------------------
window.doExportExcel = function() {
    if (state.customers.length === 0) {
        showToast("لا توجد بيانات لتصديرها", "warning");
        return;
    }

    let csvContent = "\uFEFF";
    csvContent += "التسلسل,اسم الزبون,رقم الهاتف,عدد الاستمارات المسجلة,حالة الحساب,ملاحظات,تاريخ التسجيل\n";

    state.customers.forEach((customer, index) => {
        const serial = index + 1;
        const name = `"${(customer.name || "").replace(/"/g, '""')}"`;
        const phone = `"${(customer.phone || "").replace(/"/g, '""')}"`;
        const formsCount = customer.formsCount || 0;
        const status = customer.status === 'active' ? 'مفعّل' : 'معطّل';
        const notes = `"${(customer.notes || "").replace(/"/g, '""')}"`;
        const date = `"${(customer.createdAt || "").replace(/"/g, '""')}"`;

        csvContent += `${serial},${name},${phone},${formsCount},${status},${notes},${date}\n`;
    });

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

window.exportExcel = window.doExportExcel;

window.doExportPDF = function() {
    const printWindow = window.open('', '_blank');
    const tableHtml = document.getElementById('customers-table').outerHTML;

    printWindow.document.write(`
        <html lang="ar" dir="rtl">
        <head>
            <title>طباعة قائمة العملاء</title>
            <link href="css/cairo.css" rel="stylesheet">
            <style>
                body { font-family: 'Cairo', sans-serif; padding: 20px; background: #fff; color: #000; }
                h2 { text-align: center; margin-bottom: 20px; }
                table { width: 100%; border-collapse: collapse; margin-top: 10px; }
                th, td { border: 1px solid #ddd; padding: 10px; text-align: right; font-size: 13px; }
                th { background-color: #f4f6f9; font-weight: 700; }
                /* Hide Actions Column */
                th:last-child, td:last-child { display: none; }
            </style>
        </head>
        <body onload="window.print(); window.close();">
            <h1 style="text-align:center; font-size:18px; margin:0 0 6px 0; color:#1e293b;">${getOrgName()}</h1>
            <h2>قائمة العملاء المسجلين</h2>
            ${tableHtml}
        </body>
        </html>
    `);
    printWindow.document.close();
};

window.exportPDF  = window.doExportPDF;

window.printTable = function() {
    const list = state.filteredCustomers;
    if (list.length === 0) {
        showToast("لا توجد بيانات عملاء لطباعتها", "warning");
        return;
    }

    let rowsHtml = list.map((c, idx) => {
        const statusText = c.status === 'active' ? 'مفعّل' : 'معطّل';
        return `
            <tr>
                <td>${idx + 1}</td>
                <td>${escapeHTML(c.name)}</td>
                <td>${c.phone || '—'}</td>
                <td>${c.formsCount || 0} استمارة</td>
                <td>${statusText}</td>
                <td>${c.notes || '—'}</td>
            </tr>
        `;
    }).join("");

    const printWin = window.open("", "_blank");
    printWin.document.write(`
        <html lang="ar" dir="rtl">
        <head>
            <title>تقرير قائمة العملاء والزبائن المسجلين</title>
            <link href="css/cairo.css" rel="stylesheet">
            <style>
                body { font-family: 'Cairo', sans-serif; padding: 20px; text-align: right; }
                table { width: 100%; border-collapse: collapse; margin-top: 15px; }
                th, td { border: 1px solid #ccc; padding: 8px 12px; text-align: right; font-size: 13px; }
                th { background: #f3f4f6; font-weight: 700; }
                .header { text-align: center; margin-bottom: 20px; border-bottom: 2px solid #000; padding-bottom: 10px; }
            </style>
        </head>
        <body>
            <div class="header">
                <h1 style="font-size:18px; margin:0 0 6px 0; color:#1e293b; text-align:center;">${getOrgName()}</h1>
                <h2>تقرير كشف أسماء العملاء المسجلين بالمنظومة</h2>
                <p>تاريخ الطباعة: ${new Date().toLocaleDateString('ar-EG')} - إجمالي العملاء: ${list.length}</p>
            </div>
            <table>
                <thead>
                    <tr>
                        <th>التسلسل</th>
                        <th>اسم الزبون</th>
                        <th>رقم الهاتف</th>
                        <th>عدد الاستمارات</th>
                        <th>حالة الحساب</th>
                        <th>ملاحظات</th>
                    </tr>
                </thead>
                <tbody>
                    ${rowsHtml}
                </tbody>
            </table>
        </body>
        </html>
    `);
    printWin.document.close();
    printWin.focus();
    setTimeout(() => { printWin.print(); }, 500);
};

// -------------------------------------------------------------
// 16. Customer Statement & Debt Overview Modal Logic
// -------------------------------------------------------------
window.openCustomerStatement = function(customerId) {
    const customer = state.customers.find(c => String(c.id) === String(customerId));
    if (!customer) {
        showToast("لم يتم العثور على بيانات العميل", "warning");
        return;
    }

    const customerName = customer.name;
    const modal = document.getElementById("customer-statement-modal");
    const nameEl = document.getElementById("stmt-customer-name");
    const phoneEl = document.getElementById("stmt-customer-phone");
    const formsValEl = document.getElementById("stmt-total-forms-val");
    const paidValEl = document.getElementById("stmt-total-paid-val");
    const remDebtEl = document.getElementById("stmt-remaining-debt-val");
    const tbody = document.getElementById("stmt-table-tbody");

    const targetName = customerName;
    if (nameEl) nameEl.textContent = targetName;
    if (phoneEl) phoneEl.textContent = customer.phone ? customer.phone : "غير مسجل";
    if (tbody) tbody.innerHTML = `<tr><td colspan="5" style="text-align:center; padding:15px; color:var(--text-muted);"><i class="fa-solid fa-spinner fa-spin" style="margin-left:6px;"></i>جاري تحميل كشف الحساب والديون...</td></tr>`;
    if (modal) modal.classList.add("open");

    Promise.all([
        fetch('api/forms.php?action=list').then(r => r.json()).catch(() => null),
        fetch('api/debts.php?action=list_debtors').then(r => r.json()).catch(() => null)
    ]).then(([formRes, debtRes]) => {
        let totalFormsVal = 0;
        let totalPaidVal = 0;
        let remainingDebt = 0;
        let rows = [];

        // 1. Check forms
        if (formRes && formRes.status === 'success' && formRes.data) {
            const customerForms = formRes.data.filter(f => 
                f.customerName && f.customerName.trim().toLowerCase() === targetName.trim().toLowerCase() && f.status !== 'cancelled'
            );

            customerForms.forEach((f, idx) => {
                const total = parseFloat(f.grandTotal || 0);
                const paid = parseFloat(f.totalPaid || 0);
                totalFormsVal += total;
                totalPaidVal += paid;

                rows.push({
                    number: `#${f.id}`,
                    type: 'استمارة شراء',
                    date: (f.createdAt || '').substring(0, 10),
                    amount: total,
                    isForm: true,
                    details: `قيمة الفاتورة: ${total.toLocaleString('ar-EG')} د.ع (المحَصّل منها: ${paid.toLocaleString('ar-EG')} د.ع)`
                });
            });
        }

        // 2. Check debtors
        if (debtRes && debtRes.status === 'success' && debtRes.debtors) {
            const debtor = debtRes.debtors.find(d => 
                d.name && d.name.trim().toLowerCase() === targetName.trim().toLowerCase()
            );

            if (debtor) {
                if (debtor.balance !== undefined) {
                    remainingDebt = parseFloat(debtor.balance || 0);
                }
                if (debtor.totalRepaid) {
                    totalPaidVal = Math.max(totalPaidVal, parseFloat(debtor.totalRepaid || 0));
                }

                // Add repayment items from debtor if any
                if (debtor.items && Array.isArray(debtor.items)) {
                    debtor.items.forEach(it => {
                        if (it.status === 'manual' || it.status === 'repayment' || it.status === 'balance') {
                            rows.push({
                                number: `#${it.formNumber || 'حركة'}`,
                                type: 'سداد / قيد دين',
                                date: it.formDate || '',
                                amount: parseFloat(it.totalAmount || 0),
                                isForm: false,
                                details: `المبلغ الكلي: ${(parseFloat(it.totalAmount || 0)).toLocaleString('ar-EG')} د.ع (المسدد: ${(parseFloat(it.totalPaid || 0)).toLocaleString('ar-EG')} د.ع)`
                            });
                        }
                    });
                }
            }
        }

        if (remainingDebt === 0 && totalFormsVal > totalPaidVal) {
            remainingDebt = totalFormsVal - totalPaidVal;
        }

        if (formsValEl) formsValEl.textContent = `${totalFormsVal.toLocaleString('ar-EG')} د.ع`;
        if (paidValEl) paidValEl.textContent = `${totalPaidVal.toLocaleString('ar-EG')} د.ع`;
        if (remDebtEl) remDebtEl.textContent = `${remainingDebt.toLocaleString('ar-EG')} د.ع`;

        if (!tbody) return;
        if (rows.length === 0) {
            tbody.innerHTML = `<tr><td colspan="5" style="text-align:center; padding:15px; color:var(--text-muted);">لا توجد استمارات أو حركات ديون مسجلة باسم هذا العميل حتى الآن</td></tr>`;
            return;
        }

        tbody.innerHTML = rows.map(r => `
            <tr style="border-bottom: 1px solid var(--border-color);">
                <td style="padding: 8px 12px; font-weight:700;">${r.number}</td>
                <td style="padding: 8px 12px;">${r.type}</td>
                <td style="padding: 8px 12px;">${r.date}</td>
                <td style="padding: 8px 12px; text-align:center; font-weight:700; color:${r.isForm ? 'var(--primary)' : 'var(--success)'};">${Number(r.amount).toLocaleString('ar-EG')} د.ع</td>
                <td style="padding: 8px 12px;">${r.details}</td>
            </tr>
        `).join("");
    });
};

window.closeCustomerStatementModal = function() {
    const modal = document.getElementById("customer-statement-modal");
    if (modal) modal.classList.remove("open");
};

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 || settings.company_name || "مكتب الحاج أمجد سهل عبدالامير";
}

