<?php
namespace App\Controllers;

use App\Core\Database;

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

    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;
        }

        if (empty($_SESSION['conference_id'])) {
            header("Location: /easychair/select-conference");
            exit;
        }
    }

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

    private function currentConference(): array
    {
        $stmt = $this->db()->prepare("
            SELECT c.*, o.name AS org_name
            FROM conferences c
            LEFT JOIN organizations o ON o.id = c.org_id
            WHERE c.id = ?
            LIMIT 1
        ");
        $stmt->execute([(int)$_SESSION['conference_id']]);
        $c = $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$c) {
            return [
                'id' => (int)($_SESSION['conference_id'] ?? 0),
                'org_id' => (int)($_SESSION['org_id'] ?? 0),
                'short_name' => 'Conference',
                'title_en' => '',
                'title_ar' => '',
                'org_name' => '',
            ];
        }

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

        return $c;
    }

    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 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 countTable(string $table, string $where = '1=1', array $params = []): int
    {
        if (!$this->tableExists($table)) {
            return 0;
        }

        return $this->scalar("SELECT COUNT(*) FROM {$table} WHERE {$where}", $params);
    }

    private function buildStats(array $conference, string $role): array
    {
        $confId = (int)$conference['id'];
        $orgId = (int)$conference['org_id'];

        $stats = [];

        if ($role === 'super_admin') {
            $stats = [
                ['key'=>'dashboard.kpi.organizations', 'label'=>'Organizations', 'value'=>$this->countTable('organizations'), 'icon'=>'fa-building'],
                ['key'=>'dashboard.kpi.conferences', 'label'=>'Conferences', 'value'=>$this->countTable('conferences'), 'icon'=>'fa-folder-open'],
                ['key'=>'dashboard.kpi.users', 'label'=>'Users', 'value'=>$this->countTable('users'), 'icon'=>'fa-users'],
                ['key'=>'dashboard.kpi.rbac_rows', 'label'=>'RBAC Rows', 'value'=>$this->countTable('rbac_role_menu_permissions'), 'icon'=>'fa-shield-halved'],
            ];
        } elseif ($role === 'org_admin') {
            $stats = [
                ['key'=>'dashboard.kpi.conferences', 'label'=>'Conferences', 'value'=>$this->countTable('conferences', 'org_id=?', [$orgId]), 'icon'=>'fa-folder-open'],
                ['key'=>'dashboard.kpi.submissions', 'label'=>'Submissions', 'value'=>$this->countTable('submissions', 'org_id=?', [$orgId]), 'icon'=>'fa-inbox'],
                ['key'=>'dashboard.kpi.users', 'label'=>'Users', 'value'=>$this->countTable('users', 'org_id=?', [$orgId]), 'icon'=>'fa-users'],
                ['key'=>'dashboard.kpi.notifications', 'label'=>'Notifications', 'value'=>$this->countTable('notifications', 'org_id=?', [$orgId]), 'icon'=>'fa-bell'],
            ];
        } elseif (in_array($role, ['conference_chair','admin'], true)) {
            $stats = [
                ['key'=>'dashboard.kpi.submissions', 'label'=>'Submissions', 'value'=>$this->countTable('submissions', 'conference_id=? AND org_id=?', [$confId,$orgId]), 'icon'=>'fa-inbox'],
                ['key'=>'dashboard.kpi.under_review', 'label'=>'Under Review', 'value'=>$this->countTable('submissions', "conference_id=? AND org_id=? AND (stage='reviewing' OR status='under_review')", [$confId,$orgId]), 'icon'=>'fa-clipboard-check'],
                ['key'=>'dashboard.kpi.accepted', 'label'=>'Accepted', 'value'=>$this->countTable('submissions', "conference_id=? AND org_id=? AND (stage='accepted' OR status='accepted')", [$confId,$orgId]), 'icon'=>'fa-circle-check'],
                ['key'=>'dashboard.kpi.revision_required', 'label'=>'Revision Required', 'value'=>$this->countTable('submissions', "conference_id=? AND org_id=? AND (stage='revision_required' OR status='revision_required')", [$confId,$orgId]), 'icon'=>'fa-pen-to-square'],
            ];
        } elseif ($role === 'track_chair' || $role === 'section_editor') {
            $stats = [
                ['key'=>'dashboard.kpi.submissions', 'label'=>'Submissions', 'value'=>$this->countTable('submissions', 'conference_id=? AND org_id=?', [$confId,$orgId]), 'icon'=>'fa-inbox'],
                ['key'=>'dashboard.kpi.review_assignments', 'label'=>'Review Assignments', 'value'=>$this->countTable('review_assignments', 'conference_id=? AND org_id=?', [$confId,$orgId]), 'icon'=>'fa-user-check'],
                ['key'=>'dashboard.kpi.completed_reviews', 'label'=>'Completed Reviews', 'value'=>$this->countTable('reviews', 'conference_id=? AND org_id=?', [$confId,$orgId]), 'icon'=>'fa-circle-check'],
                ['key'=>'dashboard.kpi.late_reviews', 'label'=>'Late Reviews', 'value'=>$this->countTable('review_assignments', "conference_id=? AND org_id=? AND due_date IS NOT NULL AND due_date < CURDATE() AND COALESCE(status,'assigned') NOT IN ('completed','submitted')", [$confId,$orgId]), 'icon'=>'fa-triangle-exclamation'],
            ];
        } elseif ($role === 'organizer') {
            $stats = [
                ['key'=>'dashboard.kpi.homepage_blocks', 'label'=>'Homepage Blocks', 'value'=>$this->countTable('conference_home_blocks', 'conference_id=? AND org_id=?', [$confId,$orgId]), 'icon'=>'fa-palette'],
                ['key'=>'dashboard.kpi.committee_people', 'label'=>'Committee People', 'value'=>$this->countTable('conference_committee_people', 'conference_id=? AND org_id=?', [$confId,$orgId]), 'icon'=>'fa-images'],
                ['key'=>'dashboard.kpi.pending_production', 'label'=>'Pending Production', 'value'=>$this->countTable('submissions', "conference_id=? AND org_id=? AND COALESCE(production_status,'pending')='pending'", [$confId,$orgId]), 'icon'=>'fa-industry'],
                ['key'=>'dashboard.kpi.certificates', 'label'=>'Certificates', 'value'=>$this->countTable('conference_certificates', 'conference_id=? AND org_id=?', [$confId,$orgId]), 'icon'=>'fa-certificate'],
            ];
        } else {
            $stats = [
                ['key'=>'dashboard.kpi.submissions', 'label'=>'Submissions', 'value'=>$this->countTable('submissions', 'conference_id=? AND org_id=?', [$confId,$orgId]), 'icon'=>'fa-inbox'],
                ['key'=>'dashboard.kpi.review_assignments', 'label'=>'Review Assignments', 'value'=>$this->countTable('review_assignments', 'conference_id=? AND org_id=?', [$confId,$orgId]), 'icon'=>'fa-user-check'],
                ['key'=>'dashboard.kpi.notifications', 'label'=>'Notifications', 'value'=>$this->countTable('notifications', 'conference_id=? AND org_id=?', [$confId,$orgId]), 'icon'=>'fa-bell'],
                ['key'=>'dashboard.kpi.issues', 'label'=>'Issues', 'value'=>$this->countTable('conference_issues', 'conference_id=? AND org_id=?', [$confId,$orgId]), 'icon'=>'fa-book'],
            ];
        }

        return $stats;
    }

    private function quickActions(string $role): array
    {
        $all = [
            'super_admin' => [
                ['/easychair/admin/conferences','fa-folder-open','menu.conferences','Conferences'],
                ['/easychair/admin/organizations','fa-building','menu.organizations','Organizations'],
                ['/easychair/admin/rbac-matrix','fa-sliders','menu.rbac_matrix','RBAC Matrix'],
                ['/easychair/admin/rbac-scope','fa-copy','menu.rbac_scope','RBAC Scope Manager'],
                ['/easychair/admin/dictionary','fa-language','menu.dictionary','Dictionary'],
            ],
            'org_admin' => [
                ['/easychair/admin/conferences','fa-folder-open','menu.conferences','Conferences'],
                ['/easychair/admin/conference-role-permissions','fa-user-lock','menu.conference_role_permissions','Conference Role Permissions'],
                ['/easychair/admin/rbac-scope','fa-copy','menu.rbac_scope','RBAC Scope Manager'],
                ['/easychair/admin/org-smtp','fa-server','menu.org_smtp','Organization SMTP'],
                ['/easychair/admin/users','fa-users','menu.users_management','Users Management'],
            ],
            'conference_chair' => [
                ['/easychair/admin/submissions','fa-inbox','menu.submissions','Submissions'],
                ['/easychair/admin/reviewer-assignments','fa-user-plus','menu.reviewer_assignment','Reviewer Assignment'],
                ['/easychair/admin/review-monitor','fa-chart-line','menu.review_monitor','Review Monitor'],
                ['/easychair/admin/decisions','fa-gavel','menu.decisions','Decisions'],
                ['/easychair/admin/workflow','fa-diagram-project','menu.workflow','Workflow'],
            ],
            'track_chair' => [
                ['/easychair/admin/submissions','fa-inbox','menu.submissions','Submissions'],
                ['/easychair/admin/reviewer-assignments','fa-user-plus','menu.reviewer_assignment','Reviewer Assignment'],
                ['/easychair/admin/review-monitor','fa-chart-line','menu.review_monitor','Review Monitor'],
                ['/easychair/admin/reviewer-expertise','fa-brain','menu.reviewer_expertise','Reviewer Expertise'],
            ],
            'section_editor' => [
                ['/easychair/admin/submissions','fa-inbox','menu.submissions','Submissions'],
                ['/easychair/admin/reviewer-assignments','fa-user-plus','menu.reviewer_assignment','Reviewer Assignment'],
                ['/easychair/admin/review-monitor','fa-chart-line','menu.review_monitor','Review Monitor'],
            ],
            'organizer' => [
                ['/easychair/admin/conference-home','fa-palette','menu.smart_homepage','Smart Homepage'],
                ['/easychair/admin/committee-images','fa-images','menu.committee_images','Committee Images'],
                ['/easychair/admin/conference-business','fa-calendar-days','menu.business_sessions_issues','Conference Business'],
                ['/easychair/admin/production','fa-industry','menu.production','Production'],
                ['/easychair/admin/certificates','fa-certificate','menu.certificates','Certificates'],
            ],
            'admin' => [
                ['/easychair/admin/submissions','fa-inbox','menu.submissions','Submissions'],
                ['/easychair/admin/users','fa-users','menu.users_management','Users'],
                ['/easychair/admin/email-templates','fa-envelope-open-text','menu.email_templates','Email Templates'],
                ['/easychair/admin/org-smtp','fa-server','menu.org_smtp','Organization SMTP'],
                ['/easychair/admin/notification-audit','fa-bell-circle-check','menu.notification_audit','Notification Audit'],
            ],
        ];

        $actions = $all[$role] ?? $all['admin'];

        return array_values(array_filter($actions, function ($a) {
            if (function_exists('ec_can_menu')) {
                return ec_can_menu($a[0]);
            }
            return true;
        }));
    }

    private function recentSubmissions(array $conference): array
    {
        return $this->rows("
            SELECT id, submission_no, title, title_ar, status, stage, production_status, updated_at
            FROM submissions
            WHERE conference_id=? AND org_id=?
            ORDER BY id DESC
            LIMIT 8
        ", [(int)$conference['id'], (int)$conference['org_id']]);
    }

    private function workflowRows(array $conference): array
    {
        return $this->rows("
            SELECT COALESCE(stage,status,'unknown') AS stage_key, COUNT(*) AS total
            FROM submissions
            WHERE conference_id=? AND org_id=?
            GROUP BY COALESCE(stage,status,'unknown')
            ORDER BY total DESC
            LIMIT 12
        ", [(int)$conference['id'], (int)$conference['org_id']]);
    }

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

        if (defined('BASE_PATH') && file_exists(BASE_PATH . '/app/helpers/permissions.php')) {
            require_once BASE_PATH . '/app/helpers/permissions.php';
        }

        $role = $this->role();
        $conference = $this->currentConference();
        $stats = $this->buildStats($conference, $role);
        $actions = $this->quickActions($role);
        $recentSubmissions = $this->recentSubmissions($conference);
        $workflowRows = $this->workflowRows($conference);

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

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