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

if (session_status() === PHP_SESSION_NONE) session_start();

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

 $lang = $_GET['lang'] ?? ($_SESSION['lang'] ?? 'ar');
if (isset($_GET['lang'])) { $_SESSION['lang'] = $_GET['lang'] === 'ar' ? 'ar' : 'en'; }
 $is_ar = ($_SESSION['lang'] ?? 'ar') === 'ar';

 $errors = []; $success = null;

// 1. تراجع عن حركة
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_tx_id'])) {
    $tx_id = intval($_POST['delete_tx_id']);
    
    $stmt = $pdo->prepare("SELECT * FROM supplier_transactions WHERE id = ? LIMIT 1");
    $stmt->execute([$tx_id]);
    $tx = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($tx) {
        try {
            $pdo->beginTransaction();

            if ($tx['type'] === 'out') {
                $upd = $pdo->prepare("UPDATE suppliers SET balance = COALESCE(balance,0) + ? WHERE id = ?");
                $upd->execute([$tx['amount'], $tx['supplier_id']]);
                
                // ← التعديل: أضفنا category = 'correction'
                $pdo->prepare("INSERT INTO cash_transactions (`type`, amount, description, category, created_at) VALUES ('in', ?, ?, ?, NOW())")
                    ->execute([$tx['amount'], "Correction (Undo): Reverted payment to supplier tx #$tx_id", 'correction']);
            } else {
                $upd = $pdo->prepare("UPDATE suppliers SET balance = COALESCE(balance,0) - ? WHERE id = ?");
                $upd->execute([$tx['amount'], $tx['supplier_id']]);

                // ← التعديل: أضفنا category = 'correction'
                $pdo->prepare("INSERT INTO cash_transactions (`type`, amount, description, category, created_at) VALUES ('out', ?, ?, ?, NOW())")
                    ->execute([$tx['amount'], "Correction (Undo): Reverted receipt from supplier tx #$tx_id", 'correction']);
            }

            $pdo->prepare("DELETE FROM supplier_transactions WHERE id = ?")->execute([$tx_id]);

            $pdo->commit();
            $success = $is_ar ? '✅ تم إلغاء الحركة وتصحيح الرصيد والخزنة.' : 'Transaction reverted successfully.';
        } catch (Exception $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            $errors[] = 'Error undoing transaction: ' . $e->getMessage();
        }
    }
}

