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

use Gestoreasy\Core\Tenant\ConnectionManager;

$email = $argv[1] ?? '';
$tenant = $argv[2] ?? 'default';
if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    fwrite(STDERR, "Email inválido. Uso: php scripts\\set_supplier_emails.php <email> [tenant]\n");
    exit(1);
}

$pdo = ConnectionManager::forTenant($tenant);
$stmt = $pdo->prepare('UPDATE suppliers SET email = ?');
$stmt->execute([$email]);
$updated = $stmt->rowCount();

// Opcional: também atualizar tabela antiga 'fornecedores' se existir
try {
    $chk = $pdo->query("SHOW TABLES LIKE 'fornecedores'");
    $hasFornecedores = (bool)$chk->fetchColumn();
    $updatedFornecedores = 0;
    if ($hasFornecedores) {
        $stmt2 = $pdo->prepare('UPDATE fornecedores SET email = ?');
        $stmt2->execute([$email]);
        $updatedFornecedores = $stmt2->rowCount();
    }
} catch (\Throwable $e) { $hasFornecedores = false; $updatedFornecedores = 0; }

echo json_encode([
    'ok' => true,
    'tenant' => $tenant,
    'email' => $email,
    'updated_suppliers' => $updated,
    'updated_fornecedores' => $updatedFornecedores,
    'has_fornecedores' => $hasFornecedores
]);
echo "\n";