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

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

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

// الحصول على جميع الديون مع معلومات الزبائن
$stmt = $pdo->query("
    SELECT 
        d.id,
        d.amount,
        d.paid,
        d.date,
        c.id as customer_id,
        c.name as customer_name,
        c.phone as customer_phone
    FROM debts d
    JOIN customers c ON d.customer_id = c.id
    ORDER BY d.date DESC
");
$debts = $stmt->fetchAll(PDO::FETCH_ASSOC);

// حساب الإجماليات
$total_debts = 0;
$total_paid = 0;
foreach ($debts as $debt) {
    $total_debts += $debt['amount'];
    $total_paid += $debt['paid'];
}
$total_remaining = $total_debts - $total_paid;
?>
<!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="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_debts, 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 $total_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($total_remaining, 2); ?> DH</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-body">
                <h5 class="card-title mb-4">جميع الديون</h5>
                <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 ($debts as $debt): ?>
                                <?php $remaining = $debt['amount'] - $debt['paid']; ?>
                                <tr>
                                    <td>
                                        <a href="customer_debts.php?id=<?php echo $debt['customer_id']; ?>">
                                            <?php echo htmlspecialchars($debt['customer_name']); ?>
                                        </a>
                                    </td>
                                    <td><?php echo htmlspecialchars($debt['customer_phone']); ?></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 $remaining > 0 ? 'text-danger' : 'text-success'; ?>">
                                        <?php echo number_format($remaining, 2); ?> DH
                                    </td>
                                    <td><?php echo date('Y-m-d', strtotime($debt['date'])); ?></td>
                                    <td>
                                        <?php if ($remaining > 0): ?>
                                            <button type="button" class="btn btn-sm btn-success"
                                                    onclick="showPaymentModal(<?php echo $debt['id']; ?>, <?php echo $remaining; ?>)">
                                                تسجيل دفعة
                                            </button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </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" action="customer_debts.php">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="add_payment">
                        <input type="hidden" name="debt_id" id="payment_debt_id">
                        <input type="hidden" name="customer_id" id="payment_customer_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>
