<?php

namespace App\Controllers;

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

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

class AdminSubmissionController extends Controller
{
    private function startSession(): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }
    }

    private function requireAdmin(): void
    {
        $this->startSession();

        if (empty($_SESSION['user_id'])) {

            header("Location: /easychair/login");
            exit;
        }

        if (
            !RoleMatrix::can('manage_submissions')
            &&
            !RoleMatrix::can('manage_submission')
        ) {

            http_response_code(403);
            exit("Access denied.");
        }
    }

    public function index()
    {
        $this->requireAdmin();

        $db =
            Database::getInstance();

        $role =
            $_SESSION['role'] ?? '';

        $orgId =
            (int)($_SESSION['org_id'] ?? 0);

        $conferenceId =
            (int)(
                $_SESSION['conference_id']
                ?? $_SESSION['current_conference_id']
                ?? 0
            );

        $where =
            " WHERE 1=1 ";

        $params = [];

        /*
        |--------------------------------------------------------------------------
        | CONFERENCE FILTERING
        |--------------------------------------------------------------------------
        */

        if ($role !== 'super_admin') {

            if (
                $orgId <= 0
                ||
                $conferenceId <= 0
            ) {

                header("Location: /easychair/select-conference");
                exit;
            }

            $where .= "
                AND s.org_id = ?
                AND s.conference_id = ?
            ";

            $params[] = $orgId;
            $params[] = $conferenceId;

        } elseif ($conferenceId > 0) {

            $where .= "
                AND s.conference_id = ?
            ";

            $params[] = $conferenceId;
        }

        /*
        |--------------------------------------------------------------------------
        | SUBMISSIONS
        |--------------------------------------------------------------------------
        */

        $stmt =
            $db->prepare("
                SELECT
                    s.*,

                    COALESCE(
                        s.title,
                        s.title_en,
                        s.title_ar,
                        CONCAT('Submission #', s.id)
                    ) AS display_title,

                    COALESCE(
                        c.title_ar,
                        c.title_en
                    ) AS conference,

                    c.short_name AS conference_short_name,

                    CONCAT(
                        COALESCE(u.first_name,''),
                        ' ',
                        COALESCE(u.last_name,'')
                    ) AS author_name,

                    u.email AS author_email,

                    COUNT(DISTINCT ra.id)
                        AS assignments_count,

                    COUNT(DISTINCT rv.id)
                        AS reviews_count

,
SUM(
    CASE
        WHEN ra.status = 'completed'
        THEN 1
        ELSE 0
    END
) AS completed_reviews

,
COALESCE(s.current_round_no,1)
    AS current_round_no,

COALESCE(s.avg_score,0)
    AS avg_score,

COALESCE(
    s.recommended_decision,
    '-'
) AS recommended_decision

                FROM submissions s

                LEFT JOIN conferences c
                    ON c.id = s.conference_id

                LEFT JOIN users u
                    ON u.id = s.author_id

                LEFT JOIN review_assignments ra
                    ON ra.submission_id = s.id

                LEFT JOIN reviews rv
                    ON rv.submission_id = s.id

                {$where}

                GROUP BY s.id

                ORDER BY s.id DESC
            ");

        $stmt->execute($params);

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

        /*
        |--------------------------------------------------------------------------
        | REVIEWERS
        |--------------------------------------------------------------------------
        */

        /*
|--------------------------------------------------------------------------
| REVIEWERS
|--------------------------------------------------------------------------
*/

$reviewers = [];

try {

    $stmtReviewers =
        $db->prepare("
            SELECT
                u.id,
                u.first_name,
                u.last_name,
                u.email

            FROM conference_reviewers cr

            INNER JOIN users u
                ON u.id = cr.user_id

            WHERE cr.conference_id = ?

            AND u.is_active = 1

            ORDER BY
                u.first_name ASC,
                u.last_name ASC
        ");

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

    $reviewers =
        $stmtReviewers->fetchAll(
            \PDO::FETCH_ASSOC
        );

} catch (\Throwable $e) {

    error_log(
        'REVIEWERS LOAD ERROR: '
        . $e->getMessage()
    );

    $reviewers = [];
}
        ob_start();

        require BASE_PATH
            . '/app/views/admin/submissions/index.php';

        $content =
            ob_get_clean();

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