<?php
session_start();

// التحقق من تسجيل الدخول
if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

require_once 'db_connect.php';

// إضافة عميل جديد مع التحقق من تكرار رقم البطاقة
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_client'])) {
    $name = $_POST['name'];
    $phone = $_POST['phone'];
    $address = $_POST['address'];
    $id_number = $_POST['id_number'];
    $previous_debt = $_POST['previous_debt'];

    // التحقق من تكرار رقم البطاقة
    $stmt = $conn->prepare("SELECT COUNT(*) FROM clients WHERE id_number = :id_number");
    $stmt->execute([':id_number' => $id_number]);
    $count = $stmt->fetchColumn();

    if ($count > 0) {
        $error_message = "رقم البطاقة موجود من قبل!";
    } else {
        $stmt = $conn->prepare("INSERT INTO clients (name, phone, address, id_number, previous_debt) VALUES (:name, :phone, :address, :id_number, :previous_debt)");
        $stmt->execute([
            ':name' => $name,
            ':phone' => $phone,
            ':address' => $address,
            ':id_number' => $id_number,
            ':previous_debt' => $previous_debt
        ]);
        $success_message = "تم إضافة العميل بنجاح!";
    }
}

// تعديل عميل مع التحقق من تكرار رقم البطاقة
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['edit_client'])) {
    $id = $_POST['id'];
    $name = $_POST['name'];
    $phone = $_POST['phone'];
    $address = $_POST['address'];
    $id_number = $_POST['id_number'];
    $previous_debt = $_POST['previous_debt'];

    // التحقق من تكرار رقم البطاقة باستثناء العميل الحالي
    $stmt = $conn->prepare("SELECT COUNT(*) FROM clients WHERE id_number = :id_number AND id != :id");
    $stmt->execute([':id_number' => $id_number, ':id' => $id]);
    $count = $stmt->fetchColumn();

    if ($count > 0) {
        $error_message = "رقم البطاقة موجود من قبل!";
    } else {
        $stmt = $conn->prepare("UPDATE clients SET name = :name, phone = :phone, address = :address, id_number = :id_number, previous_debt = :previous_debt WHERE id = :id");
        $stmt->execute([
            ':id' => $id,
            ':name' => $name,
            ':phone' => $phone,
            ':address' => $address,
            ':id_number' => $id_number,
            ':previous_debt' => $previous_debt
        ]);
        $success_message = "تم تعديل العميل بنجاح!";
    }
}

