<?php
session_start();
require_once __DIR__ . '/db/config.php';
require_once __DIR__ . '/includes/permissions.php';
require_once __DIR__ . '/includes/settings.php';

if (!isLoggedIn() || (!canView('charity_members') && !canView('charity_plans'))) {
    exit("لا توجد صلاحية للوصول لهذه الصفحة.");
}

$settings = get_settings();
$db = db();

// Fetch Plans
$plans_stmt = $db->query("SELECT * FROM charity_plans ORDER BY created_at DESC");
$plans = $plans_stmt->fetchAll(PDO::FETCH_ASSOC);

$total_plans = count($plans);
$completed_plans = 0;
$total_target = 0;
$total_achieved = 0;

foreach ($plans as $plan) {
    if ($plan['status'] === 'completed') {
        $completed_plans++;
    }
    $total_target += $plan['target_value'];
    $total_achieved += $plan['achieved_value'];
}

$completion_rate = $total_plans > 0 ? round(($completed_plans / $total_plans) * 100) : 0;
$kpi_score = $total_target > 0 ? min(100, round(($total_achieved / $total_target) * 100)) : 0;
$overall_score = round(($completion_rate * 0.4) + ($kpi_score * 0.6));

// Fetch Members
$members_stmt = $db->query("SELECT * FROM charity_members ORDER BY name ASC");
$members = $members_stmt->fetchAll(PDO::FETCH_ASSOC);

