<?php
// Activation de l'affichage des erreurs pour le débogage
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Démarrage de la capture des erreurs
ob_start();

try {
    require_once 'config/init.php';
    require_once 'includes/auth.php';
    requireAuth();

    $db = getDB();

    // Vérification des permissions du dossier database
    $db_dir = dirname(DB_FILE);
    if (!is_dir($db_dir)) {
        throw new Exception("Le dossier database n'existe pas: " . $db_dir);
    }
    if (!is_writable($db_dir)) {
        throw new Exception("Le dossier database n'est pas accessible en écriture: " . $db_dir);
    }

    // Get date range from query parameters or set defaults
    $start_date = $_GET['start_date'] ?? date('Y-m-01');
    $end_date = $_GET['end_date'] ?? date('Y-m-t');

    // Get consumption tiers
    $tiers_result = $db->query('SELECT * FROM consumption_tiers ORDER BY start_range');
    if ($tiers_result === false) {
        throw new Exception("Erreur lors de la récupération des tiers: " . $db->lastErrorMsg());
    }
    $tiers = [];
    while ($row = $tiers_result->fetchArray(SQLITE3_ASSOC)) {
        $tiers[] = $row;
    }

    // Get settings
    $settings_result = $db->query('SELECT * FROM settings LIMIT 1');
    if ($settings_result === false) {
        throw new Exception("Erreur lors de la récupération des paramètres: " . $db->lastErrorMsg());
    }
    $settings = $settings_result->fetchArray(SQLITE3_ASSOC);

    // Calculate monthly totals
    $consumption_query = "
        SELECT 
            strftime('%Y-%m', c.reading_date) as month,
            COUNT(DISTINCT c.subscriber_id) as subscriber_count,
            SUM(c.current_reading - c.previous_reading) as total_consumption,
            SUM(i.fixed_fees) as total_fixed_fees,
            SUM(i.collective_entitlement_amount) as total_collective_entitlement,
            SUM(i.consumption_amount) as total_consumption_amount,
            SUM(i.penalties) as total_penalties,
            SUM(i.total_amount) as grand_total,
            AVG(s.family_members) as avg_family_members
        FROM consumption c
        JOIN invoices i ON c.id = i.consumption_id
        JOIN subscribers s ON c.subscriber_id = s.id
        WHERE c.reading_date BETWEEN :start_date AND :end_date
        GROUP BY strftime('%Y-%m', c.reading_date)
        ORDER BY month DESC
    ";

    $stmt = $db->prepare($consumption_query);
    $stmt->bindValue(':start_date', $start_date);
    $stmt->bindValue(':end_date', $end_date);
    $result = $stmt->execute();
    
    $monthly_totals = [];
    while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
        $monthly_totals[] = $row;
    }

    // Calculate consumption ranges statistics
    $consumption_ranges_query = "
        SELECT 
            CASE 
                WHEN (c.current_reading - c.previous_reading) = 0 THEN 'بدون استهلاك'
                WHEN (c.current_reading - c.previous_reading) < :threshold THEN 'أقل من العتبة'
                ELSE 'أكثر من العتبة'
            END as consumption_range,
            COUNT(*) as count,
            SUM(c.current_reading - c.previous_reading) as total_consumption,
            SUM(i.fixed_fees) as total_fixed_fees,
            SUM(i.collective_entitlement_amount) as total_collective_entitlement,
            SUM(i.consumption_amount) as total_consumption_amount,
            SUM(i.penalties) as total_penalties,
            SUM(i.total_amount) as total_amount,
            AVG(s.family_members) as avg_family_members
        FROM consumption c
        JOIN invoices i ON c.id = i.consumption_id
        JOIN subscribers s ON c.subscriber_id = s.id
        WHERE c.reading_date BETWEEN :start_date AND :end_date
        GROUP BY consumption_range
        ORDER BY 
            CASE consumption_range
                WHEN 'بدون استهلاك' THEN 1
                WHEN 'أقل من العتبة' THEN 2
                ELSE 3
            END
    ";

    $stmt = $db->prepare($consumption_ranges_query);
    $stmt->bindValue(':start_date', $start_date);
    $stmt->bindValue(':end_date', $end_date);
    $stmt->bindValue(':threshold', $settings['consumption_threshold'], SQLITE3_FLOAT);
    $result = $stmt->execute();
    
    $consumption_ranges = [];
    while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
        $consumption_ranges[] = $row;
    }
