#!/usr/bin/env php
<?php
/**
 * Client Block CLI
 *
 * Maneja los bloqueos de clientes del portal (tabla clientes_bloqueos).
 *
 * Uso:
 *   php bin/clientes-bloqueo status <IdCliente>
 *   php bin/clientes-bloqueo block <IdCliente> "<motivo>" [--dias=N]
 *   php bin/clientes-bloqueo unblock <IdCliente> [--motivo="..."]
 *   php bin/clientes-bloqueo list [--activos]
 *
 * Ejemplos:
 *   php bin/clientes-bloqueo block 42 "Uso indebido del laboratorio" --dias=30
 *   php bin/clientes-bloqueo unblock 42 --motivo="Apelacion aprobada"
 *   php bin/clientes-bloqueo status 42
 */

$basePath = dirname(__DIR__);
define('BASE_PATH', $basePath . '/');

require $basePath . '/core/helpers/Env.php';
Env::load($basePath . '/.env');

if (file_exists($basePath . '/app/config/Config.php')) {
    require $basePath . '/app/config/Config.php';
}
if (file_exists($basePath . '/app/config/ConfigEnv.php')) {
    require $basePath . '/app/config/ConfigEnv.php';
}

require_once $basePath . '/app/services/ClientReservationPolicyService.php';

// ─── argumentos ─────────────────────────────────────────────────
$args = array_slice($argv, 1);
$cmd = $args[0] ?? null;

if ($cmd === null || $cmd === '--help' || $cmd === '-h') {
    echo "\nClient Block CLI\n";
    echo "Comandos:\n";
    echo "  status <IdCliente>\n";
    echo "  block <IdCliente> \"<motivo>\" [--dias=N]\n";
    echo "  unblock <IdCliente> [--motivo=\"...\"]\n";
    echo "  list [--activos]\n";
    exit(0);
}

// ─── conexion a BD ──────────────────────────────────────────────
$dbConfig = null;
if (class_exists('ConfigEnv') && property_exists('ConfigEnv', 'DB_CONNECTIONS')) {
    $connections = ConfigEnv::$DB_CONNECTIONS;
    if (isset($connections['klee'])) {
        $dbConfig = $connections['klee'];
    }
}
if (!$dbConfig) {
    fwrite(STDERR, "[error] Configuracion de BD no encontrada.\n");
    exit(1);
}

