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

use Gestoreasy\Core\Tenant\TenantAdmin;
use Gestoreasy\Core\Tenant\ConnectionManager;

function assertTrue($cond, $msg) { if (!$cond) { echo "FAIL: $msg\n"; exit(1); } }

$tenant = $argv[1] ?? 'default';
TenantAdmin::runMigrations($tenant);
$pdo = ConnectionManager::forTenant($tenant);

// create a transporter
$stmt = $pdo->prepare("INSERT INTO transportadoras (nome, cnpj, created_at) VALUES (?, ?, ?)");
$stmt->execute(['Transp Test', '00000000000191', date('Y-m-d H:i:s')]);
$transportadoraId = (int)$pdo->lastInsertId();
assertTrue($transportadoraId > 0, 'Transportadora criada deve ter id > 0');

// create a product (use existing schema: codigo, estoque, preco)
$code = 'SKU-' . substr((string)mt_rand(1000, 999999), 0, 6);
$stmt = $pdo->prepare("INSERT INTO products (codigo, estoque, preco, created_at) VALUES (?, ?, ?, ?)");
$stmt->execute([$code, 100, 10.0, date('Y-m-d H:i:s')]);
$productId = (int)$pdo->lastInsertId();
assertTrue($productId > 0, 'Produto criado deve ter id > 0');

// create a client required by sales_orders
$stmt = $pdo->prepare("INSERT INTO clients (nome, cnpj, created_at) VALUES (?, ?, ?)");
$stmt->execute(['Cliente Teste', '11.222.333/0001-44', date('Y-m-d H:i:s')]);
$clientId = (int)$pdo->lastInsertId();
assertTrue($clientId > 0, 'Cliente criado deve ter id > 0');

// create a user (seller) with required fields (use unique email)
$uniqueEmail = 'vendedor+' . substr((string)mt_rand(1000, 999999), 0, 6) . '@example.test';
$stmt = $pdo->prepare("INSERT INTO users (email, name, password_hash, created_at) VALUES (?, ?, ?, ?)");
$stmt->execute([$uniqueEmail, 'Vendedor Test', '$2y$10$abcdefghijklmnopqrstuv', date('Y-m-d H:i:s')]);
$userId = (int)$pdo->lastInsertId();
assertTrue($userId > 0, 'Usuário criado deve ter id > 0');

// create an order via direct DB insert with known columns
$numero = 'SO-' . substr((string)mt_rand(1000, 999999), 0, 6);
$stmt = $pdo->prepare("INSERT INTO sales_orders (numero, cliente_id, valor_total, status, created_at) VALUES (?, ?, ?, ?, ?)");
$stmt->execute([$numero, $clientId, 10.0, 'aberto', date('Y-m-d H:i:s')]);
$orderId = (int)$pdo->lastInsertId();
assertTrue($orderId > 0, 'Pedido criado deve ter id > 0');

// ensure delivery_json column exists and update it
try { $pdo->exec("ALTER TABLE sales_orders ADD COLUMN delivery_json JSON NULL"); } catch (\Throwable $e) {}
$payload = json_encode(['transportadora' => (int)$transportadoraId, 'freteValor' => 5.0], JSON_UNESCAPED_UNICODE);
$pdo->prepare('UPDATE sales_orders SET delivery_json = ? WHERE id = ?')->execute([$payload, $orderId]);
$row = $pdo->query("SELECT delivery_json FROM sales_orders WHERE id = " . (int)$orderId)->fetch(PDO::FETCH_ASSOC);
assertTrue(!empty((string)($row['delivery_json'] ?? '')), 'delivery_json deve estar preenchido');
assertTrue(json_decode((string)$row['delivery_json'], true) !== false, 'delivery_json deve ser JSON válido');

// create a payment linked to this order (using correct columns)
$stmt = $pdo->prepare("INSERT INTO sales_payments (order_id, metodo, valor, created_at) VALUES (?, ?, ?, ?)");
$stmt->execute([$orderId, 'dinheiro', 15.0, date('Y-m-d H:i:s')]);
$paymentId = (int)$pdo->lastInsertId();
assertTrue($paymentId > 0, 'Pagamento criado deve ter id > 0');

// insert an audit log entry mimicking AuditLogger logCreate for sales_orders
$stmt = $pdo->prepare("INSERT INTO audit_logs (user_id, action, resource, resource_id, new_data, created_at) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->execute([$userId, 'create', 'sales_orders', $orderId, json_encode(['id' => $orderId]), date('Y-m-d H:i:s')]);

// now query the report of sellers from audit_logs similar to SalesReportsController
$stmt = $pdo->prepare("SELECT DISTINCT u.id as user_id, u.name FROM audit_logs a JOIN users u ON u.id = a.user_id WHERE a.action = 'create' AND a.resource = 'sales_orders'");
$stmt->execute();
$sellers = $stmt->fetchAll(PDO::FETCH_ASSOC);
assertTrue(!empty($sellers), 'Relatório por vendedor deve retornar pelo menos um vendedor');
$found = false;
foreach ($sellers as $s) {
    if ((int)$s['user_id'] === $userId) { $found = true; break; }
}
assertTrue($found, 'Vendedor criado não aparece no relatório por vendedor');

echo "OK: SalesOrdersDeliveryAndReportsTest concluído com sucesso.\n";