<?php
ob_start(); // Start output buffering

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

// Désactiver l'affichage de la barre de navigation pour cette page
define('HIDE_NAVBAR', true);

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

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

// Récupérer les statistiques
// Nombre total de membres
$stmt = $db->query("SELECT COUNT(*) as total FROM members");
$members_count = $stmt->fetch(PDO::FETCH_ASSOC)['total'];

// Nombre d'activités par statut
$stmt = $db->query("SELECT COUNT(*) as total FROM activities");
$activities_count = $stmt->fetch(PDO::FETCH_ASSOC)['total'];

// Statistiques financières
$stmt = $db->query("
    SELECT 
        COALESCE(SUM(CASE WHEN type = 'income' THEN amount ELSE 0 END), 0) as total_income,
        COALESCE(SUM(CASE WHEN type = 'expense' THEN amount ELSE 0 END), 0) as total_expense,
        COALESCE(SUM(CASE WHEN type = 'transfer' THEN amount ELSE 0 END), 0) as total_transfers
    FROM financial_transactions
");
$financial_stats = $stmt->fetch(PDO::FETCH_ASSOC);

// Get category totals
$stmt = $db->query("
    SELECT 
        ft.type,
        CASE 
            WHEN ft.type = 'income' THEN ic.name
            WHEN ft.type = 'expense' THEN ec.name
        END as category_name,
        SUM(ft.amount) as total_amount,
        COUNT(*) as transaction_count
    FROM financial_transactions ft
    LEFT JOIN income_categories ic ON ft.type = 'income' AND ft.category_id = ic.id
    LEFT JOIN expense_categories ec ON ft.type = 'expense' AND ft.category_id = ec.id
    WHERE ft.type IN ('income', 'expense')
    GROUP BY ft.type, ft.category_id, category_name
    ORDER BY ft.type, category_name
");
$category_totals = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get account balances
$stmt = $db->query("
    SELECT 
        'bank' as account_type,
        bank_name as account_name,
        balance
    FROM bank_accounts
    WHERE status = 'active'
    UNION ALL
    SELECT 
        'cash' as account_type,
        name as account_name,
        balance
    FROM cash_funds
    WHERE status = 'active'
    ORDER BY account_type, account_name
");
$account_balances = $stmt->fetchAll(PDO::FETCH_ASSOC);

$total_income = $financial_stats['total_income'];
$total_expenses = $financial_stats['total_expense'];
$total_transfers = $financial_stats['total_transfers'];
$total_balance = $total_income - $total_expenses;

// Récupérer les paramètres de l'association
$stmt = $db->query("SELECT * FROM association_settings WHERE id = 1");
$settings = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<!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.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        @media print {
            @page {
                size: A4;
                margin: 1.5cm;
            }
            body {
                font-size: 12pt;
                line-height: 1.3;
                background: none;
                margin: 0;
                padding: 0;
            }
            .no-print, .no-print * {
                display: none !important;
            }
            #wrapper, #content {
                margin: 0 !important;
                padding: 0 !important;
            }
            .navbar, .sidebar, #sidebarCollapse {
                display: none !important;
            }
            .container-fluid {
                padding: 0 !important;
                margin: 0 !important;
                width: 100% !important;
            }
            .card {
                border: 1px solid #000 !important;
                margin-bottom: 20px !important;
            }
            .card-header {
                background-color: #f8f9fa !important;
                border-bottom: 1px solid #000 !important;
            }
        }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .page-header {
            text-align: center;
            margin-bottom: 30px;
        }
        .association-logo {
            max-width: 100px;
            height: auto;
            margin-bottom: 10px;
        }
        .report-title {
            font-size: 24px;
            font-weight: bold;
            margin: 20px 0;
            text-align: center;
        }
        .stats-card {
            margin-bottom: 20px;
        }
        .stat-value {
            font-size: 24px;
            font-weight: bold;
        }
        .stat-label {
            color: #666;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <!-- Print Button -->
    <div class="container-fluid mb-4 no-print">
        <button class="btn btn-success" onclick="window.print()">
            <i class="bi bi-printer"></i> طباعة التقرير
        </button>
    </div>

    <div class="container-fluid">
        <!-- Report Header -->
        <div class="page-header">
        <img src="uploads/association_logo.png" height="40px" alt="شعار الجمعية" class="association-logo">
           
            <h1><?php echo htmlspecialchars($settings['name'] ?? 'الجمعية'); ?></h1>
            <p><?php echo htmlspecialchars($settings['address'] ?? ''); ?></p>
            <p>الهاتف: <?php echo htmlspecialchars($settings['phone'] ?? ''); ?></p>
        </div>

        <div class="report-title">التقرير المالي والإحصائيات</div>
        <p class="text-center mb-4">تاريخ التقرير: <?php echo date('Y/m/d'); ?></p>

        <!-- Statistics Summary -->
        <div class="row">
            <!-- Membership Stats -->
            <div class="col-md-6 mb-4">
                <div class="card stats-card h-100">
                    <div class="card-header">
                        <h5 class="card-title mb-0">إحصائيات العضوية</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-12 mb-3">
                                <div class="stat-value"><?php echo formatNumber($members_count); ?></div>
                                <div class="stat-label">عدد الأعضاء</div>
                            </div>
                            <div class="col-12">
                                <div class="stat-value"><?php echo formatNumber($activities_count); ?></div>
                                <div class="stat-label">عدد الأنشطة</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Financial Stats -->
            <div class="col-md-6 mb-4">
                <div class="card stats-card h-100">
                    <div class="card-header">
                        <h5 class="card-title mb-0">الإحصائيات المالية</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-12 mb-3">
                                <div class="stat-value text-success"><?php echo formatNumber($total_income, 2); ?> درهم</div>
                                <div class="stat-label">مجموع المداخيل</div>
                            </div>
                            <div class="col-12 mb-3">
                                <div class="stat-value text-danger"><?php echo formatNumber($total_expenses, 2); ?> درهم</div>
                                <div class="stat-label">مجموع المصاريف</div>
                            </div>
                            <div class="col-12">
                                <div class="stat-value <?php echo $total_balance >= 0 ? 'text-success' : 'text-danger'; ?>">
                                    <?php echo formatNumber($total_balance, 2); ?> درهم
                                </div>
                                <div class="stat-label">الرصيد الإجمالي</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Detailed Financial Report -->
        <div class="row">
            <!-- Category Breakdown -->
            <div class="col-12 mb-4">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">تفاصيل المداخيل والمصاريف حسب التصنيف</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <!-- Income Categories -->
                            <div class="col-md-6">
                                <h6 class="text-success mb-3">المداخيل حسب التصنيف</h6>
                                <table class="table table-bordered">
                                    <thead>
                                        <tr>
                                            <th>التصنيف</th>
                                            <th>المبلغ</th>
                                            <th>عدد العمليات</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        $total_income_count = 0;
                                        foreach ($category_totals as $cat): 
                                            if ($cat['type'] === 'income'):
                                                $total_income_count += $cat['transaction_count'];
                                        ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($cat['category_name'] ?? 'بدون تصنيف'); ?></td>
                                            <td class="text-start"><?php echo formatNumber($cat['total_amount'], 2); ?> درهم</td>
                                            <td class="text-center"><?php echo $cat['transaction_count']; ?></td>
                                        </tr>
                                        <?php 
                                            endif;
                                        endforeach; 
                                        ?>
                                        <tr class="table-success">
                                            <td><strong>المجموع</strong></td>
                                            <td class="text-start"><strong><?php echo formatNumber($total_income, 2); ?> درهم</strong></td>
                                            <td class="text-center"><strong><?php echo $total_income_count; ?></strong></td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                            
                            <!-- Expense Categories -->
                            <div class="col-md-6">
                                <h6 class="text-danger mb-3">المصاريف حسب التصنيف</h6>
                                <table class="table table-bordered">
                                    <thead>
                                        <tr>
                                            <th>التصنيف</th>
                                            <th>المبلغ</th>
                                            <th>عدد العمليات</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        $total_expense_count = 0;
                                        foreach ($category_totals as $cat): 
                                            if ($cat['type'] === 'expense'):
                                                $total_expense_count += $cat['transaction_count'];
                                        ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($cat['category_name'] ?? 'بدون تصنيف'); ?></td>
                                            <td class="text-start"><?php echo formatNumber($cat['total_amount'], 2); ?> درهم</td>
                                            <td class="text-center"><?php echo $cat['transaction_count']; ?></td>
                                        </tr>
                                        <?php 
                                            endif;
                                        endforeach; 
                                        ?>
                                        <tr class="table-danger">
                                            <td><strong>المجموع</strong></td>
                                            <td class="text-start"><strong><?php echo formatNumber($total_expenses, 2); ?> درهم</strong></td>
                                            <td class="text-center"><strong><?php echo $total_expense_count; ?></strong></td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Account Balances -->
            <div class="col-12 mb-4">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">أرصدة الحسابات والصناديق</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <!-- Bank Accounts -->
                            <div class="col-md-6">
                                <h6 class="mb-3">الحسابات البنكية</h6>
                                <table class="table table-bordered">
                                    <thead>
                                        <tr>
                                            <th>الحساب</th>
                                            <th>الرصيد</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        $total_bank_balance = 0;
                                        foreach ($account_balances as $account): 
                                            if ($account['account_type'] === 'bank'):
                                                $total_bank_balance += $account['balance'];
                                        ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($account['account_name']); ?></td>
                                            <td class="text-start"><?php echo formatNumber($account['balance'], 2); ?> درهم</td>
                                        </tr>
                                        <?php 
                                            endif;
                                        endforeach; 
                                        ?>
                                        <tr class="table-primary">
                                            <td><strong>المجموع</strong></td>
                                            <td class="text-start"><strong><?php echo formatNumber($total_bank_balance, 2); ?> درهم</strong></td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                            
                            <!-- Cash Funds -->
                            <div class="col-md-6">
                                <h6 class="mb-3">صناديق النقد</h6>
                                <table class="table table-bordered">
                                    <thead>
                                        <tr>
                                            <th>الصندوق</th>
                                            <th>الرصيد</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        $total_cash_balance = 0;
                                        foreach ($account_balances as $account): 
                                            if ($account['account_type'] === 'cash'):
                                                $total_cash_balance += $account['balance'];
                                        ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($account['account_name']); ?></td>
                                            <td class="text-start"><?php echo formatNumber($account['balance'], 2); ?> درهم</td>
                                        </tr>
                                        <?php 
                                            endif;
                                        endforeach; 
                                        ?>
                                        <tr class="table-info">
                                            <td><strong>المجموع</strong></td>
                                            <td class="text-start"><strong><?php echo formatNumber($total_cash_balance, 2); ?> درهم</strong></td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Report Footer -->
        <div class="text-start mt-4">
            <p>تاريخ الطباعة: <?php echo date('Y/m/d H:i'); ?></p>
        </div>
    </div>

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