<?php
require_once 'config/init.php';
require_once 'includes/auth.php';
requireAuth();

$db = getDB();

// Get total subscribers
$result = $db->query('SELECT COUNT(*) as count FROM subscribers WHERE status = 1');
$subscribersCount = $result->fetchArray()['count'];

// Get total consumption for current period
$result = $db->query('
    SELECT SUM(c.current_reading - c.previous_reading) as total 
    FROM consumption c
    JOIN subscribers s ON c.subscriber_id = s.id
    WHERE s.status = 1 
    AND strftime("%Y-%m", c.reading_date) = strftime("%Y-%m", "now")
');
$totalConsumption = $result->fetchArray()['total'] ?? 0;

// Get total unpaid invoices
$result = $db->query('SELECT SUM(total_amount) as total FROM invoices WHERE status = "unpaid"');
$totalUnpaid = $result->fetchArray()['total'] ?? 0;

// Get total paid invoices
$result = $db->query('SELECT SUM(total_amount) as total FROM invoices WHERE status = "paid"');
$totalPaid = $result->fetchArray()['total'] ?? 0;
?>
<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>لوحة التحكم - نظام إدارة جمعيات توزيع الماء</title>
    <link rel="icon" type="image/x-icon" href="ficoni.png">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        .sidebar {
            min-height: 100vh;
            background: #343a40;
            color: white;
        }
        .sidebar a {
            color: white;
            text-decoration: none;
        }
        .sidebar a:hover {
            background: rgba(255,255,255,0.1);
        }
        .stat-card {
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
        <?php include 'includes/sidebar.php'; ?>
     

            <!-- Main content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">لوحة التحكم</h1>
                </div>

                <!-- Statistics Cards -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="card stat-card bg-primary text-white">
                            <div class="card-body">
                                <h5 class="card-title">عدد المشتركين</h5>
                                <h2 class="card-text"><?php echo number_format($subscribersCount); ?></h2>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card stat-card bg-success text-white">
                            <div class="card-body">
                                <h5 class="card-title">الاستهلاك الشهري (م³)</h5>
                                <h2 class="card-text"><?php echo number_format($totalConsumption, 1); ?></h2>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card stat-card bg-warning text-dark">
                            <div class="card-body">
                                <h5 class="card-title">الفواتير غير المسددة</h5>
                                <h2 class="card-text"><?php echo number_format($totalUnpaid, 2); ?> د.م</h2>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card stat-card bg-info text-white">
                            <div class="card-body">
                                <h5 class="card-title">الفواتير المسددة</h5>
                                <h2 class="card-text"><?php echo number_format($totalPaid, 2); ?> د.م</h2>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Charts -->
                <div class="row">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-body">
                                <h5 class="card-title">الاستهلاك الشهري</h5>
                                <canvas id="consumptionChart"></canvas>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-body">
                                <h5 class="card-title">حالة الفواتير</h5>
                                <canvas id="invoicesChart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Consumption Chart
        const consumptionCtx = document.getElementById('consumptionChart').getContext('2d');
        new Chart(consumptionCtx, {
            type: 'line',
            data: {
                labels: ['يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو'],
                datasets: [{
                    label: 'الاستهلاك (م³)',
                    data: [65, 59, 80, 81, 56, 55],
                    borderColor: 'rgb(75, 192, 192)',
                    tension: 0.1
                }]
            }
        });

        // Invoices Chart
        const invoicesCtx = document.getElementById('invoicesChart').getContext('2d');
        new Chart(invoicesCtx, {
            type: 'doughnut',
            data: {
                labels: ['مسددة', 'غير مسددة'],
                datasets: [{
                    data: [<?php echo $totalPaid; ?>, <?php echo $totalUnpaid; ?>],
                    backgroundColor: ['rgb(40, 167, 69)', 'rgb(255, 193, 7)']
                }]
            }
        });
    </script>
</body>
</html>
