<?php
namespace App\Controllers;

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

use App\Core\Database;

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

class AdminAccessAuditController
{
    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 requireSuperAdmin(): void
    {
        $this->startSession();

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

        if ($this->role() !== 'super_admin') {
            http_response_code(403);
            exit('Only super admin can access Access Audit.');
        }
    }

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

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

        $conference = $this->conference();
        $conferenceId = (int)$conference['id'];
        $orgId = (int)$conference['org_id'];

        $roles = $this->db()->query("SELECT id, code, name FROM roles ORDER BY code")->fetchAll(\PDO::FETCH_ASSOC);
        $menus = $this->db()->query("
            SELECT id, label, label_ar, url, module_key, sort_order, is_active
            FROM rbac_menu_items
            WHERE is_active=1
            ORDER BY module_key, sort_order, id
        ")->fetchAll(\PDO::FETCH_ASSOC);

        $rows = [];

        foreach ($roles as $role) {
            foreach ($menus as $menu) {
                $stmt = $this->db()->prepare("
                    SELECT *
                    FROM rbac_role_menu_permissions
                    WHERE org_id=?
                      AND conference_id=?
                      AND role_id=?
                      AND menu_item_id=?
                    ORDER BY id DESC
                    LIMIT 1
                ");
                $stmt->execute([$orgId, $conferenceId, (int)$role['id'], (int)$menu['id']]);
                $p = $stmt->fetch(\PDO::FETCH_ASSOC);

                $rows[] = [
                    'role' => $role,
                    'menu' => $menu,
                    'permission' => $p ?: null,
                ];
            }
        }

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

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

    public function heal()
    {
        $this->requireSuperAdmin();

        $conference = $this->conference();
        $cmd = 'php ' . escapeshellarg(BASE_PATH . '/tools/heal_role_permissions.php') .
            ' --conference_id=' . (int)$conference['id'] .
            ' --apply 2>&1';

        $output = shell_exec($cmd);

        $_SESSION['flash_success'] = "Healer executed for conference #" . (int)$conference['id'];
        $_SESSION['flash_output'] = $output;

        header("Location: /easychair/admin/access-audit");
        exit;
    }
}
