<?php
session_start();
require_once 'config/db.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$db = new Database();
$pdo = $db->getConnection();

// البحث عن الزبائن
$search = $_GET['search'] ?? '';
$search_condition = $search ? "WHERE name LIKE :search OR phone LIKE :search" : "";

try {
    // استرجاع قائمة الزبائن مع إجمالي ديونهم
    $query = "
        SELECT 
            c.id,
            c.name,
            c.phone,
            c.created_at,
            COALESCE(SUM(d.amount), 0) as total_debt,
            COALESCE(SUM(d.paid), 0) as total_paid
        FROM customers c
        LEFT JOIN debts d ON d.customer_id = c.id
        $search_condition
        GROUP BY c.id
        ORDER BY c.name
    ";
    
    $stmt = $pdo->prepare($query);
    if ($search) {
        $search_param = "%$search%";
        $stmt->bindParam(':search', $search_param);
    }
    $stmt->execute();
    $customers = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    $error = "حدث خطأ في قاعدة البيانات: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إدارة الزبائن - نظام إدارة البقالة</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/css/style.css" rel="stylesheet">
</head>
<body>
   
    <?php include 'includes/header.php'; ?>

    <div class="container mt-4">
        <?php if (isset($_SESSION['message'])): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <?php 
                echo htmlspecialchars($_SESSION['message']);
                unset($_SESSION['message']);
                ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>إدارة الزبائن</h2>
            <a href="customer_add.php" class="btn btn-primary">
                <i class="fas fa-plus"></i> إضافة زبون جديد
            </a>
        </div>

        <!-- بحث -->
        <div class="card mb-4">
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-8">
                        <input type="text" class="form-control" name="search" 
                               placeholder="البحث بالاسم أو رقم الهاتف..."
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    <div class="col-md-4">
                        <button type="submit" class="btn btn-primary w-100">بحث</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- قائمة الزبائن -->
        <div class="card">
            <div class="card-body">
                <?php if (isset($error)): ?>
                    <div class="alert alert-danger">
                        <?php echo htmlspecialchars($error); ?>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>الاسم</th>
                                    <th>رقم الهاتف</th>
                                    <th>إجمالي الديون</th>
                                    <th>المدفوع</th>
                                    <th>المتبقي</th>
                                    <th>تاريخ التسجيل</th>
                                    <th>الإجراءات</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($customers as $customer): ?>
                                    <?php
                                    $remaining = $customer['total_debt'] - $customer['total_paid'];
                                    $status_class = $remaining > 0 ? 'text-danger' : 'text-success';
                                    ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($customer['name']); ?></td>
                                        <td><?php echo htmlspecialchars($customer['phone']); ?></td>
                                        <td><?php echo number_format($customer['total_debt'], 2); ?> DH</td>
                                        <td><?php echo number_format($customer['total_paid'], 2); ?> DH</td>
                                        <td class="<?php echo $status_class; ?>">
                                            <?php echo number_format($remaining, 2); ?> DH
                                        </td>
                                        <td><?php echo date('Y-m-d', strtotime($customer['created_at'])); ?></td>
                                        <td>
                                            <div class="btn-group">
                                                <a href="customer_debts.php?id=<?php echo $customer['id']; ?>" 
                                                   class="btn btn-sm btn-info">الديون</a>
                                                <a href="customer_edit.php?id=<?php echo $customer['id']; ?>" 
                                                   class="btn btn-sm btn-primary">تعديل</a>
                                                <button type="button" class="btn btn-sm btn-danger"
                                                        onclick="deleteCustomer(<?php echo $customer['id']; ?>)">
                                                    حذف
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function deleteCustomer(customerId) {
            if (confirm('هل أنت متأكد من حذف هذا الزبون؟ سيتم حذف جميع الديون المرتبطة به.')) {
                fetch('api/delete_customer.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ id: customerId })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        location.reload();
                    } else {
                        alert(data.error || 'حدث خطأ أثناء حذف الزبون');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('حدث خطأ أثناء حذف الزبون');
                });
            }
        }
    </script>
</body>
</html>
