<?php
namespace App\Controllers;

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

use App\Core\Database;

class AdminBusinessRbacController
{
    private function requireSuperadmin(): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

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

        if (($_SESSION['role'] ?? $_SESSION['user_role'] ?? '') !== 'superadmin') {
            http_response_code(403);
            exit("Only superadmin can manage business RBAC.");
        }
    }

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

        $db = Database::getInstance();

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

        $permissions = $db->query("
            SELECT *
            FROM business_permissions
            WHERE is_active = 1
            ORDER BY module_key, sort_order, permission_key
        ")->fetchAll(\PDO::FETCH_ASSOC);

        $rolePermissions = $db->query("
            SELECT role_id, permission_key, allowed
            FROM business_role_permissions
        ")->fetchAll(\PDO::FETCH_ASSOC);

        $entities = [
            'themes' => 'Themes / Tracks / Panels',
            'days' => 'Conference Days',
            'venues' => 'Venues',
            'sessions' => 'Sessions',
            'session_papers' => 'Session Papers',
            'galleys' => 'Galley Production',
            'issues' => 'Proceedings Issues',
            'issue_articles' => 'Issue Articles',
            'certificates' => 'Certificates',
            'committees' => 'Committees / TPC / Patrons',
        ];

        $crudRows = $db->query("
            SELECT *
            FROM business_crud_policies
        ")->fetchAll(\PDO::FETCH_ASSOC);

        $permMap = [];
        foreach ($rolePermissions as $rp) {
            $permMap[(int)$rp['role_id']][$rp['permission_key']] = (int)$rp['allowed'];
        }

        $crudMap = [];
        foreach ($crudRows as $cr) {
            $crudMap[(int)$cr['role_id']][$cr['entity_key']] = $cr;
        }

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

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

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

        $db = Database::getInstance();

        $roleId = (int)($_POST['role_id'] ?? 0);
        $permissions = $_POST['permissions'] ?? [];
        $crud = $_POST['crud'] ?? [];

        if ($roleId <= 0) {
            exit("Role required.");
        }

        $db->beginTransaction();

        try {
            $allPerms = $db->query("SELECT permission_key FROM business_permissions WHERE is_active=1")
                ->fetchAll(\PDO::FETCH_COLUMN);

            foreach ($allPerms as $key) {
                $allowed = isset($permissions[$key]) ? 1 : 0;

                $stmt = $db->prepare("
                    INSERT INTO business_role_permissions
                    (role_id, permission_key, allowed, created_by)
                    VALUES (?, ?, ?, ?)
                    ON DUPLICATE KEY UPDATE
                        allowed = VALUES(allowed),
                        updated_at = NOW()
                ");
                $stmt->execute([$roleId, $key, $allowed, (int)$_SESSION['user_id']]);
            }

            $entities = [
                'themes','days','venues','sessions','session_papers',
                'galleys','issues','issue_articles','certificates','committees'
            ];

            foreach ($entities as $entity) {
                $row = $crud[$entity] ?? [];

                $stmt = $db->prepare("
                    INSERT INTO business_crud_policies
                    (role_id, entity_key, can_view, can_create, can_update, can_delete, can_publish, created_by)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                    ON DUPLICATE KEY UPDATE
                        can_view = VALUES(can_view),
                        can_create = VALUES(can_create),
                        can_update = VALUES(can_update),
                        can_delete = VALUES(can_delete),
                        can_publish = VALUES(can_publish),
                        updated_at = NOW()
                ");
                $stmt->execute([
                    $roleId,
                    $entity,
                    isset($row['view']) ? 1 : 0,
                    isset($row['create']) ? 1 : 0,
                    isset($row['update']) ? 1 : 0,
                    isset($row['delete']) ? 1 : 0,
                    isset($row['publish']) ? 1 : 0,
                    (int)$_SESSION['user_id']
                ]);
            }

            $db->commit();

            header("Location: /easychair/admin/business-rbac?role_id=" . $roleId . "&saved=1");
            exit;
        } catch (\Throwable $e) {
            $db->rollBack();
            throw $e;
        }
    }
}
