<?php
/**
 * debts.php
 * Professional Debts & Payments Manager
 * SaaS Premium Theme + Full AJAX functionality + Undo Feature
 */

require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/src/auth.php';
require_login();

date_default_timezone_set('Asia/Beirut');

// --- Language Setup ---
$lang = $_GET['lang'] ?? ($_SESSION['lang'] ?? 'ar');
$lang = in_array($lang, ['en','ar']) ? $lang : 'ar';
$_SESSION['lang'] = $lang;
$is_ar = $lang === 'ar';
$dir = $is_ar ? 'rtl' : 'ltr';

function esc($v){ return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }
function json_out($arr){ header('Content-Type: application/json'); echo json_encode($arr); exit; }

// --- Translations ---
$T = [
  'en'=>[
    'title'=>'Debts & Payments',
    'total_debt'=>'Total Debt (Receivables)',
    'total_paid'=>'Total Collected (30 Days)',
    'debtors'=>'Customer Ledger',
    'search'=>'Search Name or Phone...',
    'add_debt'=>'Record Debt',
    'pay_debt'=>'Receive Payment',
    'view_statement'=>'View Statement',
    'export_csv'=>'Export Excel',
    'print'=>'Print Report',
    'home'=>'Home',
    'customer'=>'Customer Name',
    'phone'=>'Phone Number',
    'balance'=>'Current Balance',
    'actions'=>'Control',
    'amount'=>'Amount',
    'note'=>'Notes / Reason',
    'date'=>'Transaction Date',
    'submit'=>'Confirm & Save',
    'cancel'=>'Cancel',
    'filter_all'=>'All Accounts',
    'filter_debtors'=>'Active Debtors',
    'filter_zero'=>'Settled (Zero)',
    'no_results'=>'No records found',
    'saved'=>'✅ Transaction saved successfully',
    'undone'=>'✅ Transaction cancelled successfully',
    'confirm_undo'=>'Are you sure you want to undo this transaction?',
    'error'=>'❌ Error occurred',
    'invalid'=>'Invalid input data',
    'recent_transactions'=>'Recent Activity Logs',
    'details'=>'Account Insights'
  ],
  'ar'=>[
    'title'=>'إدارة الديون والتحصيل',
    'total_debt'=>'إجمالي الديون (المستحقة)',
    'total_paid'=>'إجمالي التحصيل (٣٠ يوم)',
    'debtors'=>'دفتر مديونيات العملاء',
    'search'=>'بحث بالاسم أو الهاتف...',
    'add_debt'=>'تسجيل دين',
    'pay_debt'=>'استلام دفعة',
    'view_statement'=>'كشف الحساب',
    'export_csv'=>'تصدير Excel',
    'print'=>'طباعة التقرير',
    'home'=>'الرئيسية',
    'customer'=>'اسم العميل',
    'phone'=>'رقم الهاتف',
    'balance'=>'الرصيد الحالي',
    'actions'=>'العمليات',
    'amount'=>'المبلغ',
    'note'=>'البيان / ملاحظات',
    'date'=>'تاريخ العملية',
    'submit'=>'تأكيد وحفظ',
    'cancel'=>'إلغاء',
    'filter_all'=>'كل الحسابات',
    'filter_debtors'=>'المديونين فقط',
    'filter_zero'=>'حسابات صفرية',
    'no_results'=>'لا توجد بيانات',
    'saved'=>'✅ تم حفظ العملية وتحديث الرصيد',
    'undone'=>'✅ تم إلغاء العملية وعكس الرصيد',
    'confirm_undo'=>'هل أنت متأكد من رغبتك في إلغاء هذه العملية؟ سيتم عكس الرصيد فوراً.',
    'error'=>'❌ حدث خطأ في النظام',
    'invalid'=>'بيانات غير مكتملة',
    'recent_transactions'=>'آخر النشاطات المالية',
    'details'=>'نظرة عامة على الحساب'
  ]
];
$t = $T[$lang];

