<?php

namespace App\Controllers;

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

class AdminDashboardController extends Controller
{
    public function index()
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        /*
        -----------------------------------------
        Auth check
        -----------------------------------------
        */
        if (!isset($_SESSION['user_id'])) {
            header("Location: /easychair/login");
            exit;
        }

        /*
        -----------------------------------------
        Session context
        -----------------------------------------
        */
        $conferenceId = (int)($_SESSION['conference_id'] ?? 0);
        $orgId        = (int)($_SESSION['org_id'] ?? 0);
        $role         = $_SESSION['conference_role'] ?? '';

        /*
        -----------------------------------------
        DB
        -----------------------------------------
        */
        $db = Database::getInstance();

        /*
        -----------------------------------------
        Stats (safe)
        -----------------------------------------
        */
        $stats = [
            'submissions' => 0,
            'reviews'     => 0,
            'users'       => 0,
            'tracks'      => 0
        ];

        if ($conferenceId > 0) {

            // submissions
            $stmt = $db->prepare("
                SELECT COUNT(*) FROM submissions
                WHERE conference_id = ?
            ");
            $stmt->execute([$conferenceId]);
            $stats['submissions'] = (int)$stmt->fetchColumn();

            // reviews
            $stmt = $db->prepare("
                SELECT COUNT(*) FROM reviews
                WHERE submission_id IN (
                    SELECT id FROM submissions WHERE conference_id = ?
                )
            ");
            $stmt->execute([$conferenceId]);
            $stats['reviews'] = (int)$stmt->fetchColumn();

            // users
            $stmt = $db->prepare("
                SELECT COUNT(DISTINCT user_id)
                FROM conference_user_roles
                WHERE conference_id = ?
            ");
            $stmt->execute([$conferenceId]);
            $stats['users'] = (int)$stmt->fetchColumn();

            // tracks
            $stmt = $db->prepare("
                SELECT COUNT(*) FROM tracks
                WHERE conference_id = ?
            ");
            $stmt->execute([$conferenceId]);
            $stats['tracks'] = (int)$stmt->fetchColumn();
        }

        /*
        -----------------------------------------
        Pass data to view
        -----------------------------------------
        */
        $this->render('admin/dashboard', [
            'stats' => $stats,
            'role'  => $role,
            'orgId' => $orgId,
            'conferenceId' => $conferenceId
        ]);
    }
}