// تسديد دين
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['pay_debt'])) {
    $id = $_POST['id'];
    $payment = floatval($_POST['payment']);
    $treasury_id = 1; // يمكنك تعديل هذا لاختيار خزنة معينة ديناميكيًا إذا لزم الأمر

    try {
        $conn->beginTransaction();

        // التحقق من أن المبلغ المدفوع صالح
        if ($payment <= 0) {
            throw new Exception("المبلغ المدفوع يجب أن يكون أكبر من صفر!");
        }

        // جلب الدين الحالي للعميل
        $stmt = $conn->prepare("SELECT previous_debt FROM clients WHERE id = :id");
        $stmt->execute([':id' => $id]);
        $current_debt = $stmt->fetchColumn();

        if ($payment > $current_debt) {
            throw new Exception("المبلغ المدفوع يتجاوز الدين الحالي!");
        }

        // تحديث الدين في جدول العملاء
        $stmt = $conn->prepare("UPDATE clients SET previous_debt = previous_debt - :payment WHERE id = :id");
        $stmt->execute([':id' => $id, ':payment' => $payment]);

        // تسجيل معاملة تسديد الدين في جدول treasury_transactions
        $description = "تسديد دين للعميل رقم $id";
        $stmt = $conn->prepare("
            INSERT INTO treasury_transactions (treasury_id, client_id, transaction_type, amount, description, date)
            VALUES (:treasury_id, :client_id, 'income', :amount, :description, NOW())
        ");
        $stmt->execute([
            ':treasury_id' => $treasury_id,
            ':client_id' => $id,
            ':amount' => $payment,
            ':description' => $description
        ]);

        // تحديث رصيد الخزنة
        $stmt = $conn->prepare("UPDATE treasuries SET current_balance = current_balance + :amount WHERE id = :treasury_id");
        $stmt->execute([':amount' => $payment, ':treasury_id' => $treasury_id]);

        $conn->commit();
        $success_message = "تم تسديد الدين بنجاح!";
    } catch (Exception $e) {
        $conn->rollBack();
        error_log("Error paying debt: " . $e->getMessage());
        $error_message = "فشل تسديد الدين: " . $e->getMessage();
    }
}

// حذف عميل
if (isset($_GET['delete_id'])) {
    $id = $_GET['delete_id'];
    $stmt = $conn->prepare("DELETE FROM clients WHERE id = :id");
    $stmt->execute([':id' => $id]);
    $success_message = "تم حذف العميل بنجاح!";
}

// حساب مجموع الديون تلقائيًا
$total_debt = 0;
$clients = $conn->query("SELECT * FROM clients")->fetchAll(PDO::FETCH_ASSOC);
foreach ($clients as $client) {
    $total_debt += (float)$client['previous_debt'];
}
?>

<!DOCTYPE html>
<html lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Astra - العملاء</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body {
            margin: 0;
            padding: 0;
            min-height: 100vh;
            direction: rtl;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #E74C3C, #3498DB, #2ECC71);
            overflow-x: hidden;
            animation: gradientShift 10s ease infinite;
            background-size: 400% 400%;
        }

        @keyframes gradientShift {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }

        .container-fluid {
            padding: 40px;
            height: 100vh;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        .card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            padding: 20px;
            margin-bottom: 20px;
            animation: fadeIn 1s ease-in-out;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        h2 {
            color: #E74C3C;
            font-weight: bold;
            text-align: center;
            margin-bottom: 30px;
            text-shadow: 0 0 5px rgba(231, 76, 60, 0.5);
        }

        .form-label {
            color: #3498DB;
            font-weight: bold;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            font-size: 0.9rem;
        }

        .form-label i {
            margin-left: 8px;
            color: #2ECC71;
        }

        .form-control {
            border-radius: 15px;
            border: 2px solid #E74C3C;
            padding: 8px 12px;
            background: rgba(255, 255, 255, 0.8);
            transition: all 0.3s ease;
            box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.1);
            font-size: 0.9rem;
        }

        .form-control:focus {
            border-color: #2ECC71;
            box-shadow: 0 0 10px rgba(46, 204, 113, 0.5), inset 0 2px 5px rgba(0, 0, 0, 0.1);
            background: #fff;
        }

        .btn {
            border-radius: 15px;
            padding: 8px 20px;
            font-weight: bold;
            transition: all 0.4s ease;
            position: relative;
            overflow: hidden;
            font-size: 0.9rem;
        }

        .btn-add {
            background: linear-gradient(45deg, #2ECC71, #27AE60);
            border: none;
            color: #fff;
        }

        .btn-add:hover {
            background: linear-gradient(45deg, #27AE60, #219653);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(46, 204, 113, 0.5);
        }

        .btn-cancel {
            background: linear-gradient(45deg, #E74C3C, #C0392B);
            border: none;
            color: #fff;
        }

        .btn-cancel:hover {
            background: linear-gradient(45deg, #C0392B, #A93226);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(231, 76, 60, 0.5);
        }

        .btn-save {
            background: linear-gradient(45deg, #3498DB, #2980B9);
            border: none;
            color: #fff;
        }

        .btn-save:hover {
            background: linear-gradient(45deg, #2980B9, #2471A3);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(52, 152, 219, 0.5);
        }

        .btn-edit {
            background: #F1C40F;
            border: none;
            color: #fff;
        }

        .btn-edit:hover {
            background: #D4AC0D;
            transform: translateY(-2px);
        }

        .btn-delete {
            background: #E74C3C;
            border: none;
            color: #fff;
        }

        .btn-delete:hover {
            background: #C0392B;
            transform: translateY(-2px);
        }

        .btn-debt {
            background: #9B59B6;
            border: none;
            color: #fff;
        }

        .btn-debt:hover {
            background: #8E44AD;
            transform: translateY(-2px);
        }

        .btn-pay {
            background: #27AE60;
            border: none;
            color: #fff;
        }

        .btn-pay:hover {
            background: #219653;
            transform: translateY(-2px);
        }

        .btn i {
            margin-left: 8px;
        }

        .success-message {
            color: #2ECC71;
            font-weight: bold;
            text-align: center;
            margin-bottom: 20px;
            animation: fadeIn 0.5s ease-in-out;
        }

        .error-message {
            color: #E74C3C;
            font-weight: bold;
            text-align: center;
            margin-bottom: 20px;
            animation: fadeIn 0.5s ease-in-out;
        }

        .total-debt-box {
            background: linear-gradient(45deg, #F1C40F, #D4AC0D);
            color: #fff;
            padding: 10px 20px;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(241, 196, 15, 0.5);
            text-align: center;
            font-weight: bold;
            position: fixed;
            top: 20px;
            left: 20px;
            z-index: 1000;
            font-size: 1rem;
        }

        .table {
            background: #fff;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            width: 100%;
        }

        .table thead {
            background: #E74C3C;
            color: #fff;
        }

        .table tbody tr:hover {
            background: rgba(231, 76, 60, 0.1);
        }

        .modal-content {
            border-radius: 15px;
            background: rgba(255, 255, 255, 0.95);
        }

        .modal-header {
            background: #E74C3C;
            color: #fff;
            border-radius: 15px 15px 0 0;
        }

        .search-bar {
            margin-bottom: 20px;
        }

        .row-cols-5 .col {
            flex: 0 0 20%;
            max-width: 20%;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="card">
            <h2><i class="fas fa-users me-2"></i> إضافة عميل جديد</h2>
            <?php if (isset($success_message)): ?>
                <div class="success-message"><?php echo $success_message; ?></div>
            <?php endif; ?>
            <?php if (isset($error_message)): ?>
                <div class="error-message"><?php echo $error_message; ?></div>
            <?php endif; ?>
            <form method="POST">
                <div class="row row-cols-5 g-3">
                    <div class="col mb-3">
                        <label class="form-label"><i class="fas fa-user"></i> اسم العميل</label>
                        <input type="text" class="form-control" name="name" placeholder="الاسم" required>
                    </div>
                    <div class="col mb-3">
                        <label class="form-label"><i class="fas fa-phone"></i> التليفون</label>
                        <input type="text" class="form-control" name="phone" placeholder="التليفون" required>
                    </div>
                    <div class="col mb-3">
                        <label class="form-label"><i class="fas fa-map-marker-alt"></i> العنوان</label>
                        <input type="text" class="form-control" name="address" placeholder="العنوان" required>
                    </div>
                    <div class="col mb-3">
                        <label class="form-label"><i class="fas fa-id-card"></i> رقم البطاقة</label>
                        <input type="text" class="form-control" name="id_number" placeholder="رقم البطاقة" required>
                    </div>
                    <div class="col mb-3">
                        <label class="form-label"><i class="fas fa-money-bill-wave"></i> ديون سابقة</label>
                        <input type="number" step="0.01" class="form-control" name="previous_debt" placeholder="الديون" required>
                    </div>
                    <div class="col mb-3">
                        <button type="submit" class="btn btn-add" name="add_client"><i class="fas fa-plus"></i> إضافة</button>
                    </div>
                    <div class="col mb-3">
                        <button type="button" class="btn btn-cancel" onclick="window.location.href='dashboard.php'"><i class="fas fa-times"></i> إلغاء</button>
                    </div>
                </div>
            </form>
        </div>

        <div class="total-debt-box">
            مجموع الديون: <span id="totalDebt"><?php echo number_format($total_debt, 2); ?></span> ج.م
        </div>

        <div class="card">
            <h2><i class="fas fa-table me-2"></i> قائمة العملاء</h2>
            <div class="search-bar">
                <input type="text" class="form-control" id="searchInput" placeholder="ابحث بالاسم أو رقم البطاقة..." onkeyup="searchClients()">
            </div>
            <div class="table-responsive" style="max-height: 50vh; overflow-y: auto;">
                <table class="table table-striped" id="clientsTable">
                    <thead>
                        <tr>
                            <th>اسم العميل</th>
                            <th>التليفون</th>
                            <th>العنوان</th>
                            <th>رقم البطاقة</th>
                            <th>الديون السابقة</th>
                            <th>إجمالي الديون</th>
                            <th>إجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        foreach ($clients as $client):
                        ?>
                            <tr>
                                <td><?php echo htmlspecialchars($client['name']); ?></td>
                                <td><?php echo htmlspecialchars($client['phone']); ?></td>
                                <td><?php echo htmlspecialchars($client['address']); ?></td>
                                <td><?php echo htmlspecialchars($client['id_number']); ?></td>
                                <td><?php echo htmlspecialchars($client['previous_debt']); ?></td>
                                <td id="totalDebt_<?php echo $client['id']; ?>"><?php echo number_format($client['previous_debt'], 2); ?></td>
                                <td>
                                    <button class="btn btn-edit btn-sm me-1" onclick="editClient(<?php echo $client['id']; ?>, '<?php echo htmlspecialchars($client['name']); ?>', '<?php echo htmlspecialchars($client['phone']); ?>', '<?php echo htmlspecialchars($client['address']); ?>', '<?php echo htmlspecialchars($client['id_number']); ?>', '<?php echo htmlspecialchars($client['previous_debt']); ?>')"><i class="fas fa-edit"></i></button>
                                    <button class="btn btn-delete btn-sm me-1" onclick="deleteClient(<?php echo $client['id']; ?>)"><i class="fas fa-trash"></i></button>
                                    <button class="btn btn-debt btn-sm me-1" onclick="showClientDebt(<?php echo $client['id']; ?>, '<?php echo htmlspecialchars($client['name']); ?>', '<?php echo htmlspecialchars($client['previous_debt']); ?>')"><i class="fas fa-money-check"></i></button>
                                    <button class="btn btn-pay btn-sm" onclick="payClientDebt(<?php echo $client['id']; ?>, '<?php echo htmlspecialchars($client['name']); ?>', '<?php echo htmlspecialchars($client['previous_debt']); ?>')"><i class="fas fa-hand-holding-usd"></i></button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Modal لتعديل العميل -->
    <div class="modal fade" id="editClientModal" tabindex="-1" aria-labelledby="editClientModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editClientModalLabel"><i class="fas fa-edit me-2"></i> تعديل العميل</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form method="POST" id="editClientForm">
                        <input type="hidden" name="id" id="edit_id">
                        <div class="row row-cols-5 g-3">
                            <div class="col mb-3">
                                <label class="form-label"><i class="fas fa-user"></i> اسم العميل</label>
                                <input type="text" class="form-control" name="name" id="edit_name" required>
                            </div>
                            <div class="col mb-3">
                                <label class="form-label"><i class="fas fa-phone"></i> التليفون</label>
                                <input type="text" class="form-control" name="phone" id="edit_phone" required>
                            </div>
                            <div class="col mb-3">
                                <label class="form-label"><i class="fas fa-map-marker-alt"></i> العنوان</label>
                                <input type="text" class="form-control" name="address" id="edit_address" required>
                            </div>
                            <div class="col mb-3">
                                <label class="form-label"><i class="fas fa-id-card"></i> رقم البطاقة</label>
                                <input type="text" class="form-control" name="id_number" id="edit_id_number" required>
                            </div>
                            <div class="col mb-3">
                                <label class="form-label"><i class="fas fa-money-bill-wave"></i> ديون سابقة</label>
                                <input type="number" step="0.01" class="form-control" name="previous_debt" id="edit_previous_debt" required>
                            </div>
                            <div class="col mb-3">
                                <button type="submit" class="btn btn-save" name="edit_client"><i class="fas fa-save"></i> حفظ</button>
                            </div>
                            <div class="col mb-3">
                                <button type="button" class="btn btn-cancel" data-bs-dismiss="modal"><i class="fas fa-times"></i> إلغاء</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal لتسديد الدين -->
    <div class="modal fade" id="payDebtModal" tabindex="-1" aria-labelledby="payDebtModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="payDebtModalLabel"><i class="fas fa-hand-holding-usd me-2"></i> تسديد دين العميل</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form method="POST" id="payDebtForm">
                        <input type="hidden" name="id" id="pay_id">
                        <div class="row g-4">
                            <div class="col-md-6 mb-3">
                                <label class="form-label"><i class="fas fa-user"></i> اسم العميل</label>
                                <input type="text" class="form-control" id="pay_name" readonly>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label"><i class="fas fa-money-bill-wave"></i> الدين الحالي</label>
                                <input type="text" class="form-control" id="pay_previous_debt" readonly>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label"><i class="fas fa-money-check"></i> المبلغ المسدد</label>
                                <input type="number" step="0.01" class="form-control" name="payment" id="pay_payment" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <button type="submit" class="btn btn-save" name="pay_debt"><i class="fas fa-save"></i> تسديد</button>
                            </div>
                            <div class="col-md-6 mb-3">
                                <button type="button" class="btn btn-cancel" data-bs-dismiss="modal"><i class="fas fa-times"></i> إلغاء</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // تعديل عميل
        function editClient(id, name, phone, address, id_number, previous_debt) {
            document.getElementById('edit_id').value = id;
            document.getElementById('edit_name').value = name;
            document.getElementById('edit_phone').value = phone;
            document.getElementById('edit_address').value = address;
            document.getElementById('edit_id_number').value = id_number;
            document.getElementById('edit_previous_debt').value = previous_debt;

            const modal = new bootstrap.Modal(document.getElementById('editClientModal'));
            modal.show();
        }

        // حذف عميل
        function deleteClient(id) {
            if (confirm('هل أنت متأكد من حذف هذا العميل؟')) {
                window.location.href = 'clients.php?delete_id=' + id;
            }
        }

        // عرض مدوينات العميل
        function showClientDebt(id, name, debt) {
            alert(`مدوينات العميل: ${name}\nالدين الحالي: ${debt} ج.م`);
        }

        // تسديد دين عميل
        function payClientDebt(id, name, previous_debt) {
            document.getElementById('pay_id').value = id;
            document.getElementById('pay_name').value = name;
            document.getElementById('pay_previous_debt').value = previous_debt;

            const modal = new bootstrap.Modal(document.getElementById('payDebtModal'));
            modal.show();
        }

        // البحث عن العملاء
        function searchClients() {
            const input = document.getElementById('searchInput').value.toLowerCase();
            const table = document.getElementById('clientsTable');
            const rows = table.getElementsByTagName('tr');

            for (let i = 1; i < rows.length; i++) {
                const name = rows[i].getElementsByTagName('td')[0];
                const idNumber = rows[i].getElementsByTagName('td')[3];
                if (name && idNumber) {
                    const nameText = name.textContent || name.innerText;
                    const idNumberText = idNumber.textContent || idNumber.innerText;
                    if (nameText.toLowerCase().indexOf(input) > -1 || idNumberText.toLowerCase().indexOf(input) > -1) {
                        rows[i].style.display = '';
                    } else {
                        rows[i].style.display = 'none';
                    }
                }
            }
        }
    </script>
</body>
</html>