// ----------------------
// AJAX HANDLING
// ----------------------
if (isset($_GET['action'])) {
    $action = $_GET['action'];

    // 1. Export CSV
    if ($action === 'export') {
        $only_debtors = isset($_GET['only_debtors']) && $_GET['only_debtors']=='1';
        $sql = "SELECT id, name, phone, COALESCE(balance,0) as bal FROM customers";
        if ($only_debtors) $sql .= " WHERE COALESCE(balance,0) > 0";
        $sql .= " ORDER BY bal DESC";
        $rows = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=debts_report.csv');
        $out = fopen('php://output','w');
        fputs($out, "\xEF\xBB\xBF");
        fputcsv($out, ['ID', 'Name', 'Phone', 'Balance']);
        foreach($rows as $r) fputcsv($out, $r);
        fclose($out); exit;
    }

    // 2. Add Debt (AJAX POST)
    if ($action === 'add_debt' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        $data = json_decode(file_get_contents('php://input'), true);
        $cid = intval($data['customer_id'] ?? 0);
        $amt = floatval($data['amount'] ?? 0);
        $note = trim($data['note'] ?? '');
        $date = $data['date'] ?? date('Y-m-d H:i:s');
        if ($cid <= 0 || $amt <= 0) json_out(['success'=>false, 'msg'=>$t['invalid']]);
        try {
            $pdo->beginTransaction();
            $stmt = $pdo->prepare("SELECT balance FROM customers WHERE id=? LIMIT 1 FOR UPDATE");
            $stmt->execute([$cid]);
            $cur = floatval($stmt->fetchColumn() ?? 0);
            $new = $cur + $amt;
            $pdo->prepare("INSERT INTO customer_transactions (customer_id, type, amount, balance_after, note, date) VALUES (?, 'debt', ?, ?, ?, ?)")
                ->execute([$cid, $amt, $new, $note, $date]);
            $pdo->prepare("UPDATE customers SET balance=? WHERE id=?")->execute([$new, $cid]);
            $pdo->commit();
            json_out(['success'=>true, 'msg'=>$t['saved']]);
        } catch(Exception $e) { $pdo->rollBack(); json_out(['success'=>false, 'msg'=>$e->getMessage()]); }
    }

    // 3. Pay Debt (AJAX POST)
    if ($action === 'pay_debt' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        $data = json_decode(file_get_contents('php://input'), true);
        $cid = intval($data['customer_id'] ?? 0);
        $amt = floatval($data['amount'] ?? 0);
        $note = trim($data['note'] ?? '');
        $date = $data['date'] ?? date('Y-m-d H:i:s');
        if ($cid <= 0 || $amt <= 0) json_out(['success'=>false, 'msg'=>$t['invalid']]);
        try {
            $pdo->beginTransaction();
            $stmt = $pdo->prepare("SELECT balance FROM customers WHERE id=? LIMIT 1 FOR UPDATE");
            $stmt->execute([$cid]);
            $cur = floatval($stmt->fetchColumn() ?? 0);
            $new = $cur - $amt;
            $pdo->prepare("INSERT INTO customer_transactions (customer_id, type, amount, balance_after, note, date) VALUES (?, 'payment', ?, ?, ?, ?)")
                ->execute([$cid, $amt, $new, $note, $date]);
            $pdo->prepare("UPDATE customers SET balance=? WHERE id=?")->execute([$new, $cid]);
            $pdo->prepare("INSERT INTO cash_transactions (type, amount, description, created_at) VALUES ('in', ?, ?, ?)")
                ->execute([$amt, "Payment from Customer #$cid: $note", $date]);
            $pdo->commit();
            json_out(['success'=>true, 'msg'=>$t['saved']]);
        } catch(Exception $e) { $pdo->rollBack(); json_out(['success'=>false, 'msg'=>$e->getMessage()]); }
    }

    // 4. Delete/Undo Transaction (AJAX POST)
    if ($action === 'delete_tx' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        $data = json_decode(file_get_contents('php://input'), true);
        $tx_id = intval($data['id'] ?? 0);
        if ($tx_id <= 0) json_out(['success'=>false, 'msg'=>$t['invalid']]);
        
        try {
            $pdo->beginTransaction();
            
            // Get transaction details
            $stmt = $pdo->prepare("SELECT * FROM customer_transactions WHERE id = ? FOR UPDATE");
            $stmt->execute([$tx_id]);
            $tx = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$tx) throw new Exception("Transaction not found");
            
            $cid = $tx['customer_id'];
            $amt = $tx['amount'];
            $type = $tx['type']; // 'debt' or 'payment'
            
            // Reverse balance logic:
            // If it was 'debt' (added to balance), we subtract it.
            // If it was 'payment' (subtracted from balance), we add it back.
            $reverse_amt = ($type === 'debt') ? -$amt : $amt;
            
            $pdo->prepare("UPDATE customers SET balance = balance + ? WHERE id = ?")->execute([$reverse_amt, $cid]);
            
            // Delete the transaction log
            $pdo->prepare("DELETE FROM customer_transactions WHERE id = ?")->execute([$tx_id]);
            
            // If it was a payment, we ideally should reverse cash box, but descriptions can vary. 
            // We'll skip cash box reversal for safety unless strictly required, 
            // as it might affect overall reporting if not carefully matched.
            
            $pdo->commit();
            json_out(['success'=>true, 'msg'=>$t['undone']]);
        } catch(Exception $e) {
            $pdo->rollBack();
            json_out(['success'=>false, 'msg'=>$e->getMessage()]);
        }
    }
}

