<?php
namespace App\Controllers;

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

use App\Core\Database;

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

class AdminConferenceBusinessPermissionsController
{
    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;
        }

        $role = $this->role();

        if ($role === 'superadmin') {
            return;
        }

        if (!in_array($role, ['org_admin','admin'], true)) {
            http_response_code(403);
            exit('Access denied.');
        }
    }

    private function currentConference(): array
    {
        $this->startSession();

        $conferenceId = (int)($_SESSION['conference_id'] ?? 0);

        if ($conferenceId <= 0) {
            $conferenceId = (int)$this->db()->query("SELECT id FROM conferences ORDER BY id LIMIT 1")->fetchColumn();
            $_SESSION['conference_id'] = $conferenceId;
        }

        $stmt = $this->db()->prepare("SELECT * FROM conferences WHERE id=? LIMIT 1");
        $stmt->execute([$conferenceId]);
        $c = $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$c) {
            $stmt = $this->db()->query("SELECT * FROM conferences ORDER BY id LIMIT 1");
            $c = $stmt->fetch(\PDO::FETCH_ASSOC) ?: [];
        }

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

        return $c;
    }

    private function urls(): array
{
    require_once BASE_PATH .
        '/app/views/partials/unified_role_layout_links.php';

    $groups =
        ec_role_layout_all_groups();

    $urls = [];

    foreach ($groups as $group) {

        foreach (($group['items'] ?? []) as $item) {

            $url =
                trim((string)($item['url'] ?? ''));

            if (!$url) {
                continue;
            }

            /*
             * Ignore placeholders
             */
            if (
                $url === '#'
                || str_contains($url, 'javascript:')
            ) {
                continue;
            }

            /*
             * Only EasyChair admin routes
             */
            if (
                !str_starts_with(
                    $url,
                    '/easychair/admin/'
                )
            ) {
                continue;
            }

            /*
             * Ignore logout/login
             */
            if (
                str_contains($url, '/login')
                || str_contains($url, '/logout')
            ) {
                continue;
            }

            $urls[] = $url;
        }
    }

    /*
     * Remove duplicates
     */
    $urls = array_values(
        array_unique($urls)
    );

    sort($urls);

    return $urls;
}

    public function index()
    {
        // Mega520B controller hit marker
        $this->requireAccess();

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

        $urls = $this->urls();
        $in = implode(',', array_fill(0, count($urls), '?'));

        $stmt = $this->db()->prepare("
            SELECT id, menu_key, label, label_ar, i18n_key, url, icon, module_key, sort_order, is_active
            FROM rbac_menu_items mi
            WHERE url IN ($in)
              AND is_active=1
            ORDER BY mi.sort_order, mi.label, mi.id        ");
        $stmt->execute($urls);
        $menuItems = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $roles = $this->db()->query("
            SELECT id, code, name
            FROM roles
            WHERE code <> 'superadmin'
            ORDER BY FIELD(code,'org_admin','admin','conference_chair','organizer','track_chair','reviewer','author'), id
        ")->fetchAll(\PDO::FETCH_ASSOC);

        $permissions = [];

        if ($conferenceId > 0) {
            $stmt = $this->db()->prepare("
                SELECT rp.*
                FROM rbac_role_menu_permissions rp
                JOIN rbac_menu_items mi ON mi.id=rp.menu_item_id
                WHERE rp.conference_id=?
                  AND mi.url IN ($in)
            ");
            $stmt->execute(array_merge([$conferenceId], $urls));

            foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $p) {
                $permissions[(int)$p['role_id']][(int)$p['menu_item_id']] = $p;
            }
        }

        /*
         * Fallback: if session/current conference mismatch causes zero rows,
         * show latest available permission rows grouped by role/menu.
         */
        if (!$permissions) {
            $stmt = $this->db()->prepare("
                SELECT rp.*
                FROM rbac_role_menu_permissions rp
                JOIN rbac_menu_items mi ON mi.id=rp.menu_item_id
                WHERE mi.url IN ($in)
                ORDER BY rp.conference_id, rp.id
            ");
            $stmt->execute($urls);

            foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $p) {
                $permissions[(int)$p['role_id']][(int)$p['menu_item_id']] = $p;
            }
        }

        $debugCounts = [
            'conference_id' => $conferenceId,
            'org_id' => $orgId,
            'roles' => count($roles),
            'menu_items' => count($menuItems),
            'permission_role_groups' => count($permissions),
        ];

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

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

    public function save()
    {
        $this->requireAccess();

        $conference = $this->currentConference();
        $conferenceId = (int)($conference['id'] ?? 0);
        $orgId = (int)($conference['org_id'] ?? ($_SESSION['org_id'] ?? 0));
        $userId = (int)($_SESSION['user_id'] ?? 0);

        $posted = $_POST['perm'] ?? [];

        $roles = $this->db()->query("
            SELECT id
            FROM roles
            WHERE code <> 'superadmin'
        ")->fetchAll(\PDO::FETCH_COLUMN);

        $urls = $this->urls();
        $in = implode(',', array_fill(0, count($urls), '?'));

        $stmt = $this->db()->prepare("
            SELECT id
            FROM rbac_menu_items mi
            WHERE url IN ($in)
              AND is_active=1
        ");
        $stmt->execute($urls);
        $menuIds = array_map('intval', $stmt->fetchAll(\PDO::FETCH_COLUMN));

        $up = $this->db()->prepare("
            INSERT INTO rbac_role_menu_permissions
            (org_id, conference_id, role_id, menu_item_id, is_allowed, can_view, can_create, can_update, can_delete, updated_by)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
                is_allowed=VALUES(is_allowed),
                can_view=VALUES(can_view),
                can_create=VALUES(can_create),
                can_update=VALUES(can_update),
                can_delete=VALUES(can_delete),
                updated_by=VALUES(updated_by),
                updated_at=NOW()
        ");

        foreach ($roles as $roleId) {
            $roleId = (int)$roleId;

            foreach ($menuIds as $menuId) {
                $row = $posted[$roleId][$menuId] ?? [];

                $view = !empty($row['view']) ? 1 : 0;
                $create = !empty($row['create']) ? 1 : 0;
                $update = !empty($row['update']) ? 1 : 0;
                $delete = !empty($row['delete']) ? 1 : 0;
                $allowed = $view ? 1 : 0;

                $up->execute([
                    $orgId,
                    $conferenceId,
                    $roleId,
                    $menuId,
                    $allowed,
                    $view,
                    $create,
                    $update,
                    $delete,
                    $userId ?: null,
                ]);
            }
        }

        $_SESSION['flash_success'] = 'Conference business permissions saved successfully.';
        header("Location: /easychair/admin/conference-business-permissions");
        exit;
    }
}