$status_labels = [
    'pending' => 'قيد الانتظار',
    'in_progress' => 'قيد التنفيذ',
    'completed' => 'مكتمل',
    'cancelled' => 'ملغي'
];
?>
<!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.rtl.min.css" rel="stylesheet">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700&display=swap');
        body { font-family: 'Tajawal', sans-serif; background-color: #fff; color: #000; }
        .print-header { border-bottom: 2px solid #333; padding-bottom: 20px; margin-bottom: 30px; display: flex; justify-content: space-between; align-items: center; }
        .print-logo { max-height: 80px; }
        .section-title { background-color: #f8f9fa; padding: 10px; border-radius: 5px; border: 1px solid #ddd; font-weight: bold; margin-bottom: 20px; margin-top: 40px;}
        .kpi-box { border: 1px solid #dee2e6; border-radius: 5px; padding: 15px; text-align: center; background: #f8f9fa;}
        table { width: 100%; margin-top: 15px; margin-bottom: 15px; border-collapse: collapse; }
        th, td { border: 1px solid #dee2e6; padding: 8px; text-align: right; }
        th { background-color: #f1f3f5; }
        @media print {
            body { margin: 0; padding: 0; font-size: 10pt; }
            .btn-print { display: none !important; }
            @page { margin: 1cm; size: A4; }
            .container { width: 100% !important; max-width: none !important; padding: 0 !important; }
            .print-header { padding-bottom: 10px; margin-bottom: 15px; }
            .print-logo { max-height: 60px; }
            h2.fw-bold { font-size: 16pt; }
            p.fs-5 { font-size: 12pt !important; }
            h3.text-decoration-underline { font-size: 14pt; margin-bottom: 15px !important; }
            .section-title { margin-top: 15px; margin-bottom: 10px; padding: 5px 10px; font-size: 11pt; }
            .kpi-box { padding: 10px; }
            .kpi-box h2 { font-size: 14pt; margin: 0; }
            .kpi-box h5 { font-size: 10pt; margin-bottom: 2px; }
            table { margin-top: 10px; margin-bottom: 10px; }
            th, td { padding: 4px 6px; font-size: 9pt; }
            .page-break { page-break-before: auto; } /* Removed forced page break */
            .mb-5 { margin-bottom: 15px !important; }
            .py-4 { padding-top: 10px !important; padding-bottom: 10px !important; }
            .mt-5 { margin-top: 20px !important; }
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <!-- Print Button -->
        <div class="text-start mb-4 btn-print">
            <button onclick="window.print()" class="btn btn-primary"><i class="fas fa-print me-2"></i> طباعة التقرير</button>
            <button onclick="window.close()" class="btn btn-secondary">إغلاق</button>
        </div>

        <!-- Header -->
        <div class="print-header">
            <div>
                <h2 class="mb-1 fw-bold"><?= htmlspecialchars($settings['site_name']) ?></h2>
                <p class="mb-0 text-muted fs-5">تقرير الجمعية الشامل (الخطط، الأهداف والأعضاء)</p>
                <small>تاريخ التقرير: <?= date('Y-m-d') ?></small>
            </div>
            <div>
                <?php if (!empty($settings['site_logo'])): ?>
                    <img src="<?= htmlspecialchars($settings['site_logo']) ?>" class="print-logo" alt="Logo">
                <?php endif; ?>
            </div>
        </div>

        <!-- KPI Summary -->
        <h3 class="text-center text-decoration-underline mb-4 fw-bold">التقييم العام للجمعية</h3>
        <div class="row mb-5">
            <div class="col-4">
                <div class="kpi-box">
                    <h5 class="text-muted mb-2">التقييم العام</h5>
                    <h2 class="fw-bold mb-0"><?= $overall_score ?>%</h2>
                </div>
            </div>
            <div class="col-4">
                <div class="kpi-box">
                    <h5 class="text-muted mb-2">إنجاز المستهدفات</h5>
                    <h2 class="fw-bold mb-0 text-success"><?= $kpi_score ?>%</h2>
                    <small class="text-muted"><?= $total_achieved ?> من <?= $total_target ?></small>
                </div>
            </div>
            <div class="col-4">
                <div class="kpi-box">
                    <h5 class="text-muted mb-2">إنجاز الخطط</h5>
                    <h2 class="fw-bold mb-0 text-info"><?= $completion_rate ?>%</h2>
                    <small class="text-muted"><?= $completed_plans ?> من <?= $total_plans ?></small>
                </div>
            </div>
        </div>

        <!-- Plans Table -->
        <div class="section-title">1. سجل الخطط والأهداف</div>
        <?php if (empty($plans)): ?>
            <div class="text-muted text-center fst-italic py-3 border">لا توجد خطط مضافة.</div>
        <?php else: ?>
            <table>
                <thead>
                    <tr>
                        <th style="width: 40px; text-align: center;">م</th>
                        <th>الخطة / الهدف</th>
                        <th>الفترة</th>
                        <th>المستهدف</th>
                        <th>المحقق</th>
                        <th>النسبة</th>
                        <th>الحالة</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($plans as $index => $plan): 
                        $plan_rate = $plan['target_value'] > 0 ? min(100, round(($plan['achieved_value'] / $plan['target_value']) * 100)) : 0;
                    ?>
                        <tr>
                            <td style="text-align: center;"><?= $index + 1 ?></td>
                            <td>
                                <strong><?= htmlspecialchars($plan['title']) ?></strong>
                                <?php if($plan['description']): ?>
                                    <br><small class="text-muted"><?= htmlspecialchars($plan['description']) ?></small>
                                <?php endif; ?>
                            </td>
                            <td class="small">
                                من <?= $plan['start_date'] ?><br>إلى <?= $plan['end_date'] ?>
                            </td>
                            <td><?= number_format($plan['target_value']) ?></td>
                            <td><?= number_format($plan['achieved_value']) ?></td>
                            <td><?= $plan_rate ?>%</td>
                            <td><?= $status_labels[$plan['status']] ?? $plan['status'] ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>

        <!-- Members Table -->
        <div class="section-title">2. أعضاء الجمعية</div>
        <?php if (empty($members)): ?>
            <div class="text-muted text-center fst-italic py-3 border">لا يوجد أعضاء مسجلين.</div>
        <?php else: ?>
            <table>
                <thead>
                    <tr>
                        <th style="width: 40px; text-align: center;">م</th>
                        <th>اسم العضو</th>
                        <th>الدور/الصفة</th>
                        <th>رقم الجوال</th>
                        <th>البريد الإلكتروني</th>
                        <th>تاريخ الانضمام</th>
                        <th>الحالة</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($members as $index => $m): ?>
                        <tr>
                            <td style="text-align: center;"><?= $index + 1 ?></td>
                            <td><strong><?= htmlspecialchars($m['name']) ?></strong></td>
                            <td><?= htmlspecialchars($m['role'] ?: '-') ?></td>
                            <td dir="ltr" style="text-align: right;"><?= htmlspecialchars($m['phone'] ?: '-') ?></td>
                            <td dir="ltr" style="text-align: right;"><?= htmlspecialchars($m['email'] ?: '-') ?></td>
                            <td><?= htmlspecialchars($m['join_date'] ?: '-') ?></td>
                            <td><?= $m['status'] == 'active' ? 'نشط' : 'غير نشط' ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>

        <!-- Footer -->
        <div class="mt-5 pt-3 border-top text-center text-muted small">
            هذا التقرير معتمد ومستخرج آلياً من نظام إدارة الجمعية - <?= htmlspecialchars($settings['site_name']) ?>
        </div>
    </div>
    
    <!-- Font Awesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <script>
        window.onload = function() { window.print(); }
    </script>
</body>
</html>