<?php
require __DIR__ . '/../bootstrap.php';

use Gestoreasy\Core\Tenant\ConnectionManager;

$tenant = $argv[1] ?? 'default';
putenv("TENANT_ID={$tenant}");

try {
    $pdo = ConnectionManager::forTenant();
    // Verificar existência da tabela
    $chk = $pdo->prepare("SELECT COUNT(*) AS c FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'purchase_quotes'");
    $chk->execute();
    $exists = ((int)($chk->fetch()['c'] ?? 0)) > 0;
    if (!$exists) { fwrite(STDERR, "[quotes] Tabela 'purchase_quotes' não existe no tenant '{$tenant}'.\n"); exit(2); }

    $limit = isset($argv[2]) ? (int)$argv[2] : 10;
    $stmt = $pdo->prepare('SELECT id, supplier_id, valid_until, status, created_at FROM purchase_quotes ORDER BY id DESC LIMIT :lim');
    $stmt->bindValue(':lim', $limit, \PDO::PARAM_INT);
    $stmt->execute();
    $rows = $stmt->fetchAll();
    if (!$rows) { echo "[quotes] Nenhuma cotação encontrada.\n"; exit(0); }
    foreach ($rows as $r) {
        $id = (int)$r['id']; $sid = (int)$r['supplier_id']; $st = (string)$r['status']; $dt = (string)($r['created_at'] ?? '');
        // Contar itens
        $c = $pdo->prepare('SELECT COUNT(*) AS c FROM purchase_quote_items WHERE quote_id = :id'); $c->execute(['id' => $id]);
        $items = (int)($c->fetch()['c'] ?? 0);
        echo "#{$id} supplier={$sid} status={$st} itens={$items} created={$dt}\n";
    }
} catch (\Throwable $e) {
    fwrite(STDERR, "[quotes] Erro: {$e->getMessage()}\n");
    exit(1);
}
echo "[quotes] Listagem concluída para tenant '{$tenant}'.\n";
?>