<?php

namespace App\Controllers;

require_once BASE_PATH . '/app/helpers/permissions.php';

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

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

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

        $conferenceId = (int)($_SESSION['conference_id'] ?? 0);
        $orgId        = (int)($_SESSION['org_id'] ?? 0);
        $role         = $_SESSION['conference_role'] ?? '';

        $db = Database::getInstance();

        $stats = [
            'submissions' => 0,
            'reviews'     => 0,
            'users'       => 0,
            'tracks'      => 0
        ];

        $decisionQueue = [
            'accept'          => 0,
            'minor_revision'  => 0,
            'major_revision'  => 0,
            'reject'          => 0
        ];

        if ($conferenceId > 0) {

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

            $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();

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

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

            /*
            --------------------------------------------------
            PACK 957A
            Decision Queue
            --------------------------------------------------
            */

            try {

                $stmt = $db->prepare("
                    SELECT
                        recommended_decision,
                        COUNT(*) total
                    FROM submissions
                    WHERE conference_id=?
                      AND recommended_decision IS NOT NULL
                    GROUP BY recommended_decision
                ");

                $stmt->execute([$conferenceId]);

                foreach (
                    $stmt->fetchAll(\PDO::FETCH_ASSOC)
                    as $r
                ) {

                    $key =
                        (string)(
                            $r['recommended_decision']
                            ?? ''
                        );

                    if (
                        isset(
                            $decisionQueue[$key]
                        )
                    ) {

                        $decisionQueue[$key] =
                            (int)$r['total'];
                    }
                }

            } catch (\Throwable $e) {

                error_log(
                    'DECISION_QUEUE: '
                    . $e->getMessage()
                );
            }
        }

        $assignedTracks = [];

        if (
            ($_SESSION['conference_role'] ?? '') === 'track_chair'
            ||
            ($_SESSION['conference_role'] ?? $_SESSION['role'] ?? '') === 'track_chair'
        ) {

            try {

                $stmt = $db->prepare("
                    SELECT
                        t.id,
                        COALESCE(
                            t.name_en,
                            t.name_ar,
                            CONCAT('Track #', t.id)
                        ) AS track_name
                    FROM track_chair_assignments a
                    INNER JOIN tracks t
                        ON t.id=a.track_id
                    WHERE a.user_id=?
                      AND a.conference_id=?
                      AND a.is_active=1
                    ORDER BY track_name
                ");

                $stmt->execute([
                    (int)$_SESSION['user_id'],
                    $conferenceId
                ]);

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

            } catch (\Throwable $e) {

                error_log(
                    'TRACK CHAIR DASHBOARD: '
                    . $e->getMessage()
                );
            }
        }

        $this->render('admin/dashboard', [

            'stats'          => $stats,
            'role'           => $role,
            'orgId'          => $orgId,
            'conferenceId'   => $conferenceId,

            'assignedTracks' => $assignedTracks,

            'decisionQueue'  => $decisionQueue

        ]);
    }
}
