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

declare(strict_types=1);

/**
 * Script de décryptage d'un utilisateur spécifique
 * Usage: ./decrypt-user <environment> <user_id>
 */

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

// Vérifier les arguments
if ($argc < 3) {
    error("Usage: " . basename($argv[0]) . " <environment> <user_id>");
    error("Exemple: " . basename($argv[0]) . " dva 123");
    exit(1);
}

$environment = strtoupper($argv[1]);
$userId = (int)$argv[2];

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");
    info("Recherche de l'utilisateur #$userId...\n");

    // Requête pour récupérer l'utilisateur
    $stmt = $pdo->prepare("
        SELECT
            u.id,
            u.encrypted_user_name,
            u.encrypted_email,
            u.encrypted_name,
            u.first_name,
            u.encrypted_phone,
            u.encrypted_mobile,
            u.sect_name,
            u.fk_role,
            u.fk_entite,
            u.fk_titre,
            u.date_naissance,
            u.date_embauche,
            u.created_at,
            u.updated_at,
            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 u.id = :user_id
    ");

    $stmt->execute(['user_id' => $userId]);
    $user = $stmt->fetch();

    if (!$user) {
        error("Utilisateur #$userId introuvable");
        exit(1);
    }

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

    $user['user_name'] = $crypto->decryptSearchable($user['encrypted_user_name']);
    $user['email'] = $crypto->decryptSearchable($user['encrypted_email']);
    $user['name'] = $crypto->decryptWithIV($user['encrypted_name']);
    $user['phone'] = $crypto->decryptWithIV($user['encrypted_phone']);
    $user['mobile'] = $crypto->decryptWithIV($user['encrypted_mobile']);
    $user['entite_name'] = $crypto->decryptWithIV($user['entite_encrypted_name']);

    // Affichage
    title("UTILISATEUR #" . $user['id']);

    echo color("Identité\n", 'bold');
    display("Username", $user['user_name']);
    display("Prénom", $user['first_name']);
    display("Nom", $user['name']);
    display("Email", $user['email']);
    display("Téléphone", $user['phone']);
    display("Mobile", $user['mobile']);

    echo "\n" . color("Fonction\n", 'bold');
    display("Rôle", $user['role_name'] . " (ID: " . $user['fk_role'] . ")");
    display("Secteur", $user['sect_name'] ?: '-');
    display("Titre", $user['fk_titre'] ? "#" . $user['fk_titre'] : '-');

    echo "\n" . color("Amicale\n", 'bold');
    display("ID Entité", (string)$user['fk_entite']);
    display("Nom Entité", $user['entite_name']);

    echo "\n" . color("Dates\n", 'bold');
    display("Date naissance", formatDate($user['date_naissance']));
    display("Date embauche", formatDate($user['date_embauche']));
    display("Date création", formatDate($user['created_at']));
    display("Dernière modif", formatDate($user['updated_at']));

    echo "\n";
    success("Utilisateur déchiffré avec succès");

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