<?php
/**
 * Script: Grant all permissions to Admin and ensure integration permissions exist.
 * Usage: php modules/database/grant_admin_all_permissions.php
 */
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';

$db = getDB();
$pdo = $db->getConnection();

function insertPermission($pdo, $perm) {
    $sql = "INSERT IGNORE INTO permissions (name, display_name, description, module, action, is_system, updated_at) VALUES (?,?,?,?,?,1,NOW())";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$perm['name'], $perm['display_name'], $perm['description'], $perm['module'], $perm['action']]);
}

function getRoleId($pdo, $roleName) {
    $stmt = $pdo->prepare("SELECT id FROM roles WHERE name = ? LIMIT 1");
    $stmt->execute([$roleName]);
    return (int)($stmt->fetchColumn() ?: 0);
}

function getUserIdByUsername($pdo, $username) {
    $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? LIMIT 1");
    $stmt->execute([$username]);
    return (int)($stmt->fetchColumn() ?: 0);
}

function assignUserRole($pdo, $userId, $roleId) {
    $stmt = $pdo->prepare("INSERT IGNORE INTO user_roles (user_id, role_id) VALUES (?, ?)");
    $stmt->execute([$userId, $roleId]);
}

function assignAllPermissionsToRole($pdo, $roleId) {
    $permIds = $pdo->query("SELECT id FROM permissions")->fetchAll(PDO::FETCH_COLUMN);
    $stmt = $pdo->prepare("INSERT IGNORE INTO role_permissions (role_id, permission_id) VALUES (?, ?)");
    foreach ($permIds as $pid) {
        $stmt->execute([$roleId, (int)$pid]);
    }
    return count($permIds);
}

// Define permissions we’ve introduced for integrations and related features
$newPerms = [
    // Integrations module base perms
    ['name'=>'integrations.view','display_name'=>'Ver Integraciones','description'=>'Permite ver la página de integraciones','module'=>'integrations','action'=>'view'],
    ['name'=>'integrations.manage','display_name'=>'Gestionar Integraciones','description'=>'Permite gestionar todas las integraciones','module'=>'integrations','action'=>'manage'],
    ['name'=>'menu.integrations.view','display_name'=>'Ver Menú Integraciones','description'=>'Ver Integraciones en el menú','module'=>'menu','action'=>'integrations.view'],

    // Big4pay specific
    ['name'=>'big4pay.view','display_name'=>'Ver Big4pay','description'=>'Permite ver la configuración de Big4pay','module'=>'integrations','action'=>'big4pay.view'],
    ['name'=>'big4pay.configure','display_name'=>'Configurar Big4pay','description'=>'Permite configurar la integración de Big4pay','module'=>'integrations','action'=>'big4pay.configure'],
    ['name'=>'big4pay.test','display_name'=>'Probar Big4pay','description'=>'Permite ejecutar pruebas de la integración Big4pay','module'=>'integrations','action'=>'big4pay.test'],
    ['name'=>'big4pay.process_payments','display_name'=>'Procesar Pagos Big4pay','description'=>'Permite procesar pagos a través de Big4pay','module'=>'integrations','action'=>'big4pay.process_payments'],

    // Voiso specific
    ['name'=>'voiso.view','display_name'=>'Ver Voiso','description'=>'Permite ver la configuración de Voiso','module'=>'integrations','action'=>'voiso.view'],
    ['name'=>'voiso.configure','display_name'=>'Configurar Voiso','description'=>'Permite configurar la integración de Voiso','module'=>'integrations','action'=>'voiso.configure'],
    ['name'=>'voiso.test','display_name'=>'Probar Voiso','description'=>'Permite probar la integración de Voiso','module'=>'integrations','action'=>'voiso.test'],
    ['name'=>'voiso.manage_calls','display_name'=>'Gestionar Llamadas Voiso','description'=>'Permite gestionar llamadas a través de Voiso','module'=>'integrations','action'=>'voiso.manage_calls'],
    ['name'=>'voiso.click_to_call','display_name'=>'Click-to-call Voiso','description'=>'Permite realizar llamadas desde fichas','module'=>'integrations','action'=>'voiso.click_to_call'],

    // API management future
    ['name'=>'api.webhooks.manage','display_name'=>'Gestionar Webhooks','description'=>'Permite gestionar webhooks de integraciones','module'=>'integrations','action'=>'api.webhooks.manage'],
    ['name'=>'api.keys.manage','display_name'=>'Gestionar API Keys','description'=>'Permite gestionar claves de API','module'=>'integrations','action'=>'api.keys.manage'],
    ['name'=>'api.logs.view','display_name'=>'Ver Logs de API','description'=>'Permite ver logs de integraciones API','module'=>'integrations','action'=>'api.logs.view'],
];

// Insert permissions (idempotent)
foreach ($newPerms as $p) { insertPermission($pdo, $p); }

// Ensure admin role exists
$adminRoleId = getRoleId($pdo, 'admin');
if (!$adminRoleId) {
    echo "Error: rol 'admin' no existe.\n";
    exit(1);
}

// Ensure user 'admin' is assigned to admin role
$adminUserId = getUserIdByUsername($pdo, 'admin');
if ($adminUserId) {
    assignUserRole($pdo, $adminUserId, $adminRoleId);
}

// Assign ALL permissions to Admin role
$totalPerms = assignAllPermissionsToRole($pdo, $adminRoleId);

echo "Asignación completada. Total permisos en sistema: {$totalPerms}.\n";
echo "Rol Admin (ID {$adminRoleId}) ahora tiene todos los permisos.\n";
if ($adminUserId) { echo "Usuario 'admin' (ID {$adminUserId}) vinculado al rol Admin.\n"; }
?>