<?php
/**
 * modules/oauth/authorize.php — pantalla de autorización OAuth de KamiQuery.
 *
 * La extensión abre /oauth/authorize?state=..&redirect_uri=vscode://..&device=..
 * El usuario (logueado) aprueba → generamos un código de un solo uso y redirigimos
 * a redirect_uri?code=..&state=.. La extensión lo canjea en /oauth/token.
 */
if (!defined('IN_APP')) { die('Acceso denegado'); }

$redirect = (string)($_GET['redirect_uri'] ?? '');
$state    = (string)($_GET['state'] ?? '');
$device   = trim((string)($_GET['device'] ?? '')) ?: 'KamiQuery (VSCode)';

// Solo permitimos volver a la extensión KamiQuery.
$allowed = strpos($redirect, 'vscode://kamiquery.kamiquery/') === 0;
if (!$allowed) {
    http_response_code(400);
    die('redirect_uri no permitido');
}

// Requiere sesión: si no, al login y de vuelta aquí.
if ($_user === null) {
    App::redirect('/login/?return=' . rawurlencode($_SERVER['REQUEST_URI']));
}

$done = false; $callback = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['approve'])) {
    $code = $auth->createOAuthCode($_user['id_user'], $redirect, $device);
    $sep  = (strpos($redirect, '?') !== false) ? '&' : '?';
    $callback = $redirect . $sep . 'code=' . rawurlencode($code) . '&state=' . rawurlencode($state);
    $done = true;   // mostramos pantalla de "completado" que abre VSCode
}

$lang = App::locale();
?><!doctype html>
<html lang="<?= App::e($lang) ?>" class="h-full">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="/assets/favicon.svg" type="image/svg+xml">
<title><?= App::e(App::t('oauth.title')) ?> · <?= App::e(App::t('app.name')) ?></title>
<script>(function(){var t=localStorage.getItem('theme');if(t==='dark'||(!t&&window.matchMedia('(prefers-color-scheme: dark)').matches))document.documentElement.classList.add('dark');})();</script>
<link rel="stylesheet" href="/assets/css/style.css">
</head>
<body class="flex min-h-full items-center justify-center bg-paper p-4 text-ink-900 dark:bg-ink-950 dark:text-paper">
  <div class="w-full max-w-sm">
    <div class="mb-6 text-center">
      <div class="mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-lg bg-primary-600 text-xl font-bold text-white">k</div>
      <h1 class="text-2xl font-semibold"><?= App::e(App::t('app.name')) ?></h1>
    </div>
    <div class="rounded-lg border border-gray-200 bg-white p-6 shadow-sm dark:border-ink-700 dark:bg-ink-900">
      <?php if ($done): ?>
        <div class="mb-3 flex items-center gap-2 text-success">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="h-6 w-6"><path stroke-linecap="round" stroke-linejoin="round" d="M20 6 9 17l-5-5"/></svg>
          <h2 class="text-lg font-medium"><?= App::e(App::t('oauth.done_title')) ?></h2>
        </div>
        <p class="mb-4 text-sm text-gray-dark dark:text-gray-light"><?= App::e(App::t('oauth.done_hint')) ?></p>
        <a href="<?= App::e($callback) ?>" class="block w-full rounded-lg bg-primary-600 px-4 py-2 text-center text-sm font-medium text-white hover:bg-primary-700"><?= App::e(App::t('oauth.open_vscode')) ?></a>
        <script>setTimeout(function(){ window.location.href = <?= json_encode($callback) ?>; }, 400);</script>
      <?php else: ?>
        <h2 class="mb-2 text-lg font-medium"><?= App::e(App::t('oauth.title')) ?></h2>
        <p class="mb-1 text-sm text-gray-dark dark:text-gray-light"><?= App::e(App::t('oauth.intro')) ?></p>
        <div class="my-4 rounded-lg border border-gray-200 px-4 py-3 text-sm dark:border-ink-700">
          <div class="font-medium"><?= App::e($device) ?></div>
          <div class="text-xs text-gray-dark dark:text-gray-light"><?= App::e($_user['email']) ?></div>
        </div>
        <form method="post" action="<?= App::e($_SERVER['REQUEST_URI']) ?>" class="space-y-3">
          <button name="approve" value="1" class="w-full rounded-lg bg-primary-600 px-4 py-2 text-sm font-medium text-white hover:bg-primary-700"><?= App::e(App::t('oauth.approve')) ?></button>
          <a href="/chat/" class="block w-full rounded-lg border border-gray-200 px-4 py-2 text-center text-sm hover:bg-gray-50 dark:border-ink-700 dark:hover:bg-ink-800"><?= App::e(App::t('oauth.deny')) ?></a>
        </form>
      <?php endif; ?>
    </div>
  </div>
</body>
</html>
