<?php
require_once 'includes/header.php';

if (!canView('committees')) {
    echo "<div class='alert alert-danger'>لا توجد صلاحية للوصول لهذه الصفحة.</div>";
    require_once 'includes/footer.php';
    exit;
}

// Fetch all committees and calculate stats
if (isAdmin()) {
    $stmt = db()->query("
        SELECT 
            c.id, c.name,
            (SELECT COUNT(*) FROM committee_members WHERE committee_id = c.id) as members_count,
            (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 = $stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
    $stmt = db()->prepare("
        SELECT 
            c.id, c.name,
            (SELECT COUNT(*) FROM committee_members WHERE committee_id = c.id) as members_count,
            (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
    ");
    $stmt->execute([$_SESSION['user_id']]);
    $committees = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Overall stats
$total_committees = count($committees);
$total_members = 0;
$total_plans = 0;
$total_completed = 0;
$total_activities = 0;

foreach ($committees as &$c) {
    $total_members += $c['members_count'];
    $total_plans += $c['total_plans'];
    $total_completed += $c['completed_plans'];
    $total_activities += $c['activities_count'];
    
    // Calculate performance score (smart assessment)
    // Score based on: Completed plans (weight 60%) + Activities done (weight 40%)
    // Let's make a simple normalized score out of 100 for visual assessment
    $plan_completion_rate = $c['total_plans'] > 0 ? ($c['completed_plans'] / $c['total_plans']) * 100 : 0;
    
    // Assume an "active" committee should have at least 1 activity per month (say 5 is a good baseline for 100% activity score)
    $activity_score = min(100, $c['activities_count'] * 20); 
    
    // Final composite score
    $score = ($plan_completion_rate * 0.6) + ($activity_score * 0.4);
    $c['score'] = $score;
    
    // Determine badge
    if ($score >= 80) {
        $c['badge'] = '<span class="badge bg-success">ممتاز</span>';
        $c['color'] = 'success';
    } elseif ($score >= 50) {
        $c['badge'] = '<span class="badge bg-primary">جيد</span>';
        $c['color'] = 'primary';
    } elseif ($score > 0) {
        $c['badge'] = '<span class="badge bg-warning text-dark">يحتاج تحسين</span>';
        $c['color'] = 'warning';
    } else {
        $c['badge'] = '<span class="badge bg-danger">غير نشط</span>';
        $c['color'] = 'danger';
    }
}
unset($c);

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

?>

<div class="container-fluid py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="mb-0"><i class="fas fa-chart-pie text-primary me-2"></i> تقييم وتقارير اللجان</h4>
        <div>
            <a href="print_committees_report.php" target="_blank" class="btn btn-outline-primary btn-sm me-2">
                <i class="fas fa-print me-1"></i> طباعة تقرير اللجان والأعضاء
            </a>
            <a href="committees.php" class="btn btn-outline-secondary btn-sm">
                <i class="fas fa-arrow-right me-1"></i> عودة لإدارة اللجان
            </a>
        </div>
    </div>
        </div>
        </a>
    </div>

    <!-- Overview Cards -->
    <div class="row g-3 mb-4">
        <div class="col-md-3">
            <div class="card bg-primary text-white h-100 shadow-sm border-0">
                <div class="card-body d-flex flex-column justify-content-center align-items-center">
                    <i class="fas fa-users fa-2x mb-2 opacity-75"></i>
                    <h5 class="card-title">إجمالي اللجان</h5>
                    <h2 class="mb-0 fw-bold"><?= $total_committees ?></h2>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-success text-white h-100 shadow-sm border-0">
                <div class="card-body d-flex flex-column justify-content-center align-items-center">
                    <i class="fas fa-tasks fa-2x mb-2 opacity-75"></i>
                    <h5 class="card-title">إنجاز الخطط</h5>
                    <h2 class="mb-0 fw-bold">
                        <?= $total_plans > 0 ? round(($total_completed / $total_plans) * 100) : 0 ?>%
                    </h2>
                    <small><?= $total_completed ?> من <?= $total_plans ?> خطة مكتملة</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-info text-white h-100 shadow-sm border-0">
                <div class="card-body d-flex flex-column justify-content-center align-items-center">
                    <i class="fas fa-calendar-check fa-2x mb-2 opacity-75"></i>
                    <h5 class="card-title">إجمالي الأنشطة</h5>
                    <h2 class="mb-0 fw-bold"><?= $total_activities ?></h2>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-warning text-dark h-100 shadow-sm border-0">
                <div class="card-body d-flex flex-column justify-content-center align-items-center">
                    <i class="fas fa-user-friends fa-2x mb-2 opacity-75"></i>
                    <h5 class="card-title">إجمالي الأعضاء</h5>
                    <h2 class="mb-0 fw-bold"><?= $total_members ?></h2>
                </div>
            </div>
        </div>
    </div>

    <!-- Committees Ranking Table -->
    <div class="card shadow-sm border-0">
        <div class="card-header bg-white">
            <h5 class="mb-0"><i class="fas fa-trophy text-warning me-2"></i> ترتيب وتقييم أداء اللجان (الأعلى أداءً)</h5>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="table-light">
                        <tr>
                            <th class="ps-4">الترتيب</th>
                            <th>اللجنة</th>
                            <th class="text-center">الأعضاء</th>
                            <th class="text-center">إنجاز الخطط</th>
                            <th class="text-center">الأنشطة المنجزة</th>
                            <th style="width: 250px;">مؤشر الأداء (KPI)</th>
                            <th class="text-center">التقييم</th>
                            <th class="pe-4"></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($committees)): ?>
                            <tr><td colspan="8" class="text-center p-4">لا توجد لجان مضافة حتى الآن.</td></tr>
                        <?php else: ?>
                            <?php foreach ($committees as $index => $c): ?>
                            <tr>
                                <td class="ps-4">
                                    <?php if ($index == 0 && $c['score'] > 0): ?>
                                        <i class="fas fa-medal text-warning fa-2x"></i>
                                    <?php elseif ($index == 1 && $c['score'] > 0): ?>
                                        <i class="fas fa-medal text-secondary fa-2x"></i>
                                    <?php elseif ($index == 2 && $c['score'] > 0): ?>
                                        <i class="fas fa-medal fa-2x" style="color: #cd7f32;"></i>
                                    <?php else: ?>
                                        <span class="text-muted fw-bold ms-2">#<?= $index + 1 ?></span>
                                    <?php endif; ?>
                                </td>
                                <td class="fw-bold fs-6"><?= htmlspecialchars($c['name']) ?></td>
                                <td class="text-center">
                                    <span class="badge bg-light text-dark border p-2 rounded-circle fs-6"><?= $c['members_count'] ?></span>
                                </td>
                                <td class="text-center">
                                    <div class="d-inline-flex flex-column align-items-center w-75">
                                        <small class="mb-1"><?= $c['completed_plans'] ?> / <?= $c['total_plans'] ?></small>
                                        <div class="progress w-100" style="height: 6px;">
                                            <?php $plan_percent = $c['total_plans'] > 0 ? ($c['completed_plans'] / $c['total_plans']) * 100 : 0; ?>
                                            <div class="progress-bar bg-<?= $c['color'] ?>" role="progressbar" style="width: <?= $plan_percent ?>%"></div>
                                        </div>
                                    </div>
                                </td>
                                <td class="text-center">
                                    <span class="badge bg-light text-dark border p-2 rounded-circle fs-6"><?= $c['activities_count'] ?></span>
                                </td>
                                <td>
                                    <div class="d-flex justify-content-between mb-1 align-items-center">
                                        <span class="text-muted small">نسبة الإنجاز:</span>
                                        <span class="fw-bold <?= 'text-' . $c['color'] ?>"><?= round($c['score']) ?>%</span>
                                    </div>
                                    <div class="progress shadow-sm" style="height: 10px; border-radius: 5px;">
                                        <div class="progress-bar progress-bar-striped progress-bar-animated bg-<?= $c['color'] ?>" role="progressbar" style="width: <?= round($c['score']) ?>%"></div>
                                    </div>
                                </td>
                                <td class="text-center">
                                    <?= $c['badge'] ?>
                                </td>
                                <td class="text-end pe-4">
                                    <a href="view_committee.php?id=<?= $c['id'] ?>" class="btn btn-sm btn-outline-primary rounded-pill px-3">
                                        <i class="fas fa-chart-line"></i> تقرير مفصل
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php require_once 'includes/footer.php'; ?>