<?php
/**
 * Modern Customers Dashboard - Professional Table View
 * Features: Dashboard stats, Smart Table, Transaction History links, Cash Fund Sync.
 */

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

// --- الإعدادات واللغة ---
date_default_timezone_set('Asia/Beirut');
$lang = $_GET['lang'] ?? ($_SESSION['lang'] ?? 'en');
$_SESSION['lang'] = ($lang === 'ar' ? 'ar' : 'en');
$is_ar = ($_SESSION['lang'] === 'ar');
$dir = $is_ar ? 'rtl' : 'ltr';

function esc($v) { return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }

$msg = '';
$error = '';

// مساعد العمليات البرمجية للقاعدة
function run_transaction(PDO $pdo, callable $callback) {
    try {
        $pdo->beginTransaction();
        $callback($pdo);
        $pdo->commit();
        return true;
    } catch (Exception $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        throw $e;
    }
}

// --- معالجة الأفعال (POST Actions) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    try {
        if ($action === 'add_customer' || $action === 'edit_customer') {
            $id = intval($_POST['id'] ?? 0);
            $name = trim($_POST['name'] ?? '');
            $phone = trim($_POST['phone'] ?? '');
            $address = trim($_POST['address'] ?? '');

            if ($name === '') throw new Exception($is_ar ? 'الاسم مطلوب' : 'Name is required');

            if ($action === 'add_customer') {
                $stmt = $pdo->prepare("INSERT INTO customers (name, phone, address, balance, created_at) VALUES (?, ?, ?, 0, NOW())");
                $stmt->execute([$name, $phone, $address]);
                $msg = $is_ar ? 'تمت إضافة العميل' : 'Customer added';
            } else {
                $stmt = $pdo->prepare("UPDATE customers SET name=?, phone=?, address=? WHERE id=?");
                $stmt->execute([$name, $phone, $address, $id]);
                $msg = $is_ar ? 'تم تحديث بيانات العميل' : 'Customer updated';
            }
        }

        elseif ($action === 'delete_customer') {
            $id = intval($_POST['id'] ?? 0);
            $pdo->prepare("DELETE FROM customers WHERE id=?")->execute([$id]);
            $msg = $is_ar ? 'تم حذف العميل' : 'Customer deleted';
        }

        elseif ($action === 'transaction') {
            $id = intval($_POST['customer_id'] ?? 0);
            $type = $_POST['t_type'] === 'debt' ? 'debt' : 'payment';
            $amount = round(floatval($_POST['amount'] ?? 0), 2);
            $note = trim($_POST['note'] ?? '');

            if ($amount <= 0) throw new Exception($is_ar ? 'المبلغ غير صالح' : 'Invalid amount');

            run_transaction($pdo, function($pdo) use ($id, $type, $amount, $note, $is_ar) {
                $stmt = $pdo->prepare("SELECT balance FROM customers WHERE id = ? FOR UPDATE");
                $stmt->execute([$id]);
                $current_balance = floatval($stmt->fetchColumn());

                $new_balance = ($type === 'debt') ? ($current_balance + $amount) : ($current_balance - $amount);

                $pdo->prepare("UPDATE customers SET balance = ? WHERE id = ?")->execute([$new_balance, $id]);
                $pdo->prepare("INSERT INTO customer_transactions (customer_id, type, amount, balance_after, note, date, added_by) VALUES (?, ?, ?, ?, ?, NOW(), ?)")
                    ->execute([$id, $type, $amount, $new_balance, $note, $_SESSION['user']['username']]);

                if ($type === 'payment') {
                    $pdo->prepare("INSERT INTO cash_transactions (type, amount, description, created_at) VALUES ('in', ?, ?, NOW())")
                        ->execute([$amount, ($is_ar ? "سداد من العميل: " : "Payment from: ") . $id]);
                }
            });
            $msg = $is_ar ? 'تم تسجيل العملية' : 'Transaction recorded';
        }

        elseif ($action === 'withdraw_customer') {
            $id = intval($_POST['id'] ?? 0);
            $amount = round(floatval($_POST['amount'] ?? 0), 2);

            run_transaction($pdo, function($pdo) use ($id, $amount, $is_ar) {
                $stmt = $pdo->prepare("SELECT balance FROM customers WHERE id = ? FOR UPDATE");
                $stmt->execute([$id]);
                $bal = floatval($stmt->fetchColumn());

                if ($bal >= 0 || $amount > abs($bal)) throw new Exception($is_ar ? 'الرصيد غير كافٍ' : 'Insufficient credit');

                $new_balance = $bal + $amount;
                $pdo->prepare("UPDATE customers SET balance = ? WHERE id = ?")->execute([$new_balance, $id]);
                $pdo->prepare("INSERT INTO customer_transactions (customer_id, type, amount, balance_after, note, date, added_by) VALUES (?, 'withdraw', ?, ?, 'Withdrawal', NOW(), ?)")
                    ->execute([$id, $amount, $new_balance, $_SESSION['user']['username']]);
                
                $pdo->prepare("INSERT INTO cash_transactions (type, amount, description, created_at) VALUES ('out', ?, ?, NOW())")
                    ->execute([$amount, ($is_ar ? "سحب للعميل: " : "Withdraw for: ") . $id]);
            });
            $msg = $is_ar ? 'تم السحب النقدي' : 'Cash withdrawn';
        }
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}

