<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Core\Database;
use App\Core\TenantGuard;

class AdminDashboardController extends Controller
{
    public function index()
    {
        TenantGuard::requireAdmin();

        $db = Database::getInstance();

        $where = TenantGuard::conferenceWhere('c');

        $stmt = $db->query("
            SELECT 
                o.id AS org_id,
                o.name AS org_name,
                c.id AS conf_id,
                c.title_en,
                c.title_ar,
                c.short_name,
                c.status AS conference_status,
                COUNT(DISTINCT s.id) AS submission_count,
                SUM(CASE WHEN s.status='accepted' THEN 1 ELSE 0 END) AS accepted_count,
                SUM(CASE WHEN s.status='under_review' THEN 1 ELSE 0 END) AS under_review_count,
                COUNT(DISTINCT ra.id) AS assignment_count
            FROM conferences c
            LEFT JOIN organizations o ON o.id = c.org_id
            LEFT JOIN submissions s ON s.conference_id = c.id
            LEFT JOIN review_assignments ra ON ra.conference_id = c.id
            {$where}
            GROUP BY o.id, o.name, c.id, c.title_en, c.title_ar, c.short_name, c.status
            ORDER BY o.id DESC, c.id DESC
        ");

        $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $structured = [];
        $totals = [
            'conferences' => 0,
            'submissions' => 0,
            'accepted' => 0,
            'under_review' => 0,
            'assignments' => 0,
        ];

        foreach ($rows as $r) {
            $orgId = (int)($r['org_id'] ?? 0);
            $structured[$orgId]['name'] = $r['org_name'] ?? 'Organization';

            if (!empty($r['conf_id'])) {
                $totals['conferences']++;
                $totals['submissions'] += (int)$r['submission_count'];
                $totals['accepted'] += (int)$r['accepted_count'];
                $totals['under_review'] += (int)$r['under_review_count'];
                $totals['assignments'] += (int)$r['assignment_count'];

                $structured[$orgId]['conferences'][] = [
                    'id' => (int)$r['conf_id'],
                    'title' => $r['title_en'] ?: $r['title_ar'],
                    'short_name' => $r['short_name'],
                    'status' => $r['conference_status'],
                    'submissions' => (int)$r['submission_count'],
                    'accepted' => (int)$r['accepted_count'],
                    'under_review' => (int)$r['under_review_count'],
                    'assignments' => (int)$r['assignment_count'],
                ];
            }
        }

        ob_start();
        require BASE_PATH . '/app/views/admin/dashboard.php';
        $content = ob_get_clean();

        require BASE_PATH . '/app/views/layouts/admin_layout.php';
    }
}
