<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/mercado_pago_helpers.php';

function page_message(string $title, string $message, bool $success = true): void
{
    $color = $success ? '#0f8f52' : '#c62828';
    $bg = $success ? '#e9fff3' : '#fff0f0';
    echo '<!doctype html><html lang="pt-BR"><head><meta charset="utf-8">';
    echo '<meta name="viewport" content="width=device-width, initial-scale=1">';
    echo '<title>Bulo - Conexao OAuth</title>';
    echo '<style>body{margin:0;font-family:Arial,Helvetica,sans-serif;background:#f3f7fb;color:#162033;display:grid;min-height:100vh;place-items:center}.box{max-width:520px;background:#fff;border:1px solid #dce6f2;border-radius:16px;padding:28px;box-shadow:0 18px 40px rgba(15,31,82,.16)}.status{display:inline-block;padding:8px 12px;border-radius:999px;background:' . $bg . ';color:' . $color . ';font-weight:800}h1{margin:18px 0 10px;font-size:28px}p{font-size:16px;line-height:1.5;color:#526170}</style>';
    echo '</head><body><main class="box"><span class="status">' . htmlspecialchars($success ? 'Concluido' : 'Erro', ENT_QUOTES, 'UTF-8') . '</span>';
    echo '<h1>' . htmlspecialchars($title, ENT_QUOTES, 'UTF-8') . '</h1>';
    echo '<p>' . htmlspecialchars($message, ENT_QUOTES, 'UTF-8') . '</p>';
    echo '<p>Voce ja pode fechar esta tela e voltar para o app.</p>';
    echo '</main></body></html>';
    exit;
}

$code = trim((string) ($_GET['code'] ?? ''));
$state = trim((string) ($_GET['state'] ?? ''));
$error = trim((string) ($_GET['error'] ?? ''));

if ($error !== '') {
    page_message('Conexao recusada', 'O provedor de pagamento retornou: ' . $error, false);
}
if ($code === '' || $state === '') {
    page_message('Link invalido', 'Nao recebemos o codigo de autorizacao necessario.', false);
}

try {
    $pdo = db();
    $pdo->beginTransaction();

    $stmt = $pdo->prepare(
        'SELECT *
         FROM mercado_pago_oauth_states
         WHERE state = ?
           AND usado = 0
           AND expira_em >= NOW()
         LIMIT 1
         FOR UPDATE'
    );
    $stmt->execute([$state]);
    $stateRow = $stmt->fetch();
    if (!$stateRow) {
        $pdo->rollBack();
        page_message('Link expirado', 'Inicie a conexao OAuth novamente pelo app.', false);
    }

    try {
        $token = mp_oauth_trocar_codigo(
            $pdo,
            $code,
            (string) $stateRow['redirect_uri'],
            isset($stateRow['code_verifier']) ? (string) $stateRow['code_verifier'] : null
        );
        $accessToken = trim((string) ($token['access_token'] ?? ''));
        if ($accessToken === '') {
            throw new RuntimeException('O provedor de pagamento nao retornou access_token.');
        }

        $usuarioMp = [];
        try {
            $usuarioMp = mp_oauth_usuario_me($accessToken);
        } catch (Throwable) {
            $usuarioMp = [];
        }

        $expiresIn = (int) ($token['expires_in'] ?? 0);
        $expiresSql = $expiresIn > 0
            ? date('Y-m-d H:i:s', time() + $expiresIn)
            : null;

        $upsert = $pdo->prepare(
            'INSERT INTO mercado_pago_contas
              (id_usuario, tipo_usuario, mp_user_id, mp_nickname, mp_email, access_token, refresh_token,
               token_expires_at, public_key, status, modo, observacao, conectado_em)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, "conectado", ?, ?, NOW())
             ON DUPLICATE KEY UPDATE
               mp_user_id = VALUES(mp_user_id),
               mp_nickname = VALUES(mp_nickname),
               mp_email = VALUES(mp_email),
               access_token = VALUES(access_token),
               refresh_token = VALUES(refresh_token),
               token_expires_at = VALUES(token_expires_at),
               public_key = COALESCE(NULLIF(VALUES(public_key), ""), public_key),
               status = "conectado",
               modo = VALUES(modo),
               observacao = VALUES(observacao),
               conectado_em = NOW(),
               desconectado_em = NULL'
        );
        $config = mp_config($pdo);
        $upsert->execute([
            (int) $stateRow['id_usuario'],
            (string) $stateRow['tipo_usuario'],
            (string) ($token['user_id'] ?? $usuarioMp['id'] ?? ''),
            (string) ($usuarioMp['nickname'] ?? ''),
            (string) ($usuarioMp['email'] ?? ''),
            $accessToken,
            (string) ($token['refresh_token'] ?? ''),
            $expiresSql,
            (string) ($token['public_key'] ?? ''),
            (string) $config['ambiente'],
            'Conta conectada via OAuth de pagamento.',
        ]);

        $mark = $pdo->prepare('UPDATE mercado_pago_oauth_states SET usado = 1 WHERE id = ?');
        $mark->execute([(int) $stateRow['id']]);
        $pdo->commit();

        page_message('Conta conectada', 'A conta foi vinculada com sucesso ao Bulo.');
    } catch (Throwable $e) {
        $err = $pdo->prepare('UPDATE mercado_pago_oauth_states SET erro = ? WHERE id = ?');
        $err->execute([$e->getMessage(), (int) $stateRow['id']]);
        $pdo->rollBack();
        page_message('Falha ao conectar', $e->getMessage(), false);
    }
} catch (Throwable $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    page_message('Falha ao conectar', $e->getMessage(), false);
}