// --- جلب البيانات والإحصائيات ---
$search = trim($_GET['q'] ?? '');
$sql = "SELECT * FROM customers";
$params = [];
if ($search !== '') {
    $sql .= " WHERE name LIKE ? OR phone LIKE ?";
    $params = ["%$search%", "%$search%"];
}
$sql .= " ORDER BY balance DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$customers = $stmt->fetchAll(PDO::FETCH_ASSOC);

$stats = $pdo->query("SELECT 
    SUM(CASE WHEN balance > 0 THEN balance ELSE 0 END) as total_debts,
    SUM(CASE WHEN balance < 0 THEN ABS(balance) ELSE 0 END) as total_credits,
    COUNT(*) as total_count 
    FROM customers")->fetch();
?>
<!DOCTYPE html>
<html lang="<?= $_SESSION['lang'] ?>" dir="<?= $dir ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $is_ar ? 'نظام إدارة العملاء' : 'Customers Ledger' ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700&family=Noto+Kufi+Arabic:wght@400;600;700&display=swap" rel="stylesheet">
    <style>
        :root { --brand: #4338ca; --bg: #f1f5f9; }
        body { background: var(--bg); font-family: <?= $is_ar ? "'Noto Kufi Arabic'" : "'Plus Jakarta Sans'" ?>, sans-serif; color: #334155; }
        
        /* Stats Ribbon */
        .stats-ribbon { background: #fff; border-radius: 16px; padding: 20px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05); margin-bottom: 24px; border: 1px solid #e2e8f0; }
        .stat-item { padding: 0 20px; border-inline-end: 1px solid #e2e8f0; }
        .stat-item:last-child { border: none; }
        .stat-label { font-size: 0.75rem; color: #64748b; text-transform: uppercase; letter-spacing: 0.05em; font-weight: 700; }
        .stat-value { font-size: 1.25rem; font-weight: 800; margin-top: 4px; }

        /* Dashboard Table */
        .dashboard-container { background: #fff; border-radius: 20px; border: 1px solid #e2e8f0; overflow: hidden; box-shadow: 0 10px 15px -3px rgba(0,0,0,0.05); }
        .table-header { padding: 24px; background: #fff; border-bottom: 1px solid #f1f5f9; }
        .table thead th { background: #f8fafc; color: #64748b; font-weight: 600; text-transform: uppercase; font-size: 0.7rem; padding: 16px 24px; border: none; }
        .table tbody td { padding: 18px 24px; vertical-align: middle; border-bottom: 1px solid #f1f5f9; }
        .table tbody tr:hover { background: #fbfcfe; }

        /* Balance Badges */
        .badge-status { padding: 6px 12px; border-radius: 8px; font-size: 0.75rem; font-weight: 700; display: inline-flex; align-items: center; gap: 6px; }
        .badge-owes { background: #fff1f2; color: #e11d48; }
        .badge-credit { background: #f0fdf4; color: #16a34a; }
        .badge-even { background: #f8fafc; color: #94a3b8; }

        /* UI Elements */
        .btn-brand { background: var(--brand); color: #fff; border: none; border-radius: 10px; padding: 10px 20px; font-weight: 600; }
        .btn-brand:hover { background: #3730a3; color: #fff; }
        .search-input { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 12px; padding: 10px 16px 10px 40px; font-size: 0.9rem; }
        .action-icon-btn { width: 34px; height: 34px; border-radius: 8px; display: inline-flex; align-items: center; justify-content: center; border: 1px solid #e2e8f0; background: #fff; color: #64748b; transition: all 0.2s; }
        .action-icon-btn:hover { border-color: var(--brand); color: var(--brand); }
    </style>
</head>
<body>

<div class="container py-5">
    <!-- Top Navigation & Stats -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h3 class="fw-bold mb-1"><?= $is_ar ? 'لوحة تحكم العملاء' : 'Customers Dashboard' ?></h3>
            <p class="text-muted small mb-0"><?= $is_ar ? 'إدارة المديونية والمدفوعات' : 'Manage accounts and transactions' ?></p>
        </div>
        <div class="d-flex gap-2">
            <a href="?lang=<?= $is_ar ? 'en' : 'ar' ?>" class="btn btn-outline-secondary btn-sm px-3"><?= $is_ar ? 'English' : 'عربي' ?></a>
            <a href="index.php" class="btn btn-outline-secondary btn-sm px-3">🏠</a>
            <button class="btn btn-brand shadow-sm" onclick="openModal('add')"><?= $is_ar ? '+ عميل جديد' : '+ New Customer' ?></button>
        </div>
    </div>

    <!-- Stats Ribbon -->
    <div class="stats-ribbon d-flex flex-wrap">
        <div class="stat-item flex-fill">
            <div class="stat-label"><?= $is_ar ? 'إجمالي الديون لنا' : 'Total Debts' ?></div>
            <div class="stat-value text-danger">$<?= number_format($stats['total_debts'], 2) ?></div>
        </div>
        <div class="stat-item flex-fill">
            <div class="stat-label"><?= $is_ar ? 'إجمالي الأرصدة لهم' : 'Total Credits' ?></div>
            <div class="stat-value text-success">$<?= number_format($stats['total_credits'], 2) ?></div>
        </div>
        <div class="stat-item flex-fill">
            <div class="stat-label"><?= $is_ar ? 'عدد العملاء' : 'Total Customers' ?></div>
            <div class="stat-value text-primary"><?= $stats['total_count'] ?></div>
        </div>
    </div>

    <!-- Main Table Container -->
    <div class="dashboard-container">
        <div class="table-header d-flex justify-content-between align-items-center">
            <div class="position-relative" style="width: 300px;">
                <span class="position-absolute" style="<?= $is_ar ? 'right' : 'left' ?>: 14px; top: 11px; opacity: 0.4;">🔍</span>
                <input type="text" id="search" class="form-control search-input w-100" 
                       placeholder="<?= $is_ar ? 'بحث...' : 'Search name/phone...' ?>" 
                       value="<?= esc($search) ?>"
                       onkeyup="if(event.key==='Enter') window.location.href='?q='+this.value">
            </div>
            <div class="text-muted small">
                <?= count($customers) ?> <?= $is_ar ? 'نتائج وجدت' : 'results found' ?>
            </div>
        </div>

        <?php if($msg): ?> <div class="alert alert-success m-3 border-0"><?= $msg ?></div> <?php endif; ?>
        <?php if($error): ?> <div class="alert alert-danger m-3 border-0"><?= $error ?></div> <?php endif; ?>

        <div class="table-responsive">
            <table class="table mb-0">
                <thead>
                    <tr>
                        <th><?= $is_ar ? 'العميل' : 'Customer' ?></th>
                        <th><?= $is_ar ? 'التواصل' : 'Contact' ?></th>
                        <th><?= $is_ar ? 'الحالة' : 'Status' ?></th>
                        <th class="text-end"><?= $is_ar ? 'الرصيد' : 'Balance' ?></th>
                        <th class="text-center"><?= $is_ar ? 'إجراءات سريعة' : 'Quick Actions' ?></th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($customers as $c): 
                        $bal = floatval($c['balance']);
                        $status_cls = $bal > 0 ? 'badge-owes' : ($bal < 0 ? 'badge-credit' : 'badge-even');
                        $status_txt = $bal > 0 ? ($is_ar ? 'مدين' : 'Owes') : ($bal < 0 ? ($is_ar ? 'دائن' : 'Credit') : ($is_ar ? 'خالص' : 'Settled'));
                    ?>
                    <tr>
                        <td>
                            <div class="fw-bold"><?= esc($c['name']) ?></div>
                            <div class="text-muted" style="font-size: 0.7rem;">ID: #<?= $c['id'] ?></div>
                        </td>
                        <td>
                            <div class="small fw-600"><?= esc($c['phone']) ?: '--' ?></div>
                            <div class="text-muted small"><?= esc($c['address']) ?: '--' ?></div>
                        </td>
                        <td>
                            <span class="badge-status <?= $status_cls ?>">
                                <span style="width: 6px; height: 6px; border-radius: 50%; background: currentColor;"></span>
                                <?= $status_txt ?>
                            </span>
                        </td>
                        <td class="text-end fw-bold <?= $bal > 0 ? 'text-danger' : ($bal < 0 ? 'text-success' : '') ?>">
                            $<?= number_format(abs($bal), 2) ?>
                        </td>
                        <td class="text-center">
                            <div class="btn-group shadow-sm" style="border-radius: 8px; overflow: hidden;">
                                <button class="btn btn-sm btn-success px-3" onclick="openTxModal(<?= $c['id'] ?>, 'payment', '<?= addslashes($c['name']) ?>')"><?= $is_ar ? 'قبض' : 'Pay' ?></button>
                                <button class="btn btn-sm btn-danger px-3" onclick="openTxModal(<?= $c['id'] ?>, 'debt', '<?= addslashes($c['name']) ?>')"><?= $is_ar ? 'دين' : 'Debt' ?></button>
                            </div>
                        </td>
                        <td class="text-end">
                            <div class="dropdown">
                                <button class="action-icon-btn dropdown-toggle no-caret" data-bs-toggle="dropdown">⋮</button>
                                <ul class="dropdown-menu dropdown-menu-end shadow border-0">
                                    <li><a class="dropdown-item" href="#" onclick='openModal("edit", <?= json_encode($c) ?>)'>📝 <?= $is_ar ? 'تعديل' : 'Edit' ?></a></li>
                                    <li><a class="dropdown-item" href="customer_statement.php?id=<?= $c['id'] ?>">📄 <?= $is_ar ? 'كشف حساب' : 'Statement' ?></a></li>
                                    <?php if($bal < 0): ?>
                                        <li><a class="dropdown-item text-warning" href="#" onclick="openWithdrawModal(<?= $c['id'] ?>, <?= abs($bal) ?>)">💸 <?= $is_ar ? 'سحب نقدي' : 'Withdraw' ?></a></li>
                                    <?php endif; ?>
                                    <li><hr class="dropdown-divider"></li>
                                    <li><a class="dropdown-item text-danger" href="#" onclick="deleteCustomer(<?= $c['id'] ?>)">🗑️ <?= $is_ar ? 'حذف' : 'Delete' ?></a></li>
                                </ul>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Modal: Add/Edit Customer -->
<div class="modal fade" id="customerModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <form method="POST" class="modal-content border-0 shadow-lg" style="border-radius:24px;">
            <input type="hidden" name="action" id="modal_action" value="add_customer">
            <input type="hidden" name="id" id="modal_id">
            <div class="modal-header border-0 p-4 pb-0">
                <h5 class="fw-bold" id="modalTitle"></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <div class="mb-3">
                    <label class="form-label small fw-bold text-muted"><?= $is_ar ? 'اسم العميل الكامل' : 'Full Customer Name' ?></label>
                    <input type="text" name="name" id="field_name" class="form-control py-2 border-light shadow-sm" required>
                </div>
                <div class="row g-3">
                    <div class="col-6">
                        <label class="form-label small fw-bold text-muted"><?= $is_ar ? 'رقم الهاتف' : 'Phone Number' ?></label>
                        <input type="text" name="phone" id="field_phone" class="form-control py-2 border-light shadow-sm">
                    </div>
                    <div class="col-6">
                        <label class="form-label small fw-bold text-muted"><?= $is_ar ? 'العنوان' : 'Address' ?></label>
                        <input type="text" name="address" id="field_address" class="form-control py-2 border-light shadow-sm">
                    </div>
                </div>
            </div>
            <div class="modal-footer border-0 p-4 pt-0">
                <button type="submit" class="btn btn-brand w-100 py-3 fw-bold"><?= $is_ar ? 'حفظ البيانات' : 'Save Details' ?></button>
            </div>
        </form>
    </div>
</div>

<!-- Modal: Transaction -->
<div class="modal fade" id="txModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <form method="POST" class="modal-content border-0 shadow-lg" style="border-radius:24px;">
            <input type="hidden" name="action" value="transaction">
            <input type="hidden" name="customer_id" id="tx_customer_id">
            <input type="hidden" name="t_type" id="tx_type">
            <div class="modal-header border-0 p-4 pb-0">
                <h5 class="fw-bold" id="txTitle"></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <p class="text-muted small mb-4"><?= $is_ar ? 'العميل المستهدف:' : 'For Customer:' ?> <span id="txCustomerName" class="fw-bold text-dark"></span></p>
                <div class="mb-4">
                    <label class="form-label small fw-bold text-muted"><?= $is_ar ? 'المبلغ المراد تسجيله ($)' : 'Amount to record ($)' ?></label>
                    <input type="number" name="amount" step="0.01" class="form-control form-control-lg text-center fw-bold bg-light border-0" required autofocus>
                </div>
                <div class="mb-3">
                    <label class="form-label small fw-bold text-muted"><?= $is_ar ? 'بيان العملية' : 'Transaction Note' ?></label>
                    <input type="text" name="note" class="form-control border-light shadow-sm" placeholder="<?= $is_ar ? 'مثال: دفعة الحساب' : 'e.g. Account settle' ?>">
                </div>
            </div>
            <div class="modal-footer border-0 p-4 pt-0">
                <button type="submit" id="txSubmitBtn" class="btn w-100 py-3 fw-bold text-white"></button>
            </div>
        </form>
    </div>
</div>

<!-- Modal: Withdrawal -->
<div class="modal fade" id="withdrawModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <form method="POST" class="modal-content border-0 shadow-lg" style="border-radius:24px;">
            <input type="hidden" name="action" value="withdraw_customer">
            <input type="hidden" name="id" id="with_id">
            <div class="modal-header border-0 p-4 pb-0 text-center d-block">
                <h5 class="fw-bold"><?= $is_ar ? 'سحب نقدي' : 'Cash Withdrawal' ?></h5>
            </div>
            <div class="modal-body p-4 text-center">
                <div class="mb-3">
                    <input type="number" name="amount" id="with_max" step="0.01" class="form-control form-control-lg text-center fw-bold" required>
                </div>
                <p class="small text-muted mb-0"><?= $is_ar ? 'تخصم من رصيد العميل وتخرج من الصندوق' : 'Deducts from customer credit and fund' ?></p>
            </div>
            <div class="modal-footer border-0 p-4 pt-0">
                <button type="submit" class="btn btn-warning w-100 py-2 fw-bold"><?= $is_ar ? 'تأكيد السحب' : 'Confirm' ?></button>
            </div>
        </form>
    </div>
</div>

<!-- Hidden Delete Form -->
<form id="deleteForm" method="POST" style="display:none;">
    <input type="hidden" name="action" value="delete_customer">
    <input type="hidden" name="id" id="delete_id">
</form>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    const custModal = new bootstrap.Modal('#customerModal');
    const txModal = new bootstrap.Modal('#txModal');
    const withdrawModal = new bootstrap.Modal('#withdrawModal');

    function openModal(mode, data = null) {
        document.getElementById('modal_action').value = mode === 'add' ? 'add_customer' : 'edit_customer';
        document.getElementById('modalTitle').innerText = mode === 'add' ? '<?= $is_ar ? "إضافة عميل" : "New Customer" ?>' : '<?= $is_ar ? "تعديل بيانات" : "Edit Customer" ?>';
        document.getElementById('modal_id').value = data ? data.id : '';
        document.getElementById('field_name').value = data ? data.name : '';
        document.getElementById('field_phone').value = data ? data.phone : '';
        document.getElementById('field_address').value = data ? data.address : '';
        custModal.show();
    }

    function openTxModal(id, type, name) {
        document.getElementById('tx_customer_id').value = id;
        document.getElementById('tx_type').value = type;
        document.getElementById('txCustomerName').innerText = name;
        const btn = document.getElementById('txSubmitBtn');
        const title = document.getElementById('txTitle');
        if (type === 'payment') {
            title.innerText = '<?= $is_ar ? "قبض دفعة نقدية" : "Receive Payment" ?>';
            btn.innerText = '<?= $is_ar ? "تسجيل القبض" : "Record Payment" ?>';
            btn.className = 'btn w-100 py-3 fw-bold text-white btn-success';
        } else {
            title.innerText = '<?= $is_ar ? "تسجيل مديونية" : "Record Debt" ?>';
            btn.innerText = '<?= $is_ar ? "تسجيل الدين" : "Record Debt" ?>';
            btn.className = 'btn w-100 py-3 fw-bold text-white btn-danger';
        }
        txModal.show();
    }

    function openWithdrawModal(id, max) {
        document.getElementById('with_id').value = id;
        document.getElementById('with_max').value = max;
        withdrawModal.show();
    }

    function deleteCustomer(id) {
        if(confirm('<?= $is_ar ? "هل أنت متأكد من حذف العميل؟" : "Are you sure you want to delete this customer?" ?>')) {
            document.getElementById('delete_id').value = id;
            document.getElementById('deleteForm').submit();
        }
    }
</script>
</body>
</html>