// 2. إضافة مورد
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_supplier'])) {
    $name = trim($_POST['name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $balance = isset($_POST['balance']) ? floatval($_POST['balance']) : 0.0;
    
    if ($name === '') {
        $errors[] = $is_ar ? 'اسم المورد مطلوب.' : 'Supplier name required.';
    } else {
        $stmt = $pdo->prepare("INSERT INTO suppliers (name, phone, balance, created_at) VALUES (?, ?, ?, NOW())");
        $stmt->execute([$name, $phone, $balance]);
        $success = $is_ar ? '✅ تم إضافة المورد بنجاح.' : 'Supplier added successfully.';
    }
}

// 3. تعديل مورد
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_supplier'])) {
    $id = intval($_POST['supplier_id'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');

    if ($id > 0 && $name !== '') {
        $stmt = $pdo->prepare("UPDATE suppliers SET name = ?, phone = ? WHERE id = ?");
        $stmt->execute([$name, $phone, $id]);
        $success = $is_ar ? '✅ تم تحديث بيانات المورد بنجاح.' : 'Supplier updated successfully.';
    } else {
        $errors[] = $is_ar ? 'البيانات غير مكتملة.' : 'Incomplete data.';
    }
}

// 4. تسجيل حركة مالية
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_sup_tx'])) {
    $supplier_id = intval($_POST['supplier_id'] ?? 0);
    $type = $_POST['type'] ?? 'out'; 
    $amount = isset($_POST['amount']) ? floatval($_POST['amount']) : 0;
    $desc = trim($_POST['description'] ?? '');

    if ($supplier_id <= 0 || $amount <= 0) {
        $errors[] = $is_ar ? 'بيانات الحركة غير مكتملة.' : 'Incomplete transaction data.';
    } else {
        try {
            $pdo->beginTransaction();
            $pdo->prepare("INSERT INTO supplier_transactions (supplier_id, amount, type, description, created_at) VALUES (?, ?, ?, ?, NOW())")
                ->execute([$supplier_id, $amount, $type, $desc]);

            if ($type === 'out') {
                // ← التعديل: أضفنا category = 'supplier_payment'
                $pdo->prepare("INSERT INTO cash_transactions (`type`, amount, description, category, created_at) VALUES ('out', ?, ?, ?, NOW())")
                    ->execute([$amount, "Payment to supplier #$supplier_id: $desc", 'supplier_payment']);
                $pdo->prepare("UPDATE suppliers SET balance = COALESCE(balance,0) - ? WHERE id = ?")->execute([$amount, $supplier_id]);
            } else {
                // ← التعديل: أضفنا category = 'supplier_receipt'
                $pdo->prepare("INSERT INTO cash_transactions (`type`, amount, description, category, created_at) VALUES ('in', ?, ?, ?, NOW())")
                    ->execute([$amount, "Received from supplier #$supplier_id: $desc", 'supplier_receipt']);
                $pdo->prepare("UPDATE suppliers SET balance = COALESCE(balance,0) + ? WHERE id = ?")->execute([$amount, $supplier_id]);
            }
            $pdo->commit();
            $success = $is_ar ? '✅ تم تسجيل الحركة وتحديث الخزنة.' : 'Transaction recorded & balance updated.';
        } catch (Exception $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            $errors[] = 'DB error: ' . $e->getMessage();
        }
    }
}

// 5. حذف مورد
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $pdo->prepare("DELETE FROM suppliers WHERE id = ?")->execute([intval($_GET['delete'])]);
    header('Location: suppliers.php'); exit;
}

 $search = $_GET['q'] ?? '';
 $supp_query = "SELECT id, name, phone, COALESCE(balance,0) AS balance FROM suppliers";
if($search) $supp_query .= " WHERE name LIKE " . $pdo->quote("%$search%") . " OR phone LIKE " . $pdo->quote("%$search%");
 $supp_query .= " ORDER BY name ASC";
 $suppliers = $pdo->query($supp_query)->fetchAll(PDO::FETCH_ASSOC);

 $recent_tx = $pdo->query("SELECT st.*, s.name AS supplier_name FROM supplier_transactions st LEFT JOIN suppliers s ON s.id = st.supplier_id ORDER BY st.created_at DESC LIMIT 50")->fetchAll(PDO::FETCH_ASSOC);

 $stats = $pdo->query("SELECT SUM(CASE WHEN balance > 0 THEN balance ELSE 0 END) as total_debt, SUM(CASE WHEN balance < 0 THEN ABS(balance) ELSE 0 END) as total_credit FROM suppliers")->fetch(PDO::FETCH_ASSOC);