try {
    $port = isset($dbConfig['port']) && $dbConfig['port'] !== '' ? $dbConfig['port'] : '3306';
    $dsn = "mysql:host={$dbConfig['host']};port={$port};dbname={$dbConfig['dbname']};charset=utf8mb4";
    $pdo = new PDO($dsn, $dbConfig['user'], $dbConfig['password']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    fwrite(STDERR, "[error] Conexion BD: " . $e->getMessage() . "\n");
    exit(1);
}

ClientReservationPolicyService::setPdo($pdo);

// ─── helpers parse ──────────────────────────────────────────────
$argInt = function ($name, $args, $default = null) {
    foreach ($args as $arg) {
        $prefix = '--' . $name . '=';
        if (strpos($arg, $prefix) === 0) {
            return (int)substr($arg, strlen($prefix));
        }
    }
    return $default;
};
$argStr = function ($name, $args, $default = '') {
    foreach ($args as $arg) {
        $prefix = '--' . $name . '=';
        if (strpos($arg, $prefix) === 0) {
            return (string)substr($arg, strlen($prefix));
        }
    }
    return $default;
};
$argFlag = function ($name, $args) {
    return in_array('--' . $name, $args, true);
};

$getClient = function ($id) use ($pdo) {
    $stmt = $pdo->prepare("SELECT Id, Nombre, Apellido, Documento, Email FROM clientes WHERE Id = ?");
    $stmt->execute(array((int)$id));
    return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
};

// ─── despacho ───────────────────────────────────────────────────
switch ($cmd) {
    case 'status':
        $id = (int)($args[1] ?? 0);
        if ($id <= 0) {
            fwrite(STDERR, "[error] IdCliente requerido.\n");
            exit(1);
        }
        $client = $getClient($id);
        if (!$client) {
            fwrite(STDERR, "[error] Cliente {$id} no existe.\n");
            exit(1);
        }
        $block = ClientReservationPolicyService::getActiveBlock($id);
        $active = ClientReservationPolicyService::countActiveReservations($id);
        $noShows = ClientReservationPolicyService::countRecentNoShows($id);
        echo "Cliente #{$id}: " . trim(($client['Nombre'] ?? '') . ' ' . ($client['Apellido'] ?? '')) . "\n";
        echo "  Documento: " . ($client['Documento'] ?? '') . "\n";
        echo "  Reservas activas: {$active} / " . ClientReservationPolicyService::getActiveQuota() . "\n";
        echo "  No-shows ultimos " . ClientReservationPolicyService::getNoShowWindowDays() . " dias: {$noShows} (threshold: " . ClientReservationPolicyService::getNoShowThreshold() . ")\n";
        if ($block) {
            echo "  BLOQUEADO: tipo={$block['Tipo']}, motivo=" . ($block['Motivo'] ?? '') . ", desde={$block['CreadoFecha']}, vence=" . ($block['VencimientoFecha'] ?? 'sin fecha') . "\n";
        } else {
            echo "  Sin bloqueos activos.\n";
        }
        exit(0);

    case 'block':
        $id = (int)($args[1] ?? 0);
        $motivo = (string)($args[2] ?? '');
        $dias = $argInt('dias', $args, null);
        if ($id <= 0 || $motivo === '') {
            fwrite(STDERR, "[error] Uso: block <IdCliente> \"<motivo>\" [--dias=N]\n");
            exit(1);
        }
        $client = $getClient($id);
        if (!$client) {
            fwrite(STDERR, "[error] Cliente {$id} no existe.\n");
            exit(1);
        }
        try {
            $blockId = ClientReservationPolicyService::blockClient($id, $motivo, $dias, 0, 0);
            echo "[ok] Cliente {$id} bloqueado (block_id={$blockId})";
            echo $dias !== null ? " por {$dias} dias.\n" : " indefinidamente.\n";
            exit(0);
        } catch (Throwable $e) {
            fwrite(STDERR, "[error] " . $e->getMessage() . "\n");
            exit(2);
        }

    case 'unblock':
        $id = (int)($args[1] ?? 0);
        $motivo = $argStr('motivo', $args, 'Desbloqueado via CLI');
        if ($id <= 0) {
            fwrite(STDERR, "[error] Uso: unblock <IdCliente> [--motivo=\"...\"]\n");
            exit(1);
        }
        $closed = ClientReservationPolicyService::unblockClient($id, $motivo, 0);
        echo "[ok] Bloqueos cerrados: {$closed}\n";
        exit(0);

    case 'list':
        $onlyActive = $argFlag('activos', $args);
        $where = $onlyActive ? "WHERE b.Activo = 1" : "";
        $sql = "SELECT b.Id, b.IdCliente, b.Tipo, b.Motivo, b.Activo, b.VencimientoFecha,
                       b.CreadoFecha, c.Nombre, c.Apellido
                FROM clientes_bloqueos b
                LEFT JOIN clientes c ON c.Id = b.IdCliente
                {$where}
                ORDER BY b.Activo DESC, b.CreadoFecha DESC
                LIMIT 200";
        $rows = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
        if (empty($rows)) {
            echo "Sin bloqueos registrados.\n";
            exit(0);
        }
        printf("%-6s %-8s %-12s %-8s %-19s %-19s %s\n", 'BlockId', 'Cliente', 'Tipo', 'Activo', 'Creado', 'Vence', 'Motivo');
        echo str_repeat('-', 100) . "\n";
        foreach ($rows as $r) {
            printf("%-6s %-8s %-12s %-8s %-19s %-19s %s\n",
                $r['Id'], $r['IdCliente'], $r['Tipo'],
                $r['Activo'] ? 'SI' : 'no',
                substr((string)$r['CreadoFecha'], 0, 19),
                substr((string)($r['VencimientoFecha'] ?? '-'), 0, 19),
                substr((string)($r['Motivo'] ?? ''), 0, 60)
            );
        }
        exit(0);

    default:
        fwrite(STDERR, "[error] Comando desconocido: {$cmd}. Use --help.\n");
        exit(1);
}
