<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Database;
use PDO;
use Throwable;

class MyIntelligenceController extends Controller
{
    private function one(PDO $db, string $sql, array $params): array
    {
        try {
            $st = $db->prepare($sql);
            $st->execute($params);
            $row = $st->fetch(PDO::FETCH_ASSOC);
            return $row ?: [];
        } catch (Throwable $e) {
            return [];
        }
    }

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

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

        $db = Database::getInstance();

        $uid =
        (int)($_SESSION['user_id'] ?? 0);

        $role =
        strtolower(
            (string)(
                $_SESSION['conference_role']
                ?? $_SESSION['role']
                ?? ''
            )
        );

        $isAuthorRole =
        $role === 'author';

        $isReviewerRole =
        in_array(
            $role,
            [
                'reviewer',
                'track_chair',
                'conference_chair'
            ],
            true
        );

        $isAdminRole =
        in_array(
            $role,
            [
                'superadmin',
                'super_admin',
                'admin',
                'org_admin',
                'organizer'
            ],
            true
        );

        /*
        IMPORTANT:
        Author active session must NOT see reviewer intelligence.
        Reviewer/chair active session must NOT see author intelligence unless admin.
        Admin can see both if data exists for own user id.
        */

        $authorPortfolio = [];
        $authorSuccess = [];

        $reviewerTwin = [];
        $reviewerReputation = [];
        $reviewerLeadership = [];
        $reviewerAchievement = [];

        if ($isAuthorRole || $isAdminRole) {

            $authorPortfolio = $this->one($db, "
                SELECT *
                FROM author_academic_portfolio
                WHERE author_id=?
                LIMIT 1
            ", [$uid]);

            $authorSuccess = $this->one($db, "
                SELECT *
                FROM author_success_intelligence
                WHERE author_id=?
                ORDER BY success_score DESC,id DESC
                LIMIT 1
            ", [$uid]);

        }

        if ($isReviewerRole || $isAdminRole) {

            $reviewerTwin = $this->one($db, "
                SELECT *
                FROM reviewer_digital_twins
                WHERE reviewer_id=?
                ORDER BY digital_twin_score DESC,id DESC
                LIMIT 1
            ", [$uid]);

            $reviewerReputation = $this->one($db, "
                SELECT *
                FROM reviewer_reputation_network
                WHERE reviewer_id=?
                ORDER BY reputation_score DESC,id DESC
                LIMIT 1
            ", [$uid]);

            $reviewerLeadership = $this->one($db, "
                SELECT *
                FROM reviewer_leadership_succession_ai
                WHERE reviewer_id=?
                ORDER BY readiness_score DESC,id DESC
                LIMIT 1
            ", [$uid]);

            $reviewerAchievement = $this->one($db, "
                SELECT *
                FROM reviewer_lifetime_achievement
                WHERE reviewer_id=?
                ORDER BY lifetime_impact_score DESC,id DESC
                LIMIT 1
            ", [$uid]);

        }

        $showAuthor =
        $isAuthorRole
        ||
        (
            $isAdminRole
            &&
            !empty($authorPortfolio)
        );

        $showReviewer =
        $isReviewerRole
        ||
        (
            $isAdminRole
            &&
            (
                !empty($reviewerTwin)
                ||
                !empty($reviewerReputation)
                ||
                !empty($reviewerLeadership)
                ||
                !empty($reviewerAchievement)
            )
        );

        $authorScore =
        $showAuthor
        ?
        (float)($authorPortfolio['portfolio_score'] ?? 0)
        :
        0;

        $reviewerScore =
        $showReviewer
        ?
        max(
            (float)($reviewerTwin['digital_twin_score'] ?? 0),
            (float)($reviewerReputation['reputation_score'] ?? 0),
            (float)($reviewerLeadership['readiness_score'] ?? 0),
            (float)($reviewerAchievement['lifetime_impact_score'] ?? 0)
        )
        :
        0;

        $count = 0;

        if ($authorScore > 0) {
            $count++;
        }

        if ($reviewerScore > 0) {
            $count++;
        }

        $overall =
        $count > 0
        ?
        round(($authorScore + $reviewerScore) / $count, 2)
        :
        0;

        ob_start();

        require BASE_PATH .
        '/app/views/my_intelligence/index.php';

        $content =
        ob_get_clean();

        if (
            $isAuthorRole
            &&
            file_exists(BASE_PATH . '/app/views/layouts/author_layout.php')
        ) {
            require BASE_PATH .
            '/app/views/layouts/author_layout.php';
            return;
        }

        if (
            $isReviewerRole
            &&
            file_exists(BASE_PATH . '/app/views/layouts/reviewer_layout.php')
        ) {
            require BASE_PATH .
            '/app/views/layouts/reviewer_layout.php';
            return;
        }

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