<?php
// Seed de permisos para cambiar contraseña del Trader Room
if (php_sapi_name() !== 'cli') { echo "Ejecuta este script desde CLI"; }
require_once __DIR__ . '/../../database/connection.php';

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

    $perms = [
        'clients.change_portal_password',
        'leads.change_portal_password'
    ];

    foreach ($perms as $p) {
        $exists = $pdo->prepare('SELECT id FROM permissions WHERE name = ? LIMIT 1');
        $exists->execute([$p]);
        if (!$exists->fetchColumn()) {
            $ins = $pdo->prepare('INSERT INTO permissions(name, description) VALUES(?, ?)');
            $ins->execute([$p, 'Permite cambiar la contraseña del Trader Room']);
            echo "✓ Insertado permiso: $p\n";
        } else {
            echo "• Permiso ya existe: $p\n";
        }
    }

    // Asignar a rol admin si existe
    $adminRoleId = null;
    $stmtR = $pdo->query("SELECT id FROM roles WHERE name = 'admin' LIMIT 1");
    $adminRoleId = $stmtR->fetchColumn();
    if ($adminRoleId) {
        foreach ($perms as $p) {
            $pid = $pdo->prepare('SELECT id FROM permissions WHERE name = ? LIMIT 1');
            $pid->execute([$p]);
            $permId = $pid->fetchColumn();
            if ($permId) {
                $chk = $pdo->prepare('SELECT 1 FROM role_permissions WHERE role_id = ? AND permission_id = ?');
                $chk->execute([$adminRoleId, $permId]);
                if (!$chk->fetchColumn()) {
                    $pdo->prepare('INSERT INTO role_permissions(role_id, permission_id) VALUES(?, ?)')->execute([$adminRoleId, $permId]);
                    echo "✓ Asignado a admin: $p\n";
                } else {
                    echo "• Admin ya tiene: $p\n";
                }
            }
        }
    }

    echo "\nFinalizado.\n";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
?>
