#!/usr/bin/env php
<?php
/**
 * Waitlist CLI
 *
 * Maneja la lista de espera de citas (tabla citas_lista_espera).
 *
 * Uso:
 *   php bin/waitlist status <IdCliente>
 *   php bin/waitlist expire
 *   php bin/waitlist list [--activos] [--cliente=N] [--limit=N]
 *   php bin/waitlist cancel <Id> [--motivo="..."]
 *
 * Ejemplos:
 *   php bin/waitlist expire
 *   php bin/waitlist status 42
 *   php bin/waitlist list --activos --limit=20
 */

$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/WaitlistService.php';

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

if ($cmd === null || $cmd === '--help' || $cmd === '-h') {
    echo "\nWaitlist CLI\n";
    echo "Comandos:\n";
    echo "  status <IdCliente>\n";
    echo "  expire                                  (expira Notificadas vencidas y renotifica)\n";
    echo "  list [--activos] [--cliente=N] [--limit=N]\n";
    echo "  cancel <Id> [--motivo=\"...\"]            (cancela como sistema; requiere --cliente=N)\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);
}

WaitlistService::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);
};

$stateLabel = array(
    0 => 'Esperando',
    1 => 'Notificada',
    2 => 'Convertida',
    3 => 'Cancelada',
    4 => 'Expirada',
);

$formatRow = function (array $r) use ($stateLabel) {
    $estado = (int)($r['Estado'] ?? 0);
    return sprintf(
        "  #%d  cli=%d  agenda=%d  %s %s-%s  estado=%s  pos=%d  res_until=%s",
        (int)$r['Id'],
        (int)$r['IdCliente'],
        (int)$r['IdAgenda'],
        (string)$r['Fecha'],
        substr((string)$r['HoraInicio'], 0, 5),
        substr((string)$r['HoraFin'], 0, 5),
        $stateLabel[$estado] ?? ('?' . $estado),
        (int)($r['Posicion'] ?? 0),
        (string)($r['ReservedUntil'] ?? '-')
    );
};

// ─── despacho ───────────────────────────────────────────────────
switch ($cmd) {
    case 'status':
        $id = (int)($args[1] ?? 0);
        if ($id <= 0) {
            fwrite(STDERR, "[error] IdCliente requerido.\n");
            exit(1);
        }
        $entries = WaitlistService::getActiveEntriesForClient($id);
        echo "Cliente #$id - Entradas activas en lista de espera: " . count($entries) . "\n";
        foreach ($entries as $r) {
            echo $formatRow($r) . "\n";
        }
        exit(0);

    case 'expire':
        $res = WaitlistService::expireStaleNotifications();
        echo "Waitlist expire result:\n";
        echo "  Expired:    " . (int)$res['expired'] . "\n";
        echo "  Renotified: " . (int)$res['renotified'] . "\n";
        exit(0);

    case 'list':
        $soloActivos = $argFlag('activos', $args);
        $clienteId = $argInt('cliente', $args, 0);
        $limit = max(1, min(500, (int)$argInt('limit', $args, 50)));

        $where = array();
        $params = array();
        if ($soloActivos) {
            $where[] = "Estado IN (0, 1)";
        }
        if ($clienteId > 0) {
            $where[] = "IdCliente = :c";
            $params[':c'] = $clienteId;
        }
        $sql = "SELECT * FROM citas_lista_espera"
            . (count($where) > 0 ? " WHERE " . implode(' AND ', $where) : "")
            . " ORDER BY Id DESC LIMIT " . $limit;
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        echo "Entradas: " . count($rows) . "\n";
        foreach ($rows as $r) {
            echo $formatRow($r) . "\n";
        }
        exit(0);

    case 'cancel':
        $waitlistId = (int)($args[1] ?? 0);
        $clienteId = (int)$argInt('cliente', $args, 0);
        $motivo = $argStr('motivo', $args, 'Cancelada via CLI');
        if ($waitlistId <= 0 || $clienteId <= 0) {
            fwrite(STDERR, "[error] cancel requiere <Id> y --cliente=N\n");
            exit(1);
        }
        $ok = WaitlistService::cancelEntry($waitlistId, $clienteId, $motivo);
        echo $ok ? "Cancelada.\n" : "No se pudo cancelar (verifica Id/cliente/estado).\n";
        exit($ok ? 0 : 1);

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