<script>
const IS_PRESSURE_HIGH = <?= (isset($financeAnalysis) && $financeAnalysis['pressure_score']['level'] === 'high') ? 'true' : 'false' ?>;

function checkImpulsiveExpense(event, formElement) {
    if (IS_PRESSURE_HIGH) {
        // If it's the first time clicking, block it
        if (!formElement.dataset.impulseChecked) {
            event.preventDefault();
            
            const btn = formElement.querySelector('button[type="submit"]');
            const amount = formElement.querySelector('input[name="amount"]').value || '';
            const originalHtml = btn.innerHTML;
            
            btn.innerHTML = '<i class="fa-solid fa-hand"></i> توقف! الضغط المالي مرتفع. (انتظر 5 ثواني)';
            btn.classList.replace('btn-danger', 'btn-warning');
            btn.classList.add('text-dark');
            btn.disabled = true;
            
            setTimeout(() => {
                btn.innerHTML = '<i class="fa-solid fa-triangle-exclamation"></i> نعم، أنا متأكد (مخاطرة)';
                btn.classList.replace('btn-warning', 'btn-dark');
                btn.classList.replace('text-dark', 'text-white');
                btn.disabled = false;
                formElement.dataset.impulseChecked = 'true';
            }, 5000); // 5 seconds punishment/cooling-off period
            
            return false;
        }
    }
    
    // Normal Submission
    const btn = formElement.querySelector('button[type="submit"]');
    if(btn) {
        btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> جاري التنفيذ...';
        btn.classList.add('disabled');
    }
    return true;
}

function openDebtPay(id, remaining) {
    document.getElementById('pay_debt_id').value = id;
    document.getElementById('pay_debt_remaining').innerText = remaining.toLocaleString();
    document.getElementById('pay_debt_amount').max = remaining;
    document.getElementById('pay_debt_amount').value = remaining;
    
    if(typeof bootstrap !== 'undefined'){
       new bootstrap.Modal(document.getElementById('debtPaymentModal')).show();
    }
}
// JSON string array manipulation for Installments
function updatePaidJson(insId) {
    const checkboxes = document.querySelectorAll('.check-month-ins-' + insId);
    let paidArray = [];
    checkboxes.forEach(cb => {
        if(cb.checked) {
            paidArray.push(parseInt(cb.getAttribute('data-month')));
        }
    });
    // Set hidden input value
    document.getElementById('jsonStr' + insId).value = JSON.stringify(paidArray);
}

// Add tiny loaders on buttons when submitting
document.querySelectorAll('.loader-form').forEach(form => {
    form.addEventListener('submit', function() {
        if(this.checkValidity()) {
            const btn = this.querySelector('button[type="submit"]');
            if(btn) {
                const originalHTML = btn.innerHTML;
                btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> جاري التنفيذ...';
                btn.classList.add('disabled');
            }
        }
    });
});

// Toggle Fund selector visibility based on type
function toggleFundSelector() {
    const type = document.getElementById('catType').value;
    const fundWrapper = document.getElementById('catFundWrapper');
    if (type === 'expense') {
        fundWrapper.style.display = '';
    } else {
        fundWrapper.style.display = 'none';
    }
}

// Category AJAX Flow
const FUND_LABELS = { personal: 'شخصي', business: 'عمل', savings: 'ادخار', charity: 'صدقات' };

