#!/usr/bin/env php
<?php

declare(strict_types=1);

/**
 * Script de listing des utilisateurs avec données déchiffrées
 * Usage: ./list-users <environment> [--entite=X] [--role=Y] [--limit=N]
 */

require_once __DIR__ . '/../lib/CryptoService.php';
require_once __DIR__ . '/../lib/DatabaseConnection.php';
require_once __DIR__ . '/../lib/helpers.php';

// Vérifier les arguments
if ($argc < 2) {
    error("Usage: " . basename($argv[0]) . " <environment> [--entite=X] [--role=Y] [--limit=N]");
    error("Exemple: " . basename($argv[0]) . " dva --entite=5 --limit=20");
    exit(1);
}

$environment = strtoupper($argv[1]);
$filters = [];
$limit = 50;

// Parser les options
for ($i = 2; $i < $argc; $i++) {
    if (preg_match('/--entite=(\d+)/', $argv[$i], $matches)) {
        $filters['entite'] = (int)$matches[1];
    } elseif (preg_match('/--role=(\d+)/', $argv[$i], $matches)) {
        $filters['role'] = (int)$matches[1];
    } elseif (preg_match('/--limit=(\d+)/', $argv[$i], $matches)) {
        $limit = (int)$matches[1];
    }
}

try {
    // Ouvrir le tunnel SSH si nécessaire
    $tunnelScript = __DIR__ . '/_ssh-tunnel.sh';
    exec("$tunnelScript open $environment 2>&1", $output, $exitCode);

    if ($exitCode !== 0) {
        error("Impossible d'ouvrir le tunnel SSH");
        exit(1);
    }

    // Connexion à la base de données
    $db = new DatabaseConnection($environment);
    $pdo = $db->connect();

    info("Environnement: $environment");
    if (!empty($filters)) {
        info("Filtres: " . json_encode($filters));
    }
    info("Limite: $limit\n");

    // Construction de la requête
    $sql = "
        SELECT
            u.id,
            u.encrypted_user_name,
            u.encrypted_email,
            u.encrypted_name,
            u.first_name,
            u.fk_role,
            u.fk_entite,
            r.libelle as role_name,
            e.encrypted_name as entite_encrypted_name
        FROM users u
        LEFT JOIN x_users_roles r ON u.fk_role = r.id
        LEFT JOIN entites e ON u.fk_entite = e.id
        WHERE 1=1
    ";

    $params = [];

    if (isset($filters['entite'])) {
        $sql .= " AND u.fk_entite = :entite";
        $params['entite'] = $filters['entite'];
    }

    if (isset($filters['role'])) {
        $sql .= " AND u.fk_role = :role";
        $params['role'] = $filters['role'];
    }

    $sql .= " ORDER BY u.id DESC LIMIT :limit";
    $params['limit'] = $limit;

    $stmt = $pdo->prepare($sql);

    // Bind des paramètres
    foreach ($params as $key => $value) {
        if ($key === 'limit') {
            $stmt->bindValue(':' . $key, $value, PDO::PARAM_INT);
        } else {
            $stmt->bindValue(':' . $key, $value);
        }
    }

    $stmt->execute();
    $users = $stmt->fetchAll();

    if (empty($users)) {
        warning("Aucun utilisateur trouvé");
        exit(0);
    }

    // Déchiffrer les données
    $config = DatabaseConfig::getInstance();
    $crypto = new CryptoService($config->getEncryptionKey());

    $decryptedUsers = [];

    foreach ($users as $user) {
        $decryptedUsers[] = [
            'id' => $user['id'],
            'username' => truncate($crypto->decryptSearchable($user['encrypted_user_name']) ?? '-', 20),
            'email' => truncate($crypto->decryptSearchable($user['encrypted_email']) ?? '-', 30),
            'prenom' => truncate($user['first_name'] ?? '-', 15),
            'nom' => truncate($crypto->decryptWithIV($user['encrypted_name']) ?? '-', 20),
            'role' => $user['role_name'] ?? '-',
            'entite' => truncate($crypto->decryptWithIV($user['entite_encrypted_name']) ?? '-', 25),
        ];
    }

    // Affichage
    title("LISTE DES UTILISATEURS - " . count($decryptedUsers) . " résultat(s)");

    table(
        [
            'id' => 'ID',
            'username' => 'Username',
            'prenom' => 'Prénom',
            'nom' => 'Nom',
            'email' => 'Email',
            'role' => 'Rôle',
            'entite' => 'Entité',
        ],
        $decryptedUsers,
        true
    );

    success("Affichage terminé");

} catch (Exception $e) {
    error("Erreur: " . $e->getMessage());
    exit(1);
}
