#!/usr/bin/env php
<?php
/**
 * Recurring Reservations CLI
 *
 * Maneja series de reservas recurrentes (tabla citas_recurrencias).
 *
 * Uso:
 *   php bin/recurring create --json='<rule.json>'
 *   php bin/recurring create --file=ruta/regla.json
 *   php bin/recurring list [--cliente=N] [--estado=0|1|2|3] [--limit=N]
 *   php bin/recurring instances <RecurrenciaId>
 *   php bin/recurring cancel <RecurrenciaId> [--from=YYYY-MM-DD] [--motivo="..."]
 *   php bin/recurring show <RecurrenciaId>
 *
 * Formato JSON de la regla (campos minimos):
 *   {
 *     "IdAgenda": 1,
 *     "NombreSolicitante": "Juan",
 *     "Frecuencia": "weekly",
 *     "Intervalo": 1,
 *     "DiasSemana": "1,3,5",
 *     "HoraInicio": "09:00:00",
 *     "HoraFin": "10:00:00",
 *     "FechaInicio": "2026-05-01",
 *     "FechaFin": "2026-06-30",
 *     "PolicyOnConflict": "skip"
 *   }
 *
 * Para frecuencia mensual usar Frecuencia="monthly" y "DiasMes"="15" (o "1,15").
 * Intervalo en monthly = cada N meses.
 *
 * Opcionales: IdAgendaRecurso, IdActivo, IdCliente, MaxOcurrencias,
 *             EstadoCitaInicial (0|1), Email/Telefono/Documento/Comentarios.
 */

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

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

if ($cmd === null || $cmd === '--help' || $cmd === '-h') {
    echo "\nRecurring Reservations CLI\n";
    echo "Comandos:\n";
    echo "  create --json='<rule json>' | --file=<path>\n";
    echo "  list [--cliente=N] [--estado=0|1|2|3] [--limit=N]\n";
    echo "  instances <RecurrenciaId>\n";
    echo "  cancel <RecurrenciaId> [--from=YYYY-MM-DD] [--motivo=\"...\"]\n";
    echo "  show <RecurrenciaId>\n";
    exit(0);
}

// ─── conexion 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);
}
RecurringReservationService::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;
};

$stateLabel = array(0 => 'Activa', 1 => 'Pausada', 2 => 'Cancelada', 3 => 'Finalizada');

switch ($cmd) {
    case 'create':
        $json = $argStr('json', $args, '');
        $file = $argStr('file', $args, '');
        if ($json === '' && $file !== '') {
            if (!is_readable($file)) {
                fwrite(STDERR, "[error] No se puede leer $file\n");
                exit(1);
            }
            $json = file_get_contents($file);
        }
        if ($json === '') {
            fwrite(STDERR, "[error] Debes pasar --json='...' o --file=...\n");
            exit(1);
        }
        $rule = json_decode($json, true);
        if (!is_array($rule)) {
            fwrite(STDERR, "[error] JSON invalido\n");
            exit(1);
        }
        $res = RecurringReservationService::createSeries($rule);
        echo "Resultado: " . ($res['ok'] ? 'OK' : 'FAIL') . "\n";
        echo "  " . $res['message'] . "\n";
        if (!empty($res['recurrenciaId'])) {
            echo "  RecurrenciaId: " . (int)$res['recurrenciaId'] . "\n";
            echo "  Citas creadas: " . (int)($res['created'] ?? 0) . "\n";
            $sk = $res['skipped'] ?? array();
            echo "  Citas omitidas: " . count($sk) . "\n";
            foreach ($sk as $d) {
                echo "    - $d\n";
            }
        }
        exit($res['ok'] ? 0 : 1);

    case 'list':
        $cliente = (int)$argInt('cliente', $args, 0);
        $estado = $argInt('estado', $args, null);
        $limit = max(1, min(500, (int)$argInt('limit', $args, 50)));
        $where = array();
        $params = array();
        if ($cliente > 0) {
            $where[] = "IdCliente = :c";
            $params[':c'] = $cliente;
        }
        if ($estado !== null) {
            $where[] = "Estado = :e";
            $params[':e'] = (int)$estado;
        }
        $sql = "SELECT Id, IdAgenda, IdCliente, NombreSolicitante, Frecuencia, DiasSemana, HoraInicio, HoraFin, FechaInicio, FechaFin, Estado, TotalCreadas, TotalOmitidas
                FROM citas_recurrencias"
            . (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 "Series: " . count($rows) . "\n";
        foreach ($rows as $r) {
            $est = isset($stateLabel[(int)$r['Estado']]) ? $stateLabel[(int)$r['Estado']] : '?';
            $rangoHoras = substr((string)$r['HoraInicio'], 0, 5) . '-' . substr((string)$r['HoraFin'], 0, 5);
            echo sprintf(
                "  #%d  ag=%d  cli=%s  %s  %s  dias=%s  %s  %s..%s  estado=%s  creadas=%d  omitidas=%d\n",
                (int)$r['Id'],
                (int)$r['IdAgenda'],
                $r['IdCliente'] !== null ? $r['IdCliente'] : '-',
                $r['NombreSolicitante'],
                $r['Frecuencia'],
                $r['DiasSemana'] ?? '-',
                $rangoHoras,
                $r['FechaInicio'],
                $r['FechaFin'] ?? '-',
                $est,
                (int)$r['TotalCreadas'],
                (int)$r['TotalOmitidas']
            );
        }
        exit(0);

    case 'instances':
        $id = (int)($args[1] ?? 0);
        if ($id <= 0) {
            fwrite(STDERR, "[error] RecurrenciaId requerido.\n");
            exit(1);
        }
        $rows = RecurringReservationService::listInstances($id);
        echo "Instancias de serie #$id: " . count($rows) . "\n";
        foreach ($rows as $r) {
            echo sprintf(
                "  cita=%d  %s %s-%s  estado=%d  entrega=%d\n",
                (int)$r['Id'],
                $r['Fecha'],
                substr((string)$r['HoraInicio'], 0, 5),
                substr((string)$r['HoraFin'], 0, 5),
                (int)$r['Estado'],
                (int)$r['EstadoEntrega']
            );
        }
        exit(0);

    case 'cancel':
        $id = (int)($args[1] ?? 0);
        if ($id <= 0) {
            fwrite(STDERR, "[error] RecurrenciaId requerido.\n");
            exit(1);
        }
        $from = $argStr('from', $args, '') ?: null;
        $motivo = $argStr('motivo', $args, '');
        $cancelled = RecurringReservationService::cancelSeries($id, $from, $motivo);
        echo "Citas canceladas: $cancelled\n";
        exit(0);

    case 'show':
        $id = (int)($args[1] ?? 0);
        $serie = RecurringReservationService::getSeries($id);
        if (!$serie) {
            fwrite(STDERR, "[error] Serie no encontrada.\n");
            exit(1);
        }
        foreach ($serie as $k => $v) {
            echo str_pad($k, 22) . ' : ' . ($v === null ? 'NULL' : $v) . "\n";
        }
        exit(0);

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