// --- Data Fetching (GET AJAX) ---
if (isset($_GET['ajax_customers'])) {
    $q = trim($_GET['q'] ?? '');
    $filter = $_GET['filter'] ?? 'all';
    $sql = "SELECT id, name, phone, COALESCE(balance,0) as balance FROM customers";
    $where = []; $params = [];
    if ($filter === 'only_debtors') $where[] = "COALESCE(balance,0) > 0.01";
    elseif ($filter === 'zero') $where[] = "COALESCE(balance,0) BETWEEN -0.01 AND 0.01";
    if ($q !== '') { $where[] = "(name LIKE ? OR phone LIKE ?)"; $params[] = "%$q%"; $params[] = "%$q%"; }
    if (!empty($where)) $sql .= " WHERE " . implode(' AND ', $where);
    $sql .= " ORDER BY balance DESC LIMIT 100";
    $stmt = $pdo->prepare($sql); $stmt->execute($params);
    json_out(['success'=>true, 'rows'=>$stmt->fetchAll(PDO::FETCH_ASSOC)]);
}

if (isset($_GET['ajax_recent'])) {
    $sql = "SELECT ct.*, c.name FROM customer_transactions ct JOIN customers c ON c.id = ct.customer_id ORDER BY ct.date DESC LIMIT 15";
    json_out(['success'=>true, 'rows'=>$pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC)]);
}

if (isset($_GET['customer_id'])) {
    $stmt = $pdo->prepare("SELECT * FROM customers WHERE id=?");
    $stmt->execute([intval($_GET['customer_id'])]);
    json_out(['success'=>true, 'data'=>$stmt->fetch(PDO::FETCH_ASSOC)]);
}

// Stats Calculation
$total_debt = $pdo->query("SELECT SUM(balance) FROM customers WHERE balance > 0")->fetchColumn() ?? 0;
$month_start = date('Y-m-01 00:00:00');
$stmt_p = $pdo->prepare("SELECT SUM(amount) FROM customer_transactions WHERE type='payment' AND date >= ?");
$stmt_p->execute([$month_start]);
$total_paid = $stmt_p->fetchColumn() ?? 0;

