<?php
declare(strict_types=1);

session_start();
if (!isset($_SESSION['panel_user'])) { header('Location: index.php'); exit; }
if (($_SESSION['tipo_user'] ?? '') !== 'admin') { header('Location: dashboard.php'); exit; }

require_once dirname(__DIR__) . '/api/_auth_common.php';
$db = new PDO('sqlite:' . dirname(__DIR__) . '/api/db.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
auth_ensure_schema($db);

if (empty($_SESSION['general_config_csrf'])) {
    $_SESSION['general_config_csrf'] = bin2hex(random_bytes(32));
}

$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $csrf = (string)($_POST['csrf_token'] ?? '');
    if (!hash_equals((string)$_SESSION['general_config_csrf'], $csrf)) {
        $error = 'Sessão expirada. Atualize a página e tente novamente.';
    } else {
        $tmdbKey = trim((string)($_POST['tmdb_api_key'] ?? ''));
        $sportsUrl = rtrim(trim((string)($_POST['sports_api_url'] ?? '')), '/');
        $language = trim((string)($_POST['app_language'] ?? 'pt_BR'));

        if (!preg_match('/^[a-f0-9]{32}$/i', $tmdbKey)) {
            $error = 'A chave da API do TMDB deve conter exatamente 32 caracteres hexadecimais.';
        } elseif (!in_array($language, ['pt_BR', 'en', 'es'], true)) {
            $error = 'Selecione um idioma válido.';
        } else {
            $parts = parse_url($sportsUrl);
            $scheme = strtolower((string)($parts['scheme'] ?? ''));
            $host = trim((string)($parts['host'] ?? ''));
            if (!in_array($scheme, ['http', 'https'], true) || $host === '') {
                $error = 'Informe uma URL válida para a API de esportes, iniciando com http:// ou https://.';
            }
        }

        if ($error === '') {
            $current = auth_get_general_app_config($db);
            $revision = (string)($current['language_revision'] ?? '');
            if (($current['app_language'] ?? 'pt_BR') !== $language || $revision === '') {
                $revision = 'lang_' . time() . '_' . bin2hex(random_bytes(4));
            }

            $st = $db->prepare("UPDATE app_config
                SET tmdb_api_key = ?, sports_api_url = ?, app_language = ?, language_revision = ?,
                    general_config_updated_at = datetime('now'), updated_at = datetime('now')
                WHERE id = 1");
            $st->execute([$tmdbKey, $sportsUrl, $language, $revision]);
            $success = 'Configurações gerais salvas. Os aplicativos receberão os novos valores automaticamente.';
        }
    }
}

$cfg = auth_get_general_app_config($db);
require_once __DIR__ . '/../includes/header.php';
function h($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
?>
<div class="card">
  <div class="card-header d-flex align-items-center justify-content-between flex-wrap gap-3">
    <div class="d-flex align-items-center gap-3">
      <span class="topbar-page-icon"><i class="bx bx-slider-alt"></i></span>
      <div>
        <h4 class="mb-1">Configurações gerais</h4>
        <p class="text-muted mb-0">Controle idioma, TMDB e a fonte de dados da aba Esportes.</p>
      </div>
    </div>
    <span class="badge bg-primary"><i class="bx bx-cloud-download"></i> Sincronização remota</span>
  </div>

  <div class="card-body">
    <?php if ($success !== ''): ?>
      <div class="alert alert-success"><i class="bx bx-check-circle me-1"></i><?= h($success) ?></div>
    <?php endif; ?>
    <?php if ($error !== ''): ?>
      <div class="alert alert-danger"><i class="bx bx-error-circle me-1"></i><?= h($error) ?></div>
    <?php endif; ?>

    <form method="post" autocomplete="off">
      <input type="hidden" name="csrf_token" value="<?= h($_SESSION['general_config_csrf']) ?>">

      <div class="row g-4">
        <div class="col-12 col-xl-4">
          <div class="card h-100 mb-0 border">
            <div class="card-body">
              <div class="d-flex align-items-center gap-2 mb-3">
                <span class="topbar-page-icon"><i class="bx bx-world"></i></span>
                <div><h5 class="mb-0">Idioma do aplicativo</h5><small class="text-muted">TV e celular</small></div>
              </div>
              <label class="form-label" for="app_language">Idioma definido pelo painel</label>
              <select class="form-select" name="app_language" id="app_language">
                <option value="pt_BR" <?= (($cfg['app_language'] ?? 'pt_BR') === 'pt_BR') ? 'selected' : '' ?>>Português (Brasil)</option>
                <option value="en" <?= (($cfg['app_language'] ?? '') === 'en') ? 'selected' : '' ?>>English</option>
                <option value="es" <?= (($cfg['app_language'] ?? '') === 'es') ? 'selected' : '' ?>>Español</option>
              </select>
              <div class="form-text">Quando o idioma for alterado aqui, o app aplica a mudança na próxima sincronização e reinicia uma vez para atualizar todas as telas.</div>
            </div>
          </div>
        </div>

        <div class="col-12 col-xl-8">
          <div class="card h-100 mb-0 border">
            <div class="card-body">
              <div class="d-flex align-items-center gap-2 mb-3">
                <span class="topbar-page-icon"><i class="bx bx-movie-play"></i></span>
                <div><h5 class="mb-0">API do TMDB</h5><small class="text-muted">Filmes, séries, detalhes, capas e pesquisas</small></div>
              </div>
              <label class="form-label" for="tmdb_api_key">Chave v3 da API</label>
              <input
                class="form-control font-monospace"
                type="text"
                name="tmdb_api_key"
                id="tmdb_api_key"
                maxlength="32"
                minlength="32"
                spellcheck="false"
                required
                value="<?= h($cfg['tmdb_api_key'] ?? '') ?>">
              <div class="form-text">A chave será usada por todas as telas e serviços do aplicativo que consultam api.themoviedb.org.</div>
            </div>
          </div>
        </div>

        <div class="col-12">
          <div class="card mb-0 border">
            <div class="card-body">
              <div class="d-flex align-items-center gap-2 mb-3">
                <span class="topbar-page-icon"><i class="bx bx-football"></i></span>
                <div><h5 class="mb-0">API da aba Esportes</h5></div>
              </div>
              <label class="form-label" for="sports_api_url">URL completa do endpoint de jogos</label>
              <input
                class="form-control font-monospace"
                type="url"
                name="sports_api_url"
                id="sports_api_url"
                placeholder="https://fut.thefull.site/jogos"
                spellcheck="false"
                required
                value="<?= h($cfg['sports_api_url'] ?? 'https://fut.thefull.site/jogos') ?>">
           
            </div>
          </div>
        </div>
      </div>

      <div class="d-flex justify-content-end mt-4">
        <button class="btn btn-primary px-4" type="submit"><i class="bx bx-save"></i> Salvar configurações gerais</button>
      </div>
    </form>
  </div>
</div>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
