<?php
namespace App\Controllers;

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

use App\Core\Database;
use App\Core\ProfileGuard;

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

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

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

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

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

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

        if (!in_array($this->role(), ['super_admin','org_admin','admin','organizer','conference_chair','track_chair'], true)) {
            http_response_code(403);
            exit("Access denied.");
        }
    }

    private function conference(): array
    {
        $stmt = $this->db()->prepare("SELECT * FROM conferences WHERE id=? LIMIT 1");
        $stmt->execute([(int)$_SESSION['conference_id']]);
        $c = $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$c) {
            exit("Conference not found.");
        }

        if ($this->role() !== 'super_admin' && (int)$c['org_id'] !== (int)($_SESSION['org_id'] ?? 0)) {
            http_response_code(403);
            exit("Invalid organization access.");
        }

        return $c;
    }

    public function index()
    {

        // Pack512: non-superadmin bypasses selector safely.
        if (function_exists('ec_scope_role') && ec_scope_role() !== 'super_admin') {
            if (function_exists('ec_scope_auto_select_conference')) {
                // ec_scope_auto_select_conference(true);
            }
            $landing = function_exists('ec_scope_landing_url') ? ec_scope_landing_url() : '/easychair/admin/dashboard';
            header("Location: " . $landing);
            exit;
        }

$this->requireAccess();
        $conference = $this->conference();

        $roleFilter = trim((string)($_GET['role'] ?? ''));
        $statusFilter = trim((string)($_GET['status'] ?? ''));
        $q = trim((string)($_GET['q'] ?? ''));

        $where = "WHERE uc.conference_id=?";
        $params = [(int)$conference['id']];

        if ($roleFilter !== '') {
            $where .= " AND r.code=?";
            $params[] = $roleFilter;
        }

        if ($statusFilter === 'complete') {
            $where .= " AND COALESCE(p.is_profile_complete,0)=1";
        } elseif ($statusFilter === 'incomplete') {
            $where .= " AND COALESCE(p.is_profile_complete,0)=0";
        }

        if ($q !== '') {
            $where .= " AND (u.email LIKE ? OR u.first_name LIKE ? OR u.last_name LIKE ? OR p.major LIKE ? OR p.specialization LIKE ? OR p.affiliation LIKE ?)";
            $like = '%' . $q . '%';
            array_push($params, $like, $like, $like, $like, $like, $like);
        }

        $stmt = $this->db()->prepare("
            SELECT
                r.code AS role_code,
                r.name AS role_name,
                COUNT(*) AS total_users,
                SUM(CASE WHEN COALESCE(p.is_profile_complete,0)=1 THEN 1 ELSE 0 END) AS complete_users,
                SUM(CASE WHEN COALESCE(p.is_profile_complete,0)=0 THEN 1 ELSE 0 END) AS incomplete_users
            FROM user_conferences uc
            JOIN roles r ON r.id=uc.role_id
            LEFT JOIN user_profiles p
                   ON p.user_id=uc.user_id
                  AND p.conference_id=uc.conference_id
            WHERE uc.conference_id=?
            GROUP BY r.code, r.name
            ORDER BY r.id
        ");
        $stmt->execute([(int)$conference['id']]);
        $statsByRole = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $stmt = $this->db()->prepare("
            SELECT
                COUNT(*) AS total_users,
                SUM(CASE WHEN COALESCE(p.is_profile_complete,0)=1 THEN 1 ELSE 0 END) AS complete_users,
                SUM(CASE WHEN COALESCE(p.is_profile_complete,0)=0 THEN 1 ELSE 0 END) AS incomplete_users
            FROM user_conferences uc
            LEFT JOIN user_profiles p
                   ON p.user_id=uc.user_id
                  AND p.conference_id=uc.conference_id
            WHERE uc.conference_id=?
        ");
        $stmt->execute([(int)$conference['id']]);
        $overall = $stmt->fetch(\PDO::FETCH_ASSOC) ?: [];

        $stmt = $this->db()->prepare("
            SELECT
                u.id AS user_id,
                u.email,
                u.first_name,
                u.last_name,
                r.code AS role_code,
                r.name AS role_name,
                p.id AS profile_id,
                p.affiliation,
                p.major,
                p.specialization,
                p.education_level,
                p.is_profile_complete,
                p.updated_at
            FROM user_conferences uc
            JOIN users u ON u.id=uc.user_id
            JOIN roles r ON r.id=uc.role_id
            LEFT JOIN user_profiles p
                   ON p.user_id=uc.user_id
                  AND p.conference_id=uc.conference_id
            {$where}
            ORDER BY COALESCE(p.is_profile_complete,0), r.id, u.email
            LIMIT 500
        ");
        $stmt->execute($params);
        $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $roles = $this->db()->query("SELECT id, name, code FROM roles ORDER BY id")->fetchAll(\PDO::FETCH_ASSOC);

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

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

    public function recalculate()
    {
        $this->requireAccess();
        $conference = $this->conference();

        $stmt = $this->db()->prepare("
            SELECT DISTINCT uc.user_id
            FROM user_conferences uc
            WHERE uc.conference_id=?
        ");
        $stmt->execute([(int)$conference['id']]);
        $userIds = $stmt->fetchAll(\PDO::FETCH_COLUMN);

        $guard = new ProfileGuard();
        $updated = 0;

        foreach ($userIds as $uid) {
            try {
                $guard->refreshCompletion((int)$uid, (int)$conference['id']);
                $updated++;
            } catch (\Throwable $e) {
                // keep going
            }
        }

        $_SESSION['flash_success'] = "Profile completion recalculated for {$updated} user(s).";
        header("Location: /easychair/admin/profile-completion");
        exit;
    }
}
