<?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 (!ec_is_superadmin()) {
            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'];

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

    $search =
        trim((string)($_GET['q'] ?? ''));

    $perPage =
        max(
            25,
            min(
                250,
                (int)($_GET['per_page'] ?? 50)
            )
        );

    $page =
        max(
            1,
            (int)($_GET['page'] ?? 1)
        );

    $offset =
        ($page - 1) * $perPage;

    $sql = "
    SELECT
        r.code role_code,
        r.name role_name,

        mi.id menu_id,
        mi.label,
        mi.label_ar,
        mi.url,
        mi.module_key,

        rp.is_allowed,
        rp.can_view,
        rp.can_create,
        rp.can_update,
        rp.can_delete

    FROM rbac_menu_items mi

    CROSS JOIN roles r

    LEFT JOIN rbac_role_menu_permissions rp
    ON rp.role_id = r.id
   AND rp.menu_item_id = mi.id
   AND
   (
       rp.conference_id = ?
       OR rp.conference_id = 0
   )
    WHERE mi.is_active = 1
    ";

    $params = [
        $conferenceId
    ];

    if ($roleFilter !== '') {

        $sql .= "
        AND r.code = ?
        ";

        $params[] = $roleFilter;
    }

    if ($search !== '') {

        $sql .= "
        AND
        (
            mi.label LIKE ?
            OR mi.url LIKE ?
            OR mi.module_key LIKE ?
        )
        ";

        $params[] = "%{$search}%";
        $params[] = "%{$search}%";
        $params[] = "%{$search}%";
    }

    $countSql =
        "SELECT COUNT(*) FROM ({$sql}) X";

    $st =
        $this->db()->prepare($countSql);

    $st->execute($params);

    $totalRows =
        (int)$st->fetchColumn();

    $sql .= "
    ORDER BY
        r.code,
        mi.module_key,
        mi.sort_order,
        mi.label
    LIMIT {$offset},{$perPage}
    ";

    $st =
        $this->db()->prepare($sql);

    $st->execute($params);

    $rows =
        $st->fetchAll(\PDO::FETCH_ASSOC);

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

    $totalPages =
        max(
            1,
            (int)ceil(
                $totalRows / $perPage
            )
        );

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