<?php
namespace App\Controllers;

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

use App\Core\Database;

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

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

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

    protected function db()
    {
        return Database::getInstance();
    }

    private function role(): string
    {
        return (string)($_SESSION['role'] ?? $_SESSION['user_role'] ?? 'author');
    }

    private function userId(): int
    {
        return (int)($_SESSION['user_id'] ?? 0);
    }

    private function orgId(): int
    {
        return (int)($_SESSION['org_id'] ?? 0);
    }

    private function conferenceId(): int
    {
        return (int)($_SESSION['conference_id'] ?? $_SESSION['current_conference_id'] ?? 0);
    }

    private function isSuperAdmin(): bool
    {
        return $this->role() === 'super_admin';
    }

    private function adminRoles(): array
    {
        return [
            'super_admin',
            'org_admin',
            'admin',
            'organizer',
            'conference_chair',
            'track_chair'
        ];
    }

    private function tableExists(string $table): bool
    {
        try {
            $stmt = $this->db()->prepare("SHOW TABLES LIKE ?");
            $stmt->execute([$table]);
            return (bool)$stmt->fetchColumn();
        } catch (\Throwable $e) {
            return false;
        }
    }

    private function scalar(string $sql, array $params = []): int
    {
        try {
            $stmt = $this->db()->prepare($sql);
            $stmt->execute($params);
            return (int)$stmt->fetchColumn();
        } catch (\Throwable $e) {
            return 0;
        }
    }

    private function rows(string $sql, array $params = []): array
    {
        try {
            $stmt = $this->db()->prepare($sql);
            $stmt->execute($params);
            return $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];
        } catch (\Throwable $e) {
            return [];
        }
    }

    private function currentConference(): ?array
    {
        $cid = $this->conferenceId();

        if ($cid <= 0) {
            return null;
        }

        $stmt = $this->db()->prepare("
            SELECT id, org_id, title_ar, title_en, short_name, status,
                   submission_deadline, review_deadline, camera_ready_deadline,
                   start_date, end_date
            FROM conferences
            WHERE id = ?
            LIMIT 1
        ");
        $stmt->execute([$cid]);

        $conf = $stmt->fetch(\PDO::FETCH_ASSOC);

        return $conf ?: null;
    }

    private function conferenceScope(string $alias = ''): array
    {
        $role = $this->role();
        $prefix = $alias ? $alias . '.' : '';

        $where = " WHERE 1=1 ";
        $params = [];

        if ($this->isSuperAdmin()) {
            if ($this->conferenceId() > 0) {
                $where .= " AND {$prefix}conference_id = ? ";
                $params[] = $this->conferenceId();
            }
            return [$where, $params];
        }

        if ($this->orgId() > 0) {
            $where .= " AND {$prefix}org_id = ? ";
            $params[] = $this->orgId();
        }

        if ($this->conferenceId() > 0) {
            $where .= " AND {$prefix}conference_id = ? ";
            $params[] = $this->conferenceId();
        } else {
            $ids = array_values(array_filter(array_map('intval', $_SESSION['conference_list'] ?? [])));

            if ($ids) {
                $where .= " AND {$prefix}conference_id IN (" . implode(',', $ids) . ") ";
            } else {
                $where .= " AND 1=0 ";
            }
        }

        return [$where, $params];
    }

    private function conferenceTableScope(string $alias = 'c'): array
    {
        $where = " WHERE 1=1 ";
        $params = [];

        if ($this->isSuperAdmin()) {
            if ($this->conferenceId() > 0) {
                $where .= " AND {$alias}.id = ? ";
                $params[] = $this->conferenceId();
            }
            return [$where, $params];
        }

        if ($this->orgId() > 0) {
            $where .= " AND {$alias}.org_id = ? ";
            $params[] = $this->orgId();
        }

        if ($this->conferenceId() > 0) {
            $where .= " AND {$alias}.id = ? ";
            $params[] = $this->conferenceId();
        } else {
            $ids = array_values(array_filter(array_map('intval', $_SESSION['conference_list'] ?? [])));

            if ($ids) {
                $where .= " AND {$alias}.id IN (" . implode(',', $ids) . ") ";
            } else {
                $where .= " AND 1=0 ";
            }
        }

        return [$where, $params];
    }

    private function adminDashboardData(): array
    {
        [$subWhere, $subParams] = $this->conferenceScope('s');
        [$raWhere, $raParams] = $this->conferenceScope('ra');
        [$revWhere, $revParams] = $this->conferenceScope('r');
        [$confWhere, $confParams] = $this->conferenceTableScope('c');

        $data = [];

        $data['conferences_count'] = $this->scalar("
            SELECT COUNT(*)
            FROM conferences c
            {$confWhere}
        ", $confParams);

        $data['submissions_count'] = $this->scalar("
            SELECT COUNT(*)
            FROM submissions s
            {$subWhere}
        ", $subParams);

        $data['under_review_count'] = $this->scalar("
            SELECT COUNT(*)
            FROM submissions s
            {$subWhere}
              AND s.status = 'under_review'
        ", $subParams);

        $data['accepted_count'] = $this->scalar("
            SELECT COUNT(*)
            FROM submissions s
            {$subWhere}
              AND s.status = 'accepted'
        ", $subParams);

        $data['rejected_count'] = $this->scalar("
            SELECT COUNT(*)
            FROM submissions s
            {$subWhere}
              AND s.status = 'rejected'
        ", $subParams);

        $data['review_assignments_count'] = $this->scalar("
            SELECT COUNT(*)
            FROM review_assignments ra
            {$raWhere}
        ", $raParams);

        $data['completed_reviews_count'] = $this->scalar("
            SELECT COUNT(*)
            FROM review_assignments ra
            {$raWhere}
              AND ra.status = 'completed'
        ", $raParams);

        $data['reviews_count'] = $this->scalar("
            SELECT COUNT(*)
            FROM reviews r
            {$revWhere}
        ", $revParams);

        $data['reviewers_count'] = $this->scalar("
            SELECT COUNT(DISTINCT ra.reviewer_id)
            FROM review_assignments ra
            {$raWhere}
        ", $raParams);

        $data['recent_submissions'] = $this->rows("
            SELECT
                s.id,
                COALESCE(s.title, s.title_en, s.title_ar, CONCAT('Submission #', s.id)) AS title,
                s.status,
                s.stage,
                s.decision,
                s.avg_score,
                s.created_at,
                c.short_name
            FROM submissions s
            LEFT JOIN conferences c ON c.id = s.conference_id
            {$subWhere}
            ORDER BY s.id DESC
            LIMIT 10
        ", $subParams);

        $data['workflow'] = [];

        if ($this->tableExists('conference_workflow')) {
            $cid = $this->conferenceId();

            if ($cid > 0) {
                $data['workflow'] = $this->rows("
                    SELECT stage, is_enabled
                    FROM conference_workflow
                    WHERE conference_id = ?
                    ORDER BY id ASC
                ", [$cid]);
            }
        }

        $data['workflow_settings'] = null;

        if ($this->tableExists('workflow_settings')) {
            $cid = $this->conferenceId();

            if ($cid > 0) {
                $settings = $this->rows("
                    SELECT review_rounds, allow_revision, auto_decision
                    FROM workflow_settings
                    WHERE conference_id = ?
                    LIMIT 1
                ", [$cid]);

                $data['workflow_settings'] = $settings[0] ?? null;
            }
        }

        return $data;
    }

    private function reviewerDashboardData(): array
    {
        $uid = $this->userId();
        $cid = $this->conferenceId();

        $params = [$uid];
        $where = " WHERE ra.reviewer_id = ? ";

        if ($cid > 0) {
            $where .= " AND ra.conference_id = ? ";
            $params[] = $cid;
        }

        $data = [];

        $data['assigned_count'] = $this->scalar("
            SELECT COUNT(*)
            FROM review_assignments ra
            {$where}
              AND ra.status = 'assigned'
        ", $params);

        $data['accepted_count'] = $this->scalar("
            SELECT COUNT(*)
            FROM review_assignments ra
            {$where}
              AND ra.status = 'accepted'
        ", $params);

        $data['completed_count'] = $this->scalar("
            SELECT COUNT(*)
            FROM review_assignments ra
            {$where}
              AND ra.status = 'completed'
        ", $params);

        $data['declined_count'] = $this->scalar("
            SELECT COUNT(*)
            FROM review_assignments ra
            {$where}
              AND ra.status = 'declined'
        ", $params);

        $data['my_assignments'] = $this->rows("
            SELECT
                ra.id AS assignment_id,
                ra.submission_id,
                ra.status,
                ra.due_date,
                ra.round_no,
                COALESCE(s.title, s.title_en, s.title_ar, CONCAT('Submission #', s.id)) AS title,
                s.stage,
                s.avg_score
            FROM review_assignments ra
            LEFT JOIN submissions s ON s.id = ra.submission_id
            {$where}
            ORDER BY ra.id DESC
            LIMIT 10
        ", $params);

        return $data;
    }

    private function authorDashboardData(): array
    {
        $uid = $this->userId();
        $cid = $this->conferenceId();

        $params = [$uid];
        $where = " WHERE s.author_id = ? ";

        if ($cid > 0) {
            $where .= " AND s.conference_id = ? ";
            $params[] = $cid;
        }

        $data = [];

        $data['my_submissions_count'] = $this->scalar("
            SELECT COUNT(*)
            FROM submissions s
            {$where}
        ", $params);

        $data['draft_count'] = $this->scalar("
            SELECT COUNT(*)
            FROM submissions s
            {$where}
              AND s.status = 'draft'
        ", $params);

        $data['under_review_count'] = $this->scalar("
            SELECT COUNT(*)
            FROM submissions s
            {$where}
              AND s.status = 'under_review'
        ", $params);

        $data['accepted_count'] = $this->scalar("
            SELECT COUNT(*)
            FROM submissions s
            {$where}
              AND s.status = 'accepted'
        ", $params);

        $data['revision_count'] = $this->scalar("
            SELECT COUNT(*)
            FROM submissions s
            {$where}
              AND s.status IN ('revision_required','revised')
        ", $params);

        $data['my_submissions'] = $this->rows("
            SELECT
                s.id,
                COALESCE(s.title, s.title_en, s.title_ar, CONCAT('Submission #', s.id)) AS title,
                s.status,
                s.stage,
                s.decision,
                s.avg_score,
                s.created_at,
                c.short_name
            FROM submissions s
            LEFT JOIN conferences c ON c.id = s.conference_id
            {$where}
            ORDER BY s.id DESC
            LIMIT 10
        ", $params);

        return $data;
    }

public function index()
{
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }

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

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

    error_log("DASHBOARD ROLE: " . $role);

    /*
    🔥 STOP LOOP CONDITION
    If already on correct dashboard → DO NOTHING
    */

    $uri = $_SERVER['REQUEST_URI'] ?? '';

    if (str_contains($uri, '/admin/dashboard') ||
        str_contains($uri, '/reviewer/dashboard') ||
        str_contains($uri, '/author/dashboard')) {
        return; // STOP redirect loop
    }

    /*
    🔥 NORMAL REDIRECT
    */

    switch ($role) {

        case 'super_admin':
        case 'admin':
        case 'conference_chair':
        case 'track_chair':
        case 'organizer':

            header("Location: /easychair/admin/dashboard");
            break;

        case 'reviewer':

            header("Location: /easychair/reviewer/dashboard");
            break;

        default:

            header("Location: /easychair/author/dashboard");
            break;
    }

    exit;
}


}
