<?php
// Gera JWT e mfa_token para o admin do tenant default
// Uso: php scripts/issue_tokens.php

error_reporting(E_ERROR | E_PARSE);
ini_set('display_errors', '0');

$envPath = __DIR__ . '/../.env';
if (is_file($envPath)) {
    $lines = file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '' || str_starts_with($line, '#')) continue;
        [$key, $value] = array_pad(explode('=', $line, 2), 2, '');
        $key = trim($key);
        $value = trim($value);
        if ($key === '') continue;
        putenv("$key=$value");
        $_ENV[$key] = $value;
    }
}

$tenant = getenv('TENANT_ID') ?: 'default';
$dbHost = getenv('DB_HOST') ?: '127.0.0.1';
$dbUser = getenv('DB_USERNAME') ?: 'root';
$dbPass = getenv('DB_PASSWORD') ?: '';
$prefix = getenv('DB_BASE_PREFIX') ?: 'gestoreasy_tenant_';
$dbName = $prefix . $tenant;

$pdo = new PDO("mysql:host={$dbHost};dbname={$dbName};charset=utf8mb4", $dbUser, $dbPass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

$email = getenv('DEFAULT_ADMIN_EMAIL') ?: 'admin@local';
$row = $pdo->query("SELECT id FROM users WHERE email='" . addslashes($email) . "' LIMIT 1")->fetch();
if (!$row) { fwrite(STDERR, "Admin não encontrado\n"); exit(1); }
$uid = (int)$row['id'];

// JWT
$secret = getenv('JWT_SECRET') ?: 'changeme';
$now = time();
$header = ['alg' => 'HS256', 'typ' => 'JWT'];
$payload = ['sub' => $uid, 'tenant' => $tenant, 'iat' => $now, 'exp' => $now + 3600];
$b64u = function (string $s): string { return rtrim(strtr(base64_encode($s), '+/', '-_'), '='); };
$h = $b64u(json_encode($header));
$p = $b64u(json_encode($payload));
$s = $b64u(hash_hmac('sha256', "$h.$p", $secret, true));
$jwt = "$h.$p.$s";

// MFA token
$key = getenv('CERT_STORE_KEY');
if (!$key) { fwrite(STDERR, "CERT_STORE_KEY não configurado\n"); exit(2); }
$bin = (ctype_xdigit($key) && strlen($key) % 2 === 0) ? hex2bin($key) : $key;
$exp = time() + 300; $nonce = bin2hex(random_bytes(8));
$pl = $uid . ':' . $exp . ':' . $nonce;
$sig = bin2hex(hash_hmac('sha256', $pl, $bin, true));
$mfa = base64_encode($pl) . '.' . $sig;

echo json_encode(['jwt' => $jwt, 'mfa_token' => $mfa], JSON_UNESCAPED_UNICODE) . "\n";