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

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

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

$report = [ 'tenant' => $tenant, 'counts' => [], 'notes' => [] ];

// Contagem de documentos com tax_model_version e tax_data
foreach ([
    ['table' => 'sales_orders', 'key' => 'sales_orders'],
    ['table' => 'sales_order_items', 'key' => 'sales_order_items'],
    ['table' => 'sales_payments', 'key' => 'sales_payments'],
    ['table' => 'pos_sales', 'key' => 'pos_sales'],
    ['table' => 'purchase_invoices', 'key' => 'purchase_invoices']
] as $t) {
    try {
        $stmt = $pdo->query("SELECT 
            SUM(CASE WHEN tax_model_version IS NOT NULL THEN 1 ELSE 0 END) AS with_version,
            SUM(CASE WHEN tax_data IS NOT NULL THEN 1 ELSE 0 END) AS with_data,
            COUNT(*) AS total
        FROM {$t['table']}");
        $row = $stmt->fetch();
        $report['counts'][$t['key']] = $row ?: [];
    } catch (\Throwable $e) {
        $report['notes'][] = "Tabela {$t['table']} indisponível ou sem colunas (ok em ambientes iniciais).";
    }
}

// Produtos: presença de NCM/CFOP e tax_attributes
try {
    $stmt = $pdo->query("SELECT 
        SUM(CASE WHEN ncm IS NOT NULL AND ncm <> '' THEN 1 ELSE 0 END) AS with_ncm,
        SUM(CASE WHEN cfop IS NOT NULL AND cfop <> '' THEN 1 ELSE 0 END) AS with_cfop,
        SUM(CASE WHEN tax_attributes IS NOT NULL THEN 1 ELSE 0 END) AS with_tax_attrs,
        COUNT(*) AS total
      FROM products");
    $report['counts']['products'] = $stmt->fetch() ?: [];
} catch (\Throwable $e) {
    $report['notes'][] = 'Tabela products indisponível.';
}

echo json_encode(['ok' => true, 'report' => $report], JSON_UNESCAPED_UNICODE) . "\n";