async function refreshCategoriesDOM(income, expense) {
    const incList = document.getElementById('listIncomeCats');
    const expList = document.getElementById('listExpenseCats');
    
    incList.innerHTML = income.map(c => {
        const color = c.color || '#6366f1';
        return `<li class="list-group-item d-flex justify-content-between align-items-center px-2 py-2 bg-transparent border-0">
           <div class="d-flex align-items-center gap-2">
               <span class="rounded-circle d-inline-block flex-shrink-0" style="width:12px;height:12px;background:${color};"></span>
               <span class="fw-semibold small">${c.name}</span>
           </div>
           <a href="javascript:void(0)" class="btn btn-sm btn-light text-danger border-0 opacity-75" onclick="deleteCategory(${c.id})"><i class="fa-solid fa-times"></i></a>
       </li>`;
    }).join('');
       
    expList.innerHTML = expense.map(c => {
        const color = c.color || '#6366f1';
        const fundLabel = FUND_LABELS[c.linked_fund] || 'شخصي';
        return `<li class="list-group-item d-flex justify-content-between align-items-center px-2 py-2 bg-transparent border-0">
           <div class="d-flex align-items-center gap-2">
               <span class="rounded-circle d-inline-block flex-shrink-0" style="width:12px;height:12px;background:${color};"></span>
               <span class="fw-semibold small">${c.name}</span>
               <span class="badge rounded-pill" style="background: ${color}22; color: ${color}; font-size: 0.65rem;">${fundLabel}</span>
           </div>
           <a href="javascript:void(0)" class="btn btn-sm btn-light text-danger border-0 opacity-75" onclick="deleteCategory(${c.id})"><i class="fa-solid fa-times"></i></a>
       </li>`;
    }).join('');

    const incSelect = document.querySelector('select[name="source"]');
    const expSelect = document.querySelector('select[name="category"]');
    
    if(incSelect) {
        incSelect.innerHTML = '<option value="" disabled selected>اختر المصدر...</option>' + 
                              income.map(c => `<option value="${c.name}">${c.name}</option>`).join('');
    }
    if(expSelect) {
         expSelect.innerHTML = '<option value="" disabled selected>اختر التصنيف...</option>' + 
                              expense.map(c => `<option value="${c.name}">${c.name}</option>`).join('');
    }
}

// Inline delete confirmation logic
let _pendingDeleteId = null;

function deleteCategory(id) {
    _pendingDeleteId = id;
    const bar = document.getElementById('catDeleteConfirm');
    bar.classList.remove('d-none');
    // Scroll the modal body to the top so the bar is visible
    const modalBody = document.querySelector('#categoriesModal .modal-body');
    if (modalBody) modalBody.scrollTop = 0;
    // Wire up confirm button
    document.getElementById('catDeleteConfirmBtn').onclick = executeCategoryDelete;
}

function cancelDeleteCategory() {
    _pendingDeleteId = null;
    document.getElementById('catDeleteConfirm').classList.add('d-none');
}

async function executeCategoryDelete() {
    if (!_pendingDeleteId) return;
    const id = _pendingDeleteId;
    _pendingDeleteId = null;
    document.getElementById('catDeleteConfirm').classList.add('d-none');

    const csrf = document.getElementById('catCsrf').value;
    const errorDiv = document.getElementById('catErrorAlert');

    const formData = new FormData();
    formData.append('action', 'delete');
    formData.append('id', id);
    formData.append('csrf_token', csrf);

    try {
        const res = await fetch('<?= BASE_URL ?>/finance/apiManageCategory', { method: 'POST', body: formData });
        const text = await res.text();
        let data;
        try { data = JSON.parse(text); } catch(jsonErr) {
            errorDiv.textContent = 'خطأ أثناء الحذف — حدّث الصفحة وحاول مرة أخرى.';
            errorDiv.classList.remove('d-none');
            return;
        }
        if(data.success) {
            refreshCategoriesDOM(data.income, data.expense);
        } else {
            errorDiv.textContent = data.message || 'فشل الحذف.';
            errorDiv.classList.remove('d-none');
        }
    } catch(err) {
        errorDiv.textContent = 'تعذّر الاتصال بالخادم.';
        errorDiv.classList.remove('d-none');
    }
}