?>
<!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 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">
    <style>
        @media print {
            .no-print {
                display: none !important;
            }
            .container-fluid {
                width: 100% !important;
                padding: 0 !important;
            }
            .card {
                break-inside: avoid;
                border: none !important;
                box-shadow: none !important;
            }
            .table {
                border-collapse: collapse !important;
                width: 100% !important;
            }
            .table th, .table td {
                background-color: white !important;
                border: 1px solid #dee2e6 !important;
                padding: 8px !important;
            }
            @page {
                size: A4;
                margin: 1.5cm;
            }
        }
        
        /* Screen styles */
        .table {
            width: 100%;
            margin-bottom: 1rem;
            border: 1px solid #dee2e6;
        }
        .table th {
            background-color: #f8f9fa;
            font-weight: 600;
            text-align: right;
        }
        .table td, .table th {
            padding: 12px;
            vertical-align: middle;
        }
        .card {
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            margin-bottom: 2rem;
        }
        .card-header {
            background-color: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
            padding: 1rem;
        }
        .card-body {
            padding: 1.5rem;
        }
        .summary-box {
            background-color: #f8f9fa;
            border-radius: 0.25rem;
            padding: 1rem;
            margin-bottom: 1rem;
        }
        .summary-value {
            font-size: 1.25rem;
            font-weight: 600;
            color: #0d6efd;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <?php include 'includes/sidebar.php'; ?>

            <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 no-print">
                    <h1 class="h2">تقرير المستحقات</h1>
                    <div>
                        <button class="btn btn-primary" onclick="window.print()">
                            <i class="bi bi-printer"></i> طباعة التقرير
                        </button>
                    </div>
                </div>

                <!-- Date Filter Form -->
                <div class="card mb-4 no-print">
                    <div class="card-body">
                        <form class="row g-3 align-items-center" method="GET">
                            <div class="col-auto">
                                <label for="start_date" class="form-label">من تاريخ:</label>
                                <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo $start_date; ?>">
                            </div>
                            <div class="col-auto">
                                <label for="end_date" class="form-label">إلى تاريخ:</label>
                                <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo $end_date; ?>">
                            </div>
                            <div class="col-auto">
                                <label class="form-label">&nbsp;</label>
                                <button type="submit" class="btn btn-primary d-block">تصفية</button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Print Header -->
                <div class="d-none d-print-block text-center mb-4">
                    <h1 class="mb-3">تقرير المستحقات</h1>
                    <p class="mb-1">الفترة من: <?php echo date('Y/m/d', strtotime($start_date)); ?></p>
                    <p>إلى: <?php echo date('Y/m/d', strtotime($end_date)); ?></p>
                </div>

                <!-- Monthly Summary -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="card-title mb-0">ملخص شهري</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <th>الشهر</th>
                                        <th>عدد المشتركين</th>
                                        <th>الاستهلاك الكلي (م³)</th>
                                        <th>المستحقات الثابتة</th>
                                        <th>مبلغ الاستهلاك</th>
                                        <th>المجموع الكلي</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($monthly_totals as $month): ?>
                                    <tr>
                                        <td><?php echo date('Y-m', strtotime($month['month'])); ?></td>
                                        <td><?php echo number_format($month['subscriber_count']); ?></td>
                                        <td><?php echo number_format($month['total_consumption'], 2); ?></td>
                                        <td><?php echo number_format($month['total_fixed_fees'], 2); ?></td>
                                        <td><?php echo number_format($month['total_consumption_amount'], 2); ?></td>
                                        <td><?php echo number_format($month['grand_total'], 2); ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Consumption Ranges -->
               
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

<?php
} catch (Exception $e) {
    // Log l'erreur dans un fichier
    $log_file = __DIR__ . '/logs/error.log';
    $log_dir = dirname($log_file);
    
    if (!file_exists($log_dir)) {
        mkdir($log_dir, 0755, true);
    }
    
    $error_message = date('Y-m-d H:i:s') . " - Error: " . $e->getMessage() . "\n" . 
                     "Stack trace: " . $e->getTraceAsString() . "\n\n";
    
    error_log($error_message, 3, $log_file);
    
    // Affiche un message d'erreur générique pour l'utilisateur
    http_response_code(500);
    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
        die(json_encode(['error' => 'Une erreur est survenue. Veuillez contacter l\'administrateur.']));
    } else {
        ?>
        <!DOCTYPE html>
        <html dir="rtl" lang="ar">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Erreur</title>
            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
        </head>
        <body>
            <div class="container mt-5">
                <div class="alert alert-danger" role="alert">
                    <h4 class="alert-heading">عذراً!</h4>
                    <p>حدث خطأ في النظام. يرجى الاتصال بمسؤول النظام.</p>
                    <hr>
                    <p class="mb-0">
                        <a href="index.php" class="btn btn-outline-danger">العودة إلى الصفحة الرئيسية</a>
                    </p>
                </div>
            </div>
        </body>
        </html>
        <?php
        exit;
    }
}

// Si tout va bien, on continue avec le reste du code
$content = ob_get_clean();
echo $content;
