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

declare(strict_types=1);

/**
 * Script de listage des opérations
 * Usage: ./list-operations <environment> [--entite=<id>] [--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=<id>] [--limit=<n>]");
    error("Exemple: " . basename($argv[0]) . " dev");
    error("         " . basename($argv[0]) . " rca --entite=5");
    error("         " . basename($argv[0]) . " dva --entite=10 --limit=20");
    exit(1);
}

$environment = strtoupper($argv[1]);

// Parser les options
$filters = [];
$limit = 50;

for ($i = 2; $i < $argc; $i++) {
    if (preg_match('/^--entite=(\d+)$/', $argv[$i], $matches)) {
        $filters['entite'] = (int)$matches[1];
    } elseif (preg_match('/^--limit=(\d+)$/', $argv[$i], $matches)) {
        $limit = (int)$matches[1];
    } else {
        error("Option invalide: " . $argv[$i]);
        exit(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
            o.id,
            o.fk_entite,
            o.libelle,
            o.date_deb,
            o.date_fin,
            o.chk_distinct_sectors,
            o.chk_active,
            o.created_at,
            o.updated_at,
            e.encrypted_name as entite_encrypted_name,
            COUNT(DISTINCT p.id) as nb_passages,
            COUNT(DISTINCT u.id) as nb_users,
            COUNT(DISTINCT s.id) as nb_sectors
        FROM operations o
        LEFT JOIN entites e ON e.id = o.fk_entite
        LEFT JOIN ope_pass p ON p.fk_operation = o.id
        LEFT JOIN ope_users u ON u.fk_operation = o.id
        LEFT JOIN ope_sectors s ON s.fk_operation = o.id
        WHERE 1=1
    ";

    $params = [];

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

    $sql .= " GROUP BY o.id";
    $sql .= " ORDER BY o.date_deb DESC";
    $sql .= " LIMIT :limit";

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

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

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

    if (empty($operations)) {
        warning("\nAucune opération trouvée");
        exit(0);
    }

    // Déchiffrer les noms d'entités
    $config = DatabaseConfig::getInstance();
    $crypto = new CryptoService($config->getEncryptionKey());

    $operationsData = [];

    foreach ($operations as $op) {
        $operationsData[] = [
            'id' => $op['id'],
            'entite' => truncate($crypto->decryptWithIV($op['entite_encrypted_name']) ?? '-', 25),
            'libelle' => truncate($op['libelle'], 35),
            'date_deb' => date('d/m/Y', strtotime($op['date_deb'])),
            'date_fin' => date('d/m/Y', strtotime($op['date_fin'])),
            'passages' => $op['nb_passages'],
            'users' => $op['nb_users'],
            'sectors' => $op['nb_sectors'],
            'actif' => $op['chk_active'] ? '✓' : '✗',
        ];
    }

    // Affichage
    title("LISTE DES OPÉRATIONS - " . count($operationsData) . " résultat(s)");

    table(
        [
            'id' => 'ID',
            'entite' => 'Entité',
            'libelle' => 'Libellé',
            'date_deb' => 'Début',
            'date_fin' => 'Fin',
            'passages' => 'Passages',
            'users' => 'Users',
            'sectors' => 'Secteurs',
            'actif' => 'Actif',
        ],
        $operationsData,
        true
    );

    success("Opérations listées avec succès");

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