<?php
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);
$alert = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $mode = strtolower(trim((string)($_POST['active_login_mode'] ?? 'normal')));
    if (!in_array($mode, ['normal','mac','activation_code'], true)) $mode = 'normal';
    $qrcode = isset($_POST['qrcode_app_enabled']) ? 1 : 0;
    $renew = isset($_POST['renew_button_enabled']) ? 1 : 0;
    $testButton = isset($_POST['test_button_enabled']) ? 1 : 0;
    $vencimentoModal = isset($_POST['vencimento_modal_enabled']) ? 1 : 0;
    $st = $db->prepare('UPDATE app_config SET active_login_mode = ?, qrcode_app_enabled = ?, renew_button_enabled = ?, test_button_enabled = ?, vencimento_modal_enabled = ?, updated_at = datetime(\'now\') WHERE id = 1');
    $st->execute([$mode, $qrcode, $renew, $testButton, $vencimentoModal]);
    $alert = 'Configurações salvas com sucesso.';
}
$cfg = $db->query('SELECT * FROM app_config WHERE id = 1 LIMIT 1')->fetch(PDO::FETCH_ASSOC) ?: [];
require_once __DIR__ . '/../includes/header.php';
function h($v){ return htmlspecialchars((string)$v, 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-log-in-circle"></i></span>
      <div><h4 class="mb-1">Configuração do login</h4><p class="text-muted mb-0">Controle como os usuários entram nos aplicativos TV e celular.</p></div>
    </div>
    <span class="badge bg-primary"><i class="bx bx-devices"></i> TV + celular</span>
  </div>
  <div class="card-body">
    <?php if ($alert): ?><div class="alert alert-success"><i class="bx bx-check-circle me-1"></i><?= h($alert) ?></div><?php endif; ?>
    <form method="post">
      <div class="mb-4">
        <label class="form-label" for="active_login_mode">Modo de login ativo</label>
        <select name="active_login_mode" id="active_login_mode" class="form-select">
          <option value="normal" <?= (($cfg['active_login_mode'] ?? 'normal') === 'normal') ? 'selected' : '' ?>>Login normal com usuário e senha</option>
          <option value="mac" <?= (($cfg['active_login_mode'] ?? '') === 'mac') ? 'selected' : '' ?>>Login automático por MAC</option>
          <option value="activation_code" <?= (($cfg['active_login_mode'] ?? '') === 'activation_code') ? 'selected' : '' ?>>Login por código de ativação</option>
        </select>
        <div class="form-text">O login automático por MAC também funciona no modo normal quando o dispositivo já possui DNS, usuário e senha válidos.</div>
      </div>

      <div class="settings-grid mb-4">
        <label class="card p-3 mb-0" for="qrcode_app_enabled">
          <span class="d-flex align-items-center justify-content-between gap-3">
            <span><strong class="d-block mb-1">QR Code de ativação</strong><small class="text-muted">Mostra o QR Code e o card de ativação na tela de login.</small></span>
            <input class="form-check-input" type="checkbox" name="qrcode_app_enabled" id="qrcode_app_enabled" <?= ((int)($cfg['qrcode_app_enabled'] ?? 1) === 1) ? 'checked' : '' ?>>
          </span>
        </label>
        <label class="card p-3 mb-0" for="test_button_enabled">
          <span class="d-flex align-items-center justify-content-between gap-3">
            <span><strong class="d-block mb-1">Teste grátis</strong><small class="text-muted">Exibe o botão para gerar um teste na LoginActivity.</small></span>
            <input class="form-check-input" type="checkbox" name="test_button_enabled" id="test_button_enabled" <?= ((int)($cfg['test_button_enabled'] ?? 1) === 1) ? 'checked' : '' ?>>
          </span>
        </label>
        <label class="card p-3 mb-0" for="vencimento_modal_enabled">
          <span class="d-flex align-items-center justify-content-between gap-3">
            <span><strong class="d-block mb-1">Aviso de vencimento</strong><small class="text-muted">Ativa o modal de vencimento na tela inicial.</small></span>
            <input class="form-check-input" type="checkbox" name="vencimento_modal_enabled" id="vencimento_modal_enabled" <?= ((int)($cfg['vencimento_modal_enabled'] ?? 1) === 1) ? 'checked' : '' ?>>
          </span>
        </label>
        <label class="card p-3 mb-0" for="renew_button_enabled">
          <span class="d-flex align-items-center justify-content-between gap-3">
            <span><strong class="d-block mb-1">Botão Renovar</strong><small class="text-muted">Mostra o atalho de renovação dentro do aplicativo.</small></span>
            <input class="form-check-input" type="checkbox" name="renew_button_enabled" id="renew_button_enabled" <?= ((int)($cfg['renew_button_enabled'] ?? 1) === 1) ? 'checked' : '' ?>>
          </span>
        </label>
      </div>
      <div class="d-flex justify-content-end"><button class="btn btn-primary" type="submit"><i class="bx bx-save"></i> Salvar configurações</button></div>
    </form>
  </div>
</div>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
