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

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

if (!isset($_GET['id'])) {
    $_SESSION['message'] = 'معرف الزبون غير موجود';
    header('Location: customers.php');
    exit();
}

$customer_id = $_GET['id'];
$db = new Database();
$pdo = $db->getConnection();

try {
    // الحصول على بيانات الزبون
    $stmt = $pdo->prepare("SELECT * FROM customers WHERE id = ?");
    $stmt->execute([$customer_id]);
    $customer = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$customer) {
        $_SESSION['message'] = 'الزبون غير موجود';
        header('Location: customers.php');
        exit();
    }
    
    // الحصول على قائمة الديون
    $stmt = $pdo->prepare("
        SELECT id, amount, paid, date 
        FROM debts 
        WHERE customer_id = ? 
        ORDER BY date DESC
    ");
    $stmt->execute([$customer_id]);
    $debts = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // حساب إجماليات الديون
    $total_debt = array_sum(array_column($debts, 'amount'));
    $total_paid = array_sum(array_column($debts, 'paid'));
    $remaining = $total_debt - $total_paid;
    
} catch (PDOException $e) {
    $_SESSION['message'] = "حدث خطأ: " . $e->getMessage();
    header('Location: customers.php');
    exit();
}

// معالجة إضافة دين جديد
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    try {
        if ($_POST['action'] === 'add_debt') {
            $amount = $_POST['amount'];
            
            $stmt = $pdo->prepare("
                INSERT INTO debts (customer_id, amount, paid, date)
                VALUES (?, ?, 0, CURRENT_TIMESTAMP)
            ");
            $stmt->execute([$customer_id, $amount]);
            
            $_SESSION['message'] = 'تم إضافة الدين بنجاح';
            header("Location: customer_debts.php?id=$customer_id");
            exit();
        }
        elseif ($_POST['action'] === 'add_payment') {
            $debt_id = $_POST['debt_id'];
            $payment = $_POST['payment'];
            
            // التحقق من صحة المبلغ المدفوع
            $stmt = $pdo->prepare("
                SELECT amount, paid 
                FROM debts 
                WHERE id = ? AND customer_id = ?
            ");
            $stmt->execute([$debt_id, $customer_id]);
            $debt = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$debt) {
                throw new Exception('الدين غير موجود');
            }
            
            $remaining_debt = $debt['amount'] - $debt['paid'];
            if ($payment > $remaining_debt) {
                throw new Exception('المبلغ المدفوع أكبر من المبلغ المتبقي');
            }
            
            // تحديث المبلغ المدفوع
            $stmt = $pdo->prepare("
                UPDATE debts 
                SET paid = paid + ? 
                WHERE id = ? AND customer_id = ?
            ");
            $stmt->execute([$payment, $debt_id, $customer_id]);
            
            $_SESSION['message'] = 'تم تسجيل الدفعة بنجاح';
            header("Location: customer_debts.php?id=$customer_id");
            exit();
        }
    } catch (Exception $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/navbar.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; ?>

        <?php if (isset($error)): ?>
            <div class="alert alert-danger">
                <?php echo htmlspecialchars($error); ?>
            </div>
        <?php endif; ?>

        <div class="row mb-4">
            <div class="col-md-6">
                <h2>ديون الزبون: <?php echo htmlspecialchars($customer['name']); ?></h2>
                <?php if ($customer['phone']): ?>
                    <p>رقم الهاتف: <?php echo htmlspecialchars($customer['phone']); ?></p>
                <?php endif; ?>
            </div>
            <div class="col-md-6 text-start">
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addDebtModal">
                    إضافة دين جديد
                </button>
            </div>
        </div>

        <!-- ملخص الديون -->
        <div class="row mb-4">
            <div class="col-md-4">
                <div class="card bg-primary text-white">
                    <div class="card-body">
                        <h5 class="card-title">إجمالي الديون</h5>
                        <p class="card-text display-6"><?php echo number_format($total_debt, 2); ?> DH</p>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card bg-success text-white">
                    <div class="card-body">
                        <h5 class="card-title">إجمالي المدفوع</h5>
                        <p class="card-text display-6"><?php echo number_format($total_paid, 2); ?> DH</p>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card <?php echo $remaining > 0 ? 'bg-danger' : 'bg-success'; ?> text-white">
                    <div class="card-body">
                        <h5 class="card-title">المبلغ المتبقي</h5>
                        <p class="card-text display-6"><?php echo number_format($remaining, 2); ?> DH</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- جدول الديون -->
        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>التاريخ</th>
                                <th>المبلغ</th>
                                <th>المدفوع</th>
                                <th>المتبقي</th>
                                <th>الإجراءات</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($debts as $debt): ?>
                                <?php $debt_remaining = $debt['amount'] - $debt['paid']; ?>
                                <tr>
                                    <td><?php echo date('Y-m-d', strtotime($debt['date'])); ?></td>
                                    <td><?php echo number_format($debt['amount'], 2); ?> DH</td>
                                    <td><?php echo number_format($debt['paid'], 2); ?> DH</td>
                                    <td class="<?php echo $debt_remaining > 0 ? 'text-danger' : 'text-success'; ?>">
                                        <?php echo number_format($debt_remaining, 2); ?> DH
                                    </td>
                                    <td>
                                        <?php if ($debt_remaining > 0): ?>
                                            <button type="button" class="btn btn-sm btn-success"
                                                    onclick="showPaymentModal(<?php echo $debt['id']; ?>, <?php echo $debt_remaining; ?>)">
                                                تسجيل دفعة
                                            </button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- نموذج إضافة دين جديد -->
    <div class="modal fade" id="addDebtModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">إضافة دين جديد</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="add_debt">
                        <div class="mb-3">
                            <label for="amount" class="form-label">المبلغ (DH)</label>
                            <input type="number" class="form-control" id="amount" name="amount" 
                                   step="0.01" min="0" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                        <button type="submit" class="btn btn-primary">إضافة</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- نموذج تسجيل دفعة -->
    <div class="modal fade" id="addPaymentModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">تسجيل دفعة</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="add_payment">
                        <input type="hidden" name="debt_id" id="payment_debt_id">
                        <div class="mb-3">
                            <label for="payment" class="form-label">المبلغ المدفوع (DH)</label>
                            <input type="number" class="form-control" id="payment" name="payment" 
                                   step="0.01" min="0" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                        <button type="submit" class="btn btn-primary">تسجيل</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function showPaymentModal(debtId, remainingAmount) {
            document.getElementById('payment_debt_id').value = debtId;
            const paymentInput = document.getElementById('payment');
            paymentInput.max = remainingAmount;
            paymentInput.value = remainingAmount;
            
            const modal = new bootstrap.Modal(document.getElementById('addPaymentModal'));
            modal.show();
        }
    </script>
</body>
</html>
