<?php
// Fonction pour formater les nombres
function formatNumber($number, $decimals = 0) {
    return number_format($number, $decimals, ',', '.');
}

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../config/database.php';

$database = new Database();
$db = $database->getConnection();
$auth = new Auth($database);

// Get date range from request
$start_date = $_GET['start_date'] ?? date('Y-m-01'); // First day of current month
$end_date = $_GET['end_date'] ?? date('Y-m-t'); // Last day of current month

// Get association info
$stmt = $db->query("SELECT * FROM association_settings WHERE id = 1");
$association = $stmt->fetch(PDO::FETCH_ASSOC);

// Get financial summary
$stmt = $db->prepare("
    SELECT 
        SUM(CASE WHEN type = 'income' THEN amount ELSE 0 END) as total_income,
        SUM(CASE WHEN type = 'expense' THEN amount ELSE 0 END) as total_expense,
        COUNT(DISTINCT CASE WHEN type = 'income' THEN category_id END) as income_categories_count,
        COUNT(DISTINCT CASE WHEN type = 'expense' THEN category_id END) as expense_categories_count
    FROM financial_transactions
    WHERE transaction_date BETWEEN ? AND ?
");
$stmt->execute([$start_date, $end_date]);
$financial_summary = $stmt->fetch(PDO::FETCH_ASSOC);

// Get income by category
$stmt = $db->prepare("
    SELECT 
        ic.name as category_name,
        SUM(ft.amount) as total_amount,
        COUNT(*) as transaction_count
    FROM financial_transactions ft
    JOIN income_categories ic ON ft.category_id = ic.id
    WHERE ft.type = 'income' AND ft.transaction_date BETWEEN ? AND ?
    GROUP BY ft.category_id
    ORDER BY total_amount DESC
");
$stmt->execute([$start_date, $end_date]);
$income_by_category = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get expenses by category
$stmt = $db->prepare("
    SELECT 
        ec.name as category_name,
        SUM(ft.amount) as total_amount,
        COUNT(*) as transaction_count
    FROM financial_transactions ft
    JOIN expense_categories ec ON ft.category_id = ec.id
    WHERE ft.type = 'expense' AND ft.transaction_date BETWEEN ? AND ?
    GROUP BY ft.category_id
    ORDER BY total_amount DESC
");
$stmt->execute([$start_date, $end_date]);
$expenses_by_category = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get activities summary
$stmt = $db->prepare("
    SELECT COUNT(*) as total_activities
    FROM activities
    WHERE date BETWEEN ? AND ?
");
$stmt->execute([$start_date, $end_date]);
$activities_summary = $stmt->fetch(PDO::FETCH_ASSOC);

// Get members summary
$stmt = $db->query("
    SELECT 
        COUNT(*) as total_members,
        COUNT(CASE WHEN role = 'member' THEN 1 END) as regular_members,
        COUNT(CASE WHEN role != 'member' THEN 1 END) as board_members
    FROM members
    WHERE status = 'active'
");
$members_summary = $stmt->fetch(PDO::FETCH_ASSOC);
?>

<div class="container-fluid">
    <!-- Report Header -->
    <div class="row mb-4">
        <div class="col">
            <h2>التقارير والإحصائيات</h2>
        </div>
        <div class="col-auto">
            <a href="?page=print_reports" target="_blank" class="btn btn-success">
                <i class="bi bi-printer"></i> طباعة التقرير
            </a>
        </div>
    </div>

    <!-- Date Range Filter -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="card">
                <div class="card-body">
                    <form method="GET" class="row g-3">
                        <input type="hidden" name="page" value="reports">
                        <div class="col-md-5">
                            <label class="form-label">من تاريخ</label>
                            <input type="date" class="form-control" name="start_date" value="<?php echo $start_date; ?>">
                        </div>
                        <div class="col-md-5">
                            <label class="form-label">إلى تاريخ</label>
                            <input type="date" class="form-control" name="end_date" value="<?php echo $end_date; ?>">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">&nbsp;</label>
                            <button type="submit" class="btn btn-primary w-100">تصفية</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Report Content -->
    <div class="report-content">
        <!-- Association Info -->
        <div class="text-center mb-4">
            <h3><?php echo htmlspecialchars($association['name'] ?? 'الجمعية'); ?></h3>
            <p><?php echo htmlspecialchars($association['address'] ?? ''); ?></p>
            <p>تقرير عن الفترة من <?php echo $start_date; ?> إلى <?php echo $end_date; ?></p>
        </div>

        <!-- Summary Cards -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card bg-success text-white">
                    <div class="card-body">
                        <h5 class="card-title">إجمالي المداخيل</h5>
                        <h3 class="card-text"><?php echo formatNumber($financial_summary['total_income'], 2); ?> درهم</h3>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-danger text-white">
                    <div class="card-body">
                        <h5 class="card-title">إجمالي المصاريف</h5>
                        <h3 class="card-text"><?php echo formatNumber($financial_summary['total_expense'], 2); ?> درهم</h3>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-info text-white">
                    <div class="card-body">
                        <h5 class="card-title">عدد الأنشطة</h5>
                        <h3 class="card-text"><?php echo $activities_summary['total_activities']; ?></h3>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-primary text-white">
                    <div class="card-body">
                        <h5 class="card-title">مجموع الأعضاء</h5>
                        <h3 class="card-text"><?php echo $members_summary['total_members']; ?></h3>
                    </div>
                </div>
            </div>
        </div>

        <!-- Financial Details -->
        <div class="row mb-4">
            <!-- Income Categories -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">تفاصيل المداخيل حسب التصنيف</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>التصنيف</th>
                                        <th>عدد العمليات</th>
                                        <th>المجموع</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($income_by_category as $category): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($category['category_name']); ?></td>
                                        <td><?php echo $category['transaction_count']; ?></td>
                                        <td><?php echo formatNumber($category['total_amount'], 2); ?> درهم</td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Expense Categories -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">تفاصيل المصاريف حسب التصنيف</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>التصنيف</th>
                                        <th>عدد العمليات</th>
                                        <th>المجموع</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($expenses_by_category as $category): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($category['category_name']); ?></td>
                                        <td><?php echo $category['transaction_count']; ?></td>
                                        <td><?php echo formatNumber($category['total_amount'], 2); ?> درهم</td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Members Statistics -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">إحصائيات الأعضاء</h5>
                    </div>
                    <div class="card-body">
                        <div class="row text-center">
                            <div class="col-md-4">
                                <h4>مجموع الأعضاء</h4>
                                <h2><?php echo $members_summary['total_members']; ?></h2>
                            </div>
                            <div class="col-md-4">
                                <h4>أعضاء المكتب</h4>
                                <h2><?php echo $members_summary['board_members']; ?></h2>
                            </div>
                            <div class="col-md-4">
                                <h4>المنخرطون</h4>
                                <h2><?php echo $members_summary['regular_members']; ?></h2>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Report Footer -->
        <div class="row mt-4 print-only">
            <div class="col-12 text-center">
                <p>تم إصدار هذا التقرير بتاريخ: <?php echo date('Y-m-d H:i'); ?></p>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Initialize any charts or visualizations here
    if (typeof Chart !== 'undefined') {
        // Income vs Expenses Chart
        new Chart(document.getElementById('financialChart'), {
            type: 'bar',
            data: {
                labels: ['المداخيل', 'المصاريف'],
                datasets: [{
                    data: [
                        <?php echo $financial_summary['total_income']; ?>,
                        <?php echo $financial_summary['total_expense']; ?>
                    ],
                    backgroundColor: ['#28a745', '#dc3545']
                }]
            },
            options: {
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    }
});
</script>

<!-- Add Chart.js for visualizations -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
