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

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

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

// Fetch committees and members
if (isAdmin()) {
    $committees_query = $db->query("
        SELECT 
            c.id, c.name, c.description,
            (SELECT COUNT(*) FROM committee_plans WHERE committee_id = c.id) as total_plans,
            (SELECT COUNT(*) FROM committee_plans WHERE committee_id = c.id AND status = 'completed') as completed_plans,
            (SELECT COUNT(*) FROM committee_activities WHERE committee_id = c.id) as activities_count
        FROM committees c
        ORDER BY c.name ASC
    ");
    $committees = $committees_query->fetchAll(PDO::FETCH_ASSOC);
} else {
    $committees_query = $db->prepare("
        SELECT 
            c.id, c.name, c.description,
            (SELECT COUNT(*) FROM committee_plans WHERE committee_id = c.id) as total_plans,
            (SELECT COUNT(*) FROM committee_plans WHERE committee_id = c.id AND status = 'completed') as completed_plans,
            (SELECT COUNT(*) FROM committee_activities WHERE committee_id = c.id) as activities_count
        FROM committees c
        JOIN committee_members m ON c.id = m.committee_id
        JOIN charity_members cm ON m.charity_member_id = cm.id
        JOIN users u ON (u.id = cm.user_id) OR (cm.email != '' AND cm.email = u.email) OR (cm.name = u.full_name) OR (cm.name = u.username)
        WHERE u.id = ?
        GROUP BY c.id
        ORDER BY c.name ASC
    ");
    $committees_query->execute([$_SESSION['user_id']]);
    $committees = $committees_query->fetchAll(PDO::FETCH_ASSOC);
}

foreach ($committees as &$c) {
    // Calculate performance score
    $plan_completion_rate = $c['total_plans'] > 0 ? ($c['completed_plans'] / $c['total_plans']) * 100 : 0;
    $activity_score = min(100, $c['activities_count'] * 20); 
    $c['score'] = ($plan_completion_rate * 0.6) + ($activity_score * 0.4);
    
    // Fetch members for this committee
    $members_stmt = $db->prepare("
        SELECT cm.role, u.name as full_name, u.phone 
        FROM committee_members cm 
        JOIN charity_members u ON cm.charity_member_id = u.id 
        WHERE cm.committee_id = ? 
        ORDER BY cm.id DESC
    ");
    $members_stmt->execute([$c['id']]);
    $c['members'] = $members_stmt->fetchAll(PDO::FETCH_ASSOC);
}
unset($c);

// Sort by score descending
usort($committees, function($a, $b) {
    return $b['score'] <=> $a['score'];
});

?>
<!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; }
        .committee-section { margin-bottom: 40px; page-break-inside: avoid; }
        .committee-title { background-color: #f8f9fa; padding: 10px; border-radius: 5px; border: 1px solid #ddd; font-weight: bold; }
        .score-badge { display: inline-block; padding: 5px 10px; border-radius: 20px; background: #e9ecef; border: 1px solid #ccc; font-size: 0.9em; }
        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; }
            .btn-print { display: none !important; }
            @page { margin: 1cm; }
        }
    </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>

        <h3 class="text-center text-decoration-underline mb-4 fw-bold">تقرير تفصيلي بأسماء اللجان وأعضائها</h3>

        <?php if (empty($committees)): ?>
            <div class="alert alert-info text-center">لا توجد لجان مسجلة في النظام.</div>
        <?php else: ?>
            <?php foreach ($committees as $index => $c): ?>
                <div class="committee-section">
                    <div class="committee-title d-flex justify-content-between align-items-center">
                        <span class="fs-5">
                            <?= $index + 1 ?>. <?= htmlspecialchars($c['name']) ?>
                        </span>
                        <div class="score-badge">
                            مؤشر الأداء (KPI): <strong><?= round($c['score']) ?>%</strong>
                        </div>
                    </div>
                    
                    <p class="text-muted small mt-2 mb-2 px-2">
                        <?= htmlspecialchars($c['description']) ?: 'لا يوجد وصف' ?>
                    </p>
                    
                    <div class="px-2 mb-3 small text-secondary">
                        <span class="me-3">إجمالي الخطط: <strong><?= $c['total_plans'] ?></strong></span>
                        <span class="me-3">الخطط المكتملة: <strong><?= $c['completed_plans'] ?></strong></span>
                        <span>إجمالي الأنشطة: <strong><?= $c['activities_count'] ?></strong></span>
                    </div>

                    <?php if (count($c['members']) > 0): ?>
                        <table>
                            <thead>
                                <tr>
                                    <th style="width: 50px; text-align: center;">م</th>
                                    <th>اسم العضو</th>
                                    <th>الدور في اللجنة</th>
                                    <th style="width: 150px;">رقم الهاتف</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($c['members'] as $m_index => $m): ?>
                                    <tr>
                                        <td style="text-align: center;"><?= $m_index + 1 ?></td>
                                        <td><strong><?= htmlspecialchars($m['full_name']) ?></strong></td>
                                        <td><?= htmlspecialchars($m['role']) ?></td>
                                        <td dir="ltr" style="text-align: right;"><?= htmlspecialchars($m['phone'] ?? '-') ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php else: ?>
                        <div class="text-muted fst-italic px-2 py-3 border-bottom border-start border-end mb-4">لا يوجد أعضاء مسجلين في هذه اللجنة حالياً.</div>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        <?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>