<?php
require __DIR__ . '/../config/bootstrap.php';

use App\Core\Database;

$db = Database::getInstance();

echo "Restoring superadmin privileges...\n";

$roleStmt = $db->prepare("SELECT id FROM roles WHERE code='super_admin' LIMIT 1");
$roleStmt->execute();
$superRoleId = (int)$roleStmt->fetchColumn();

if ($superRoleId <= 0) {
    $db->prepare("INSERT INTO roles (code, name) VALUES ('super_admin', 'Super Admin')")->execute();
    $superRoleId = (int)$db->lastInsertId();
}

$userStmt = $db->prepare("SELECT id FROM users WHERE email='admin@jpu.edu.jo' LIMIT 1");
$userStmt->execute();
$adminUserId = (int)$userStmt->fetchColumn();

if ($adminUserId > 0) {
    $stmt = $db->prepare("
        UPDATE users
        SET role_id=?, org_id=NULL, is_active=1, preferred_lang='ar', updated_at=NOW()
        WHERE id=?
    ");
    $stmt->execute([$superRoleId, $adminUserId]);
}

$db->exec("
    INSERT IGNORE 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)
    SELECT c.org_id, c.id, {$superRoleId}, mi.id, 1, 1, 1, 1, 1, NULL
    FROM conferences c
    JOIN rbac_menu_items mi ON mi.is_active=1
");

$db->exec("
    UPDATE rbac_role_menu_permissions
    SET is_allowed=1, can_view=1, can_create=1, can_update=1, can_delete=1, updated_at=NOW()
    WHERE role_id={$superRoleId}
");

$stmt = $db->query("
    SELECT r.code,
           COUNT(*) total_rows,
           SUM(rp.is_allowed) allowed_rows,
           SUM(rp.can_view) view_rows,
           SUM(rp.can_create) create_rows,
           SUM(rp.can_update) update_rows,
           SUM(rp.can_delete) delete_rows
    FROM rbac_role_menu_permissions rp
    JOIN roles r ON r.id=rp.role_id
    WHERE r.code='super_admin'
    GROUP BY r.code
");
print_r($stmt->fetch(PDO::FETCH_ASSOC));
echo "Done.\n";