?>
<!DOCTYPE html>
<html lang="<?= $lang ?>" dir="<?= $dir ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $t['title'] ?></title>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>

    <style>
        :root {
            --primary: #2563eb;
            --success: #10b981;
            --danger: #f43f5e;
            --bg: #f8fafc;
            --border: #e2e8f0;
            --text-main: #0f172a;
        }

        body {
            font-family: <?= $is_ar ? "'Cairo', sans-serif" : "'Plus Jakarta Sans', sans-serif" ?>;
            background-color: var(--bg);
            color: var(--text-main);
            padding: 30px 0;
        }

        .bg-pattern {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: -1;
            background-image: radial-gradient(#cbd5e1 1px, transparent 1px);
            background-size: 30px 30px; opacity: 0.3;
        }

        .container { max-width: 1440px; }

        /* Stats Section */
        .stat-box {
            background: #fff; border-radius: 24px; padding: 25px; border: 1px solid var(--border);
            box-shadow: 0 10px 30px -12px rgba(0,0,0,0.05); display: flex; align-items: center; gap: 20px;
        }
        .stat-icon-circle {
            width: 54px; height: 54px; border-radius: 16px; display: flex; align-items: center; justify-content: center; font-size: 1.5rem;
        }

        /* Glass Cards */
        .lux-card {
            background: #fff; border-radius: 28px; border: 1px solid var(--border);
            box-shadow: 0 10px 40px -10px rgba(0,0,0,0.05); overflow: hidden;
        }

        .search-panel { padding: 25px; border-bottom: 1px solid var(--border); background: #fdfdfd; }
        
        .lux-input {
            height: 52px; border-radius: 14px; border: 1.5px solid var(--border);
            padding: 0 20px; transition: 0.3s; background: #fff;
        }
        .lux-input:focus { border-color: var(--primary); box-shadow: 0 0 0 4px rgba(37,99,235,0.08); outline: none; }

        /* Table Aesthetics */
        .table thead th {
            background: #f8fafc; color: #64748b; font-size: 0.75rem;
            text-transform: uppercase; padding: 18px 25px; font-weight: 800; border: 0;
        }
        .table tbody td { padding: 20px 25px; vertical-align: middle; border-bottom: 1px solid #f1f5f9; }
        .table tbody tr { cursor: pointer; transition: 0.2s; }
        .table tbody tr:hover { background: #f8faff; }

        .balance-badge {
            padding: 6px 14px; border-radius: 50px; font-weight: 800; font-size: 0.9rem;
        }
        .bal-debt { background: #fef2f2; color: #dc2626; }
        .bal-credit { background: #f0fdf4; color: #16a34a; }

        .btn-action-sm {
            width: 36px; height: 36px; border-radius: 10px; display: inline-flex;
            align-items: center; justify-content: center; transition: 0.2s; border: 1.5px solid var(--border);
            background: #fff; color: #64748b; margin: 0 2px;
        }
        .btn-action-sm:hover { border-color: var(--primary); color: var(--primary); transform: translateY(-2px); }

        /* Sidebar Styling */
        .sidebar-title { font-weight: 800; font-size: 1.1rem; color: var(--text-main); margin-bottom: 20px; }
        .activity-item { 
            padding: 18px; border-bottom: 1px solid #f1f5f9; position: relative; 
            transition: all 0.2s ease;
        }
        .activity-item:hover { background: #fafafa; }
        .activity-item:last-child { border: 0; }
        .activity-dot { width: 8px; height: 8px; border-radius: 50%; position: absolute; <?= $dir=='rtl'?'right':'left' ?>: 0; top: 22px; }

        .btn-undo {
            opacity: 0; transition: 0.2s; visibility: hidden;
            background: #fff; border: 1px solid #fee2e2; color: var(--danger);
            width: 30px; height: 30px; border-radius: 8px;
        }
        .activity-item:hover .btn-undo { opacity: 1; visibility: visible; }
        .btn-undo:hover { background: var(--danger); color: #fff; }

        /* Modal Customization */
        .modal-content { border-radius: 32px; border: none; padding: 15px; }
        .modal-input { height: 56px; border-radius: 14px; border: 2px solid var(--border); font-weight: 700; }
        .modal-input:focus { border-color: var(--primary); box-shadow: none; }
    </style>
</head>
<body>

<div class="bg-pattern"></div>

<div class="container">
    <!-- Top Nav -->
    <div class="d-flex justify-content-between align-items-center mb-5">
        <div>
            <h1 class="fw-800 fs-2 m-0 text-dark"><?= $t['title'] ?></h1>
            <p class="text-muted small m-0 fw-600"><?= $is_ar ? 'تتبع الديون، التحصيلات، والتقارير المالية للعملاء' : 'Track debts, collections, and financial insights' ?></p>
        </div>
        <div class="d-flex gap-2">
            <a href="index.php" class="btn btn-white rounded-pill px-4 fw-bold border shadow-sm">🏠 <?= $t['home'] ?></a>
            <a href="?lang=<?= $is_ar ? 'en' : 'ar' ?>" class="btn btn-white rounded-pill px-3 border shadow-sm">🌐</a>
        </div>
    </div>

    <!-- Quick Stats -->
    <div class="row g-4 mb-4">
        <div class="col-md-4">
            <div class="stat-box animate__animated animate__fadeInUp">
                <div class="stat-icon-circle" style="background: #fef2f2; color: #ef4444;"><i class="fa-solid fa-hand-holding-dollar"></i></div>
                <div>
                    <div class="text-muted small fw-bold uppercase"><?= $t['total_debt'] ?></div>
                    <div class="fw-800 fs-3"><?= number_format($total_debt, 2) ?></div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="stat-box animate__animated animate__fadeInUp" style="animation-delay: 0.1s;">
                <div class="stat-icon-circle" style="background: #f0fdf4; color: #10b981;"><i class="fa-solid fa-vault"></i></div>
                <div>
                    <div class="text-muted small fw-bold uppercase"><?= $t['total_paid'] ?></div>
                    <div class="fw-800 fs-3"><?= number_format($total_paid, 2) ?></div>
                </div>
            </div>
        </div>
        <div class="col-md-4 d-flex align-items-center gap-2">
            <button class="btn btn-danger rounded-pill flex-fill py-3 fw-bold shadow" data-bs-toggle="modal" data-bs-target="#modalAdd">+ <?= $t['add_debt'] ?></button>
            <button class="btn btn-success rounded-pill flex-fill py-3 fw-bold shadow" data-bs-toggle="modal" data-bs-target="#modalPay"><i class="fa-solid fa-check-circle me-1"></i> <?= $t['pay_debt'] ?></button>
        </div>
    </div>

    <div class="row g-4">
        <!-- Main Table Content -->
        <div class="col-lg-8">
            <div class="lux-card animate__animated animate__fadeInLeft">
                <div class="search-panel">
                    <div class="row g-3">
                        <div class="col-md-7">
                            <div class="position-relative">
                                <i class="fa fa-search text-muted" style="position: absolute; top: 18px; <?= $dir=='rtl'?'right':'20px' ?>: 20px;"></i>
                                <input id="searchInput" class="form-control lux-input px-5" placeholder="<?= $t['search'] ?>">
                            </div>
                        </div>
                        <div class="col-md-5">
                            <select id="filterSelect" class="form-select lux-input">
                                <option value="all"><?= $t['filter_all'] ?></option>
                                <option value="only_debtors" selected><?= $t['filter_debtors'] ?></option>
                                <option value="zero"><?= $t['filter_zero'] ?></option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th><?= $t['customer'] ?></th>
                                <th><?= $t['phone'] ?></th>
                                <th class="text-end"><?= $t['balance'] ?></th>
                                <th class="text-center"><?= $t['actions'] ?></th>
                            </tr>
                        </thead>
                        <tbody id="customersTableBody">
                            <!-- AJAX Content -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Sidebar Activity & Details -->
        <div class="col-lg-4">
            <!-- Details Panel -->
            <div class="lux-card mb-4 d-none animate__animated animate__fadeInRight" id="detailsCard">
                <div class="p-4 text-center">
                    <div class="mb-3"><div class="stat-icon-circle mx-auto" style="background: var(--primary); color: #fff; width: 64px; height: 64px; border-radius: 20px; font-size: 1.8rem;"><i class="fa fa-user-tie"></i></div></div>
                    <h4 class="fw-800 mb-1" id="detName">-</h4>
                    <div class="text-muted mb-4 fw-600" id="detPhone">-</div>
                    <div class="stat-box justify-content-center border-0 bg-light py-4 mb-4">
                        <div class="text-center">
                            <div class="text-muted small fw-bold"><?= $t['balance'] ?></div>
                            <div class="fw-800 fs-2" id="detBalance">0.00</div>
                        </div>
                    </div>
                    <a href="#" id="detLink" class="btn btn-primary rounded-pill w-100 py-3 fw-bold shadow">📄 <?= $t['view_statement'] ?></a>
                </div>
            </div>

            <!-- Activity Panel -->
            <div class="lux-card animate__animated animate__fadeInRight">
                <div class="p-4 border-bottom bg-light d-flex justify-content-between align-items-center">
                    <h6 class="sidebar-title m-0"><?= $t['recent_transactions'] ?></h6>
                    <i class="fa fa-history text-muted"></i>
                </div>
                <div id="recentList" class="p-2">
                    <!-- AJAX Recent Tx -->
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modals -->
<div class="modal fade" id="modalAdd" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <form class="modal-content shadow-lg" id="formAdd">
            <div class="modal-header border-0"><h5 class="fw-800 text-danger"><?= $t['add_debt'] ?></h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <label class="small fw-bold text-muted mb-2"><?= $t['customer'] ?></label>
                <select class="form-select modal-input customer-select mb-3" name="customer_id" required></select>
                <div class="row g-2 mb-3">
                    <div class="col-6"><label class="small fw-bold text-muted mb-1"><?= $t['amount'] ?></label><input type="number" step="0.01" class="form-control modal-input text-danger" name="amount" required></div>
                    <div class="col-6"><label class="small fw-bold text-muted mb-1"><?= $t['date'] ?></label><input type="datetime-local" class="form-control modal-input" name="date" value="<?= date('Y-m-d\TH:i') ?>"></div>
                </div>
                <label class="small fw-bold text-muted mb-2"><?= $t['note'] ?></label>
                <input type="text" class="form-control modal-input" name="note">
                <button type="submit" class="btn btn-danger w-100 py-3 rounded-pill fw-bold mt-4 shadow-lg"><?= $t['submit'] ?></button>
            </div>
        </form>
    </div>
</div>

<div class="modal fade" id="modalPay" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <form class="modal-content shadow-lg" id="formPay">
            <div class="modal-header border-0"><h5 class="fw-800 text-success"><?= $t['pay_debt'] ?></h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <label class="small fw-bold text-muted mb-2"><?= $t['customer'] ?></label>
                <select class="form-select modal-input customer-select mb-3" name="customer_id" required></select>
                <div class="row g-2 mb-3">
                    <div class="col-6"><label class="small fw-bold text-muted mb-1"><?= $t['amount'] ?></label><input type="number" step="0.01" class="form-control modal-input text-success" name="amount" required></div>
                    <div class="col-6"><label class="small fw-bold text-muted mb-1"><?= $t['date'] ?></label><input type="datetime-local" class="form-control modal-input" name="date" value="<?= date('Y-m-d\TH:i') ?>"></div>
                </div>
                <label class="small fw-bold text-muted mb-2"><?= $t['note'] ?></label>
                <input type="text" class="form-control modal-input" name="note">
                <button type="submit" class="btn btn-success w-100 py-3 rounded-pill fw-bold mt-4 shadow-lg"><?= $t['submit'] ?></button>
            </div>
        </form>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
const T = <?= json_encode($t) ?>;
const lang = '<?= $lang ?>';

async function fetchData(url, postData = null) {
    try {
        const opts = postData ? { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(postData) } : {};
        const res = await fetch(url, opts); return await res.json();
    } catch(e) { return {success:false, msg:'Network Error'}; }
}

async function loadTable() {
    const q = document.getElementById('searchInput').value;
    const filter = document.getElementById('filterSelect').value;
    const tbody = document.getElementById('customersTableBody');
    const res = await fetchData(`?ajax_customers=1&q=${encodeURIComponent(q)}&filter=${filter}`);
    if(!res.success || !res.rows) return;
    if(res.rows.length === 0) { tbody.innerHTML = `<tr><td colspan="4" class="text-center py-5 text-muted fw-bold">${T.no_results}</td></tr>`; return; }
    tbody.innerHTML = res.rows.map(r => `
        <tr onclick="showDetails(${r.id})">
            <td><div class="fw-800 text-dark">${r.name}</div><div class="text-muted small">ID: #${r.id}</div></td>
            <td><span class="fw-bold text-muted">${r.phone || '-'}</span></td>
            <td class="text-end"><span class="balance-badge ${r.balance > 0 ? 'bal-debt' : 'bal-credit'}">${parseFloat(r.balance).toFixed(2)}</span></td>
            <td class="text-center">
                <button onclick="prefillModal(${r.id}, 'modalPay'); event.stopPropagation()" class="btn-action-sm text-success" title="${T.pay_debt}"><i class="fa fa-check"></i></button>
                <button onclick="prefillModal(${r.id}, 'modalAdd'); event.stopPropagation()" class="btn-action-sm text-danger" title="${T.add_debt}"><i class="fa fa-plus"></i></button>
                <a href="customer_statement.php?id=${r.id}&lang=${lang}" class="btn-action-sm text-primary" onclick="event.stopPropagation()"><i class="fa fa-file-lines"></i></a>
            </td>
        </tr>`).join('');
}

async function loadRecent() {
    const res = await fetchData('?ajax_recent=1');
    const list = document.getElementById('recentList');
    if(!res.success || !res.rows.length) { list.innerHTML = `<div class="p-4 text-center small text-muted">${T.no_results}</div>`; return; }
    list.innerHTML = res.rows.map(r => `
        <div class="activity-item d-flex justify-content-between align-items-center">
            <div class="d-flex align-items-center gap-3">
                <div class="activity-dot ${r.type==='debt'?'bg-danger':'bg-success'}" style="position:static"></div>
                <div>
                    <div class="fw-800 small">${r.name}</div>
                    <div class="text-muted" style="font-size:0.7rem">${r.date.substring(5,16)}</div>
                </div>
            </div>
            <div class="d-flex align-items-center gap-3">
                <div class="text-end">
                    <div class="fw-800 ${r.type==='debt'?'text-danger':'text-success'} small">${parseFloat(r.amount).toFixed(2)}</div>
                    <div class="text-muted x-small uppercase" style="font-size:0.6rem">${r.type}</div>
                </div>
                <button onclick="undoTx(${r.id}); event.stopPropagation()" class="btn-undo d-flex align-items-center justify-content-center" title="Undo / Cancel">
                    <i class="fa-solid fa-rotate-left"></i>
                </button>
            </div>
        </div>`).join('');
}

async function undoTx(id) {
    if (!confirm(T.confirm_undo)) return;
    const res = await fetchData('?action=delete_tx', { id: id });
    if (res.success) {
        loadTable();
        loadRecent();
        setTimeout(() => location.reload(), 600);
    } else {
        alert(res.msg || T.error);
    }
}

async function showDetails(id) {
    const res = await fetchData('?customer_id='+id);
    if(res.success) {
        document.getElementById('detailsCard').classList.remove('d-none');
        document.getElementById('detName').innerText = res.data.name;
        document.getElementById('detPhone').innerText = res.data.phone || 'No Phone';
        const bal = parseFloat(res.data.balance);
        const elBal = document.getElementById('detBalance');
        elBal.innerText = bal.toFixed(2);
        elBal.className = 'fw-800 fs-2 ' + (bal > 0.01 ? 'text-danger' : 'text-success');
        document.getElementById('detLink').href = `customer_statement.php?id=${id}&lang=${lang}`;
    }
}

function updateSelects(rows) {
    const html = `<option value="">-- ${T.customer} --</option>` + rows.map(r => `<option value="${r.id}">${r.name}</option>`).join('');
    document.querySelectorAll('.customer-select').forEach(s => { const cur = s.value; s.innerHTML = html; s.value = cur; });
}

function prefillModal(id, modalId) {
    const modalEl = document.getElementById(modalId);
    const bsModal = new bootstrap.Modal(modalEl);
    modalEl.querySelector('select').value = id;
    bsModal.show();
}

async function handleForm(e, action) {
    e.preventDefault();
    const fd = new FormData(e.target);
    const res = await fetchData('?action='+action, Object.fromEntries(fd.entries()));
    if(res.success) {
        bootstrap.Modal.getInstance(e.target.closest('.modal')).hide(); e.target.reset();
        loadTable(); loadRecent(); setTimeout(() => location.reload(), 600);
    } else alert(res.msg || T.error);
}

document.getElementById('searchInput').addEventListener('input', () => { clearTimeout(window.searchT); window.searchT = setTimeout(loadTable, 300); });
document.getElementById('filterSelect').addEventListener('change', loadTable);
document.getElementById('formAdd').addEventListener('submit', (e) => handleForm(e, 'add_debt'));
document.getElementById('formPay').addEventListener('submit', (e) => handleForm(e, 'pay_debt'));

loadTable(); loadRecent();
(async () => { const res = await fetchData('?ajax_customers=1&filter=all'); if(res.success) updateSelects(res.rows); })();
</script>
</body>
</html>