async function submitCategory(e) {
    e.preventDefault();
    const type = document.getElementById('catType').value;
    const name = document.getElementById('catName').value.trim();
    const color = document.getElementById('catColor').value;
    const linkedFund = document.getElementById('catFund').value;
    const csrf = document.getElementById('catCsrf').value;
    const btn = document.getElementById('catSubmitBtn');
    const errorDiv = document.getElementById('catErrorAlert');

    if (!name) { errorDiv.textContent = 'يرجى كتابة اسم التصنيف.'; errorDiv.classList.remove('d-none'); return; }
    errorDiv.classList.add('d-none');
    
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> جاري...';

    const formData = new FormData();
    formData.append('action', 'add');
    formData.append('type', type);
    formData.append('name', name);
    formData.append('linked_fund', linkedFund);
    formData.append('color', color);
    formData.append('csrf_token', csrf);

    try {
        const res = await fetch('<?= BASE_URL ?>/finance/apiManageCategory', { method: 'POST', body: formData });
        const text = await res.text();
        let data;
        try { data = JSON.parse(text); } catch(jsonErr) {
            errorDiv.textContent = 'خطأ في الاستجابة — تأكد من صلاحية الجلسة وحدّث الصفحة.';
            errorDiv.classList.remove('d-none');
            btn.disabled = false; btn.innerHTML = '<i class="fa-solid fa-plus me-1"></i> إضافة';
            return;
        }
        if(data.success) {
            refreshCategoriesDOM(data.income, data.expense);
            document.getElementById('catName').value = '';
            document.getElementById('catColor').value = '#6366f1';
        } else {
            errorDiv.textContent = data.message || 'حدث خطأ أثناء الحفظ.';
            errorDiv.classList.remove('d-none');
        }
    } catch(err) {
        errorDiv.textContent = 'تعذّر الاتصال بالخادم. حاول مرة أخرى.';
        errorDiv.classList.remove('d-none');
    }
    
    btn.disabled = false;
    btn.innerHTML = '<i class="fa-solid fa-plus me-1"></i> إضافة';
}

// (duplicate deleteCategory removed — using inline confirmation version above)

async function fetchPaginatedTransactions(type, page) {
    const container = document.getElementById(type + 'TableContainer');
    if(!container) return;
    
    // Add loading spinner
    container.innerHTML = '<div class="text-center py-4"><span class="spinner-border text-primary"></span></div>';
    
    try {
        const response = await fetch(`<?= BASE_URL ?>/finance/apiPaginateList?type=${type}&page=${page}`);
        const html = await response.text();
        container.innerHTML = html;
    } catch(err) {
        container.innerHTML = '<div class="alert alert-danger text-center py-4">حدث خطأ أثناء الاتصال. برجاء المحاولة مرة أخرى.</div>';
    }
}
</script>

<!-- FINANCE INTELLIGENCE SCRIPTS -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 1. Line Chart (Unified Timeline)
    const lineCtx = document.getElementById('financeLineChart');
    if (lineCtx) {
        const timelineData = <?= json_encode($financeAnalysis['timeline'] ?? []) ?>;
        
        if (timelineData.length > 0) {
            new Chart(lineCtx, {
                type: 'line',
                data: {
                    labels: timelineData.map(d => d.date),
                    datasets: [
                    {
                        label: 'المصروفات (ج.م)',
                        data: timelineData.map(d => d.outflow),
                        borderColor: '#ef4444',
                        backgroundColor: 'rgba(239, 68, 68, 0.1)',
                        borderWidth: 2,
                        tension: 0.4,
                        fill: true,
                    },
                    {
                        label: 'الموارد والدخل (ج.م)',
                        data: timelineData.map(d => d.inflow),
                        borderColor: '#22c55e',
                        backgroundColor: 'rgba(34, 197, 94, 0.1)',
                        borderWidth: 2,
                        tension: 0.4,
                        fill: true,
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: { legend: { position: 'top', labels: { usePointStyle: true, font: { family: 'Cairo' } } } },
                    scales: { 
                        y: { beginAtZero: true, grid: { borderDash: [5, 5] } },
                        x: { grid: { display: false } }
                    }
                }
            });
        }
    }

    // 2. Pie Chart (Categories)
    const pieCtx = document.getElementById('financePieChart');
    if (pieCtx) {
        const catData = <?= json_encode($financeAnalysis['categories'] ?? []) ?>;
        
        if (catData.length > 0) {
            new Chart(pieCtx, {
                type: 'doughnut',
                data: {
                    labels: catData.map(c => c.name),
                    datasets: [{
                        data: catData.map(c => c.total),
                        backgroundColor: ['#3b82f6', '#f59e0b', '#10b981', '#ef4444', '#8b5cf6', '#06b6d4', '#ec4899', '#64748b'],
                        borderWidth: 0,
                        hoverOffset: 4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    cutout: '70%',
                    plugins: {
                        legend: { position: 'bottom', labels: { usePointStyle: true, padding: 20, font: { family: 'Cairo' } } }
                    }
                }
            });
        }
    }
});
</script>