?>
<!doctype html>
<html lang="<?= $is_ar ? 'ar' : 'en' ?>" dir="<?= $is_ar ? 'rtl' : 'ltr' ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title><?= $is_ar ? 'إدارة الموردين' : 'Suppliers Management' ?></title>
    
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    
    <style>
        :root {
            --primary: #2563eb;
            --success: #10b981;
            --danger: #ef4444;
            --bg: #f8fafc;
            --border: #e2e8f0;
        }

        body {
            font-family: <?= $is_ar ? "'Cairo', sans-serif" : "'Plus Jakarta Sans', sans-serif" ?>;
            background-color: var(--bg);
            color: #1e293b;
            padding-bottom: 50px;
        }

        .container-fluid { max-width: 1400px; padding: 30px; }

        .glass-card {
            background: #fff; border-radius: 20px; border: 1px solid var(--border);
            box-shadow: 0 4px 20px rgba(0,0,0,0.03); overflow: hidden;
        }

        .stat-card {
            background: #fff; border-radius: 16px; padding: 20px; border: 1px solid var(--border);
            display: flex; align-items: center; gap: 15px;
        }
        .stat-icon { width: 48px; height: 48px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 1.25rem; }

        .search-input {
            border: 1px solid var(--border); padding: 8px 15px; border-radius: 10px;
            background: #fcfcfd; width: 100%; max-width: 250px; font-size: 0.9rem;
        }

        .table thead th {
            background: #f8fafc; color: #64748b; font-size: 0.75rem;
            text-transform: uppercase; padding: 15px 20px; font-weight: 700; border: 0;
        }
        .table tbody td { padding: 15px 20px; vertical-align: middle; border-bottom: 1px solid #f1f5f9; }

        .balance-badge {
            padding: 5px 12px; border-radius: 50px; font-weight: 700; font-size: 0.8rem;
        }
        .bal-debt { background: #fef2f2; color: #991b1b; } 
        .bal-credit { background: #f0fdf4; color: #166534; } 
        .bal-zero { background: #f1f5f9; color: #475569; }

        .btn-action {
            width: 34px; height: 34px; border-radius: 8px; display: inline-flex;
            align-items: center; justify-content: center; transition: all 0.2s; border: none;
            background: #f8fafc; color: #64748b; margin: 0 2px;
        }
        .btn-action:hover { background: var(--primary); color: #fff; }
        .btn-edit:hover { background: #6366f1; color: white; }
        .btn-delete:hover { background: var(--danger); color: white; }
        .btn-pay:hover { background: var(--success); color: white; }
        .btn-receive:hover { background: #f59e0b; color: white; }

        .modal-content { border-radius: 20px; border: none; }
        .form-control { border-radius: 10px; padding: 10px 15px; border: 1px solid #dee2e6; }
    </style>
</head>
<body>

    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h2 class="fw-bold m-0"><?= $is_ar ? 'إدارة الموردين' : 'Suppliers' ?></h2>
                <p class="text-muted small m-0"><?= $is_ar ? 'التحكم في حسابات الموردين والمدفوعات' : 'Manage accounts and payments' ?></p>
            </div>
            <div class="d-flex gap-2">
                <a href="cash_report.php" class="btn btn-outline-secondary px-3 rounded-pill btn-sm">
                   <i class="fa fa-chart-pie"></i> <?= $is_ar ? 'التقارير' : 'Reports' ?>
                </a>
                <a href="index.php" class="btn btn-outline-secondary px-3 rounded-pill btn-sm">
                   <i class="fa fa-home"></i> <?= $is_ar ? 'الرئيسية' : 'Home' ?>
                </a>
                <button class="btn btn-primary px-4 rounded-pill fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#addSupplierModal">
                    <i class="fa fa-plus me-1 ms-1"></i> <?= $is_ar ? 'إضافة مورد' : 'New Supplier' ?>
                </button>
            </div>
        </div>

        <div class="row g-3 mb-4">
            <div class="col-md-6 col-lg-3">
                <div class="stat-card">
                    <div class="stat-icon bg-danger text-white"><i class="fa fa-arrow-down"></i></div>
                    <div>
                        <div class="text-muted small"><?= $is_ar ? 'ديونك للموردين' : 'Your Debts' ?></div>
                        <div class="fw-bold fs-5"><?= number_format($stats['total_debt'] ?? 0, 2) ?></div>
                    </div>
                </div>
            </div>
            <div class="col-md-6 col-lg-3">
                <div class="stat-card">
                    <div class="stat-icon bg-success text-white"><i class="fa fa-arrow-up"></i></div>
                    <div>
                        <div class="text-muted small"><?= $is_ar ? 'لك عند الموردين' : 'Your Credits' ?></div>
                        <div class="fw-bold fs-5"><?= number_format($stats['total_credit'] ?? 0, 2) ?></div>
                    </div>
                </div>
            </div>
        </div>

        <?php if ($success): ?>
            <div class="alert alert-success border-0 shadow-sm rounded-3 mb-4"><i class="fa fa-check-circle me-2 ms-2"></i> <?= esc($success) ?></div>
        <?php endif; ?>

        <div class="row g-4">
            <div class="col-lg-8">
                <div class="glass-card">
                    <div class="p-3 border-bottom d-flex justify-content-between align-items-center bg-light">
                        <h6 class="m-0 fw-bold"><?= $is_ar ? 'الموردين' : 'Suppliers List' ?></h6>
                        <form action="" method="get">
                            <input type="text" name="q" value="<?= esc($search) ?>" class="search-input" placeholder="<?= $is_ar ? 'بحث...' : 'Search...' ?>">
                        </form>
                    </div>
                    <div class="table-responsive">
                        <table class="table mb-0">
                            <thead>
                                <tr>
                                    <th><?= $is_ar ? 'الاسم والبيانات' : 'Supplier Details' ?></th>
                                    <th><?= $is_ar ? 'الرصيد' : 'Balance' ?></th>
                                    <th class="text-center"><?= $is_ar ? 'إجراءات' : 'Actions' ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($suppliers as $s): ?>
                                <tr>
                                    <td>
                                        <div class="fw-bold"><?= esc($s['name']) ?></div>
                                        <div class="text-muted small"><i class="fa fa-phone me-1 ms-1"></i> <?= esc($s['phone'] ?: '---') ?></div>
                                    </td>
                                    <td>
                                        <?php 
                                            $b = floatval($s['balance']);
                                            $b_class = $b > 0 ? 'bal-debt' : ($b < 0 ? 'bal-credit' : 'bal-zero');
                                            $b_text = $b > 0 ? ($is_ar ? 'مدين له' : 'You Owe') : ($b < 0 ? ($is_ar ? 'لك عنده' : 'Owes You') : ($is_ar ? 'خالص' : 'Settled'));
                                        ?>
                                        <span class="balance-badge <?= $b_class ?>">
                                            <?= number_format(abs($b), 2) ?> <small>(<?= $b_text ?>)</small>
                                        </span>
                                    </td>
                                    <td class="text-center">
                                        <div class="btn-group">
                                            <button class="btn-action btn-edit" onclick="openEditModal('<?= $s['id'] ?>', '<?= esc($s['name']) ?>', '<?= esc($s['phone']) ?>')" title="<?= $is_ar ? 'تعديل' : 'Edit' ?>">
                                                <i class="fa fa-edit"></i>
                                            </button>
                                            <a href="supplier_view.php?id=<?= $s['id'] ?>" class="btn-action" title="<?= $is_ar ? 'كشف حساب' : 'Statement' ?>">
                                                <i class="fa fa-file-lines"></i>
                                            </a>
                                            <button class="btn-action btn-pay" onclick="openTxModal(<?= $s['id'] ?>,'out','<?= esc($s['name']) ?>')" title="<?= $is_ar ? 'دفع نقدية' : 'Pay Cash' ?>">
                                                <i class="fa fa-minus-circle"></i>
                                            </button>
                                            <button class="btn-action btn-receive" onclick="openTxModal(<?= $s['id'] ?>,'in','<?= esc($s['name']) ?>')" title="<?= $is_ar ? 'استلام نقدية' : 'Receive Cash' ?>">
                                                <i class="fa fa-plus-circle"></i>
                                            </button>
                                            <a href="?delete=<?= $s['id'] ?>" class="btn-action btn-delete" onclick="return confirm('<?= $is_ar ? 'حذف المورد نهائياً؟' : 'Delete this supplier?' ?>')">
                                                <i class="fa fa-trash-can"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div class="col-lg-4">
                <div class="glass-card">
                    <div class="p-3 bg-light border-bottom">
                        <h6 class="m-0 fw-bold"><?= $is_ar ? 'أحدث الحركات' : 'Recent Logs' ?></h6>
                    </div>
                    <div style="max-height: 600px; overflow-y: auto;">
                        <?php foreach($recent_tx as $rt): ?>
                        <div class="p-3 border-bottom d-flex justify-content-between align-items-start">
                            <div>
                                <div class="fw-bold small"><?= esc($rt['supplier_name']) ?></div>
                                <div class="text-muted" style="font-size: 0.7rem;">
                                    <?= $rt['type'] === 'out' ? ($is_ar ? 'دفع للمورد' : 'Payment') : ($is_ar ? 'قبض من المورد' : 'Receipt') ?>
                                    • <?= date('d/m H:i', strtotime($rt['created_at'])) ?>
                                </div>
                            </div>
                            <div class="text-end">
                                <div class="fw-bold small <?= $rt['type'] === 'out' ? 'text-danger' : 'text-success' ?>">
                                    <?= number_format($rt['amount'], 2) ?>
                                </div>
                                <form method="POST" onsubmit="return confirm('Undo this action?')">
                                    <input type="hidden" name="delete_tx_id" value="<?= $rt['id'] ?>">
                                    <button class="btn btn-link p-0 text-danger text-decoration-none" style="font-size: 0.65rem;">
                                        <?= $is_ar ? 'تراجع' : 'Undo' ?>
                                    </button>
                                </form>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal: Add Supplier -->
    <div class="modal fade" id="addSupplierModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <form method="post" class="modal-content shadow">
                <input type="hidden" name="add_supplier" value="1">
                <div class="modal-header"><h5 class="fw-bold m-0"><?= $is_ar ? 'إضافة مورد' : 'Add Supplier' ?></h5></div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label small fw-bold"><?= $is_ar ? 'اسم المورد' : 'Name' ?></label>
                        <input name="name" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-bold"><?= $is_ar ? 'الهاتف' : 'Phone' ?></label>
                        <input name="phone" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-bold"><?= $is_ar ? 'الرصيد الافتتاحي (مدين به للمورد)' : 'Opening Balance' ?></label>
                        <input name="balance" type="number" step="0.01" value="0" class="form-control">
                    </div>
                    <button class="btn btn-primary w-100 rounded-pill py-2 fw-bold"><?= $is_ar ? 'حفظ المورد' : 'Save Supplier' ?></button>
                </div>
            </form>
        </div>
    </div>

    <!-- Modal: Edit Supplier -->
    <div class="modal fade" id="editSupplierModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <form method="post" class="modal-content shadow">
                <input type="hidden" name="edit_supplier" value="1">
                <input type="hidden" name="supplier_id" id="edit_id">
                <div class="modal-header"><h5 class="fw-bold m-0"><?= $is_ar ? 'تعديل بيانات مورد' : 'Edit Supplier' ?></h5></div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label small fw-bold"><?= $is_ar ? 'الاسم' : 'Name' ?></label>
                        <input name="name" id="edit_name" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-bold"><?= $is_ar ? 'الهاتف' : 'Phone' ?></label>
                        <input name="phone" id="edit_phone" class="form-control">
                    </div>
                    <button class="btn btn-primary w-100 rounded-pill py-2 fw-bold"><?= $is_ar ? 'تحديث البيانات' : 'Update Supplier' ?></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 shadow">
                <input type="hidden" name="add_sup_tx" value="1">
                <input type="hidden" name="supplier_id" id="modal_supplier_id">
                <input type="hidden" name="type" id="modal_type">
                <div class="modal-header"><h5 class="fw-bold m-0"><?= $is_ar ? 'حركة نقدية' : 'Transaction' ?></h5></div>
                <div class="modal-body">
                    <div class="alert alert-secondary py-2 small" id="modal_supplier_name"></div>
                    <div class="mb-3">
                        <label class="form-label small fw-bold"><?= $is_ar ? 'المبلغ' : 'Amount' ?></label>
                        <input type="number" step="0.01" name="amount" class="form-control" required autofocus>
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-bold"><?= $is_ar ? 'ملاحظات' : 'Description' ?></label>
                        <input type="text" name="description" class="form-control">
                    </div>
                    <button class="btn btn-primary w-100 rounded-pill py-2 fw-bold"><?= $is_ar ? 'تأكيد' : 'Confirm' ?></button>
                </div>
            </form>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function openTxModal(id, type, name){
            document.getElementById('modal_supplier_id').value = id;
            document.getElementById('modal_type').value = type;
            const typeLabel = (type === 'out' ? ' — <?= $is_ar ? "دفع للمورد" : "Pay" ?>' : ' — <?= $is_ar ? "استلام من المورد" : "Receive" ?>');
            document.getElementById('modal_supplier_name').textContent = name + typeLabel;
            new bootstrap.Modal(document.getElementById('txModal')).show();
        }

        function openEditModal(id, name, phone) {
            document.getElementById('edit_id').value = id;
            document.getElementById('edit_name').value = name;
            document.getElementById('edit_phone').value = phone;
            new bootstrap.Modal(document.getElementById('editSupplierModal')).show();
        }
    </script>
</body>
</html>