<?php
// views/pages/minha_conta.php

require_once __DIR__ . '/../../app/config.php';
require_once __DIR__ . '/../../app/db.php';
require_once __DIR__ . '/../../app/auth_middleware.php';
require_once __DIR__ . '/../../app/license_middleware.php';
require_once __DIR__ . '/../../app/csrf.php';

require_auth_or_redirect();

$userId = $_SESSION['user']['id'] ?? null;
$email  = $_SESSION['user']['email'] ?? '';
$name   = $_SESSION['user']['name']  ?? '';

$licenca = null;
try {
  $pdo = db();
  $q = $pdo->prepare("
    SELECT contratado_em, expira_em
    FROM public.auth_users
    WHERE id = :id
    LIMIT 1
  ");
  $q->execute([':id' => $userId]);
  $licenca = $q->fetch();
} catch (Throwable $e) {
  // silencioso
}

$contratadoEm = $licenca && !empty($licenca['contratado_em']) ? (new DateTimeImmutable($licenca['contratado_em']))->format('d/m/Y H:i') : '—';
$expiraEm     = $licenca && !empty($licenca['expira_em'])     ? (new DateTimeImmutable($licenca['expira_em']))->format('d/m/Y H:i') : '—';

// ===== Status do plano (Ativo/Expirado) =====
$statusPlano = 'Indefinido';
$statusClass = '';
if (!empty($licenca['expira_em'])) {
  $agora   = new DateTimeImmutable('now');
  $expiraD = new DateTimeImmutable($licenca['expira_em']);
  if ($expiraD > $agora) {
    $statusPlano = 'Ativo';
    $statusClass = 'ativo';
  } else {
    $statusPlano = 'Expirado';
    $statusClass = 'expirado';
  }
}
?>
<style>
  .card{background:#fff; border:1px solid #e5e7eb; border-radius:14px; padding:16px}
  .dark .card{background:#0b0f1a; border-color:#1f2937}
  .label{font-size:.85rem; color:#6b7280}
  .value{font-weight:600}
  .hr{height:1px; background:rgba(148,163,184,.25); margin:14px 0}
  .muted{color:#6b7280; font-size:.9rem}
  .input{width:100%; background:rgba(2,6,23,.04); color:inherit; border:1px solid rgba(148,163,184,.35); border-radius:12px; padding:10px 12px; outline:none}
  .input:focus{border-color:#60a5fa; box-shadow:0 0 0 4px rgba(96,165,250,.18)}
  .btn{display:inline-flex; align-items:center; gap:8px; border:0; border-radius:12px; padding:10px 14px; font-weight:700; cursor:pointer}
.btn-primary{
  background: linear-gradient(90deg,#6ee7ff,#7c3aed);
  color:#0b1020;
  box-shadow:0 10px 30px rgba(124,58,237,.25);
  width:auto;
  align-self:start;
  padding:10px 24px;
  font-weight:600;
  transition:transform .2s ease;
}
.btn-primary:hover{
  transform:translateY(-1px);
}
  .msg{margin:12px 0 0; padding:10px 12px; border-radius:12px; font-size:.93rem; border:1px solid}
  .msg.ok {
    transition: all .3s ease;
    background: rgba(16,185,129,.12);
    color: #10b981;
    border-color: rgba(16,185,129,.4);
    font-weight: 600;
    box-shadow: 0 2px 8px rgba(16,185,129,.15);
  }
  .msg.err {
    background: rgba(239,68,68,.12);
    color: #ef4444;
    border-color: rgba(239,68,68,.45);
    font-weight: 600;
    box-shadow: 0 2px 8px rgba(239,68,68,.15);
    transition: all .3s ease;
  }
  .status-badge{
    display:inline-block; font-weight:600; border-radius:8px; padding:4px 10px;
    font-size:.85rem; letter-spacing:.3px; border:1px solid transparent
  }
  .status-badge.ativo{
    background: rgba(16,185,129,.15);
    color:#10b981;
    border-color: rgba(16,185,129,.4);
  }
  .status-badge.expirado{
    background: rgba(239,68,68,.15);
    color:#ef4444;
    border-color: rgba(239,68,68,.4);
  }
  .grid{display:grid; gap:12px}
  @media(min-width:900px){ .grid-2{grid-template-columns:1fr 1fr} }

/* Botão do formulário de senha: não ocupar 100% */
#formSenha .btn{
  width: auto !important;
  justify-self: start;
  align-self: start;
  padding: 10px 24px;
}
#formSenha .btn-primary:hover{
  transform: translateY(-1px);
}
</style>

<div class="space-y-4">
  <div class="card">
    <h2 class="text-lg font-semibold">Minha conta</h2>
    <p class="muted">Veja seu e-mail de cadastro, status do plano e altere sua senha.</p>
  </div>

  <div class="grid grid-2">
    <!-- Bloco: Dados da conta / Licença -->
    <div class="card">
      <div class="label">E-mail</div>
      <div class="value"><?= htmlspecialchars($email, ENT_QUOTES, 'UTF-8') ?></div>

      <div class="hr"></div>

      <div class="label">Plano</div>
      <div class="muted">Licença do Evolua Prospect</div>

      <div class="grid" style="margin-top:10px">
        <div>
          <div class="label">Contratado em</div>
          <div class="value"><?= $contratadoEm ?></div>
        </div>
        <div>
          <div class="label">Expira em</div>
          <div class="value"><?= $expiraEm ?></div>
        </div>
      </div>

      <!-- Status do plano -->
      <div style="margin-top:12px">
        <div class="label">Status do plano</div>
        <div class="status-badge <?= $statusClass ?>">
          <?= htmlspecialchars($statusPlano, ENT_QUOTES, 'UTF-8') ?>
        </div>
      </div>

      <?php if (defined('RENEW_URL') && RENEW_URL): ?>
        <div style="margin-top:14px">
          <!-- <a href="<?= htmlspecialchars(RENEW_URL, ENT_QUOTES, 'UTF-8') ?>" target="_blank" class="btn btn-primary">Gerenciar/renovar plano</a> -->
        </div>
      <?php endif; ?>
    </div>

    <!-- Bloco: Alterar senha -->
    <div class="card">
      <h3 class="font-semibold mb-1">Alterar senha</h3>
      <p class="muted">Por segurança, confirme sua senha atual.</p>

      <form id="formSenha" class="grid" style="margin-top:10px">
        <input type="hidden" name="csrf" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>">
        <label class="grid">
          <span class="label">Senha atual</span>
          <input class="input" type="password" name="current_password" required autocomplete="current-password" placeholder="********">
        </label>

        <label class="grid">
          <span class="label">Nova senha</span>
          <input class="input" type="password" name="new_password" required autocomplete="new-password" placeholder="Mín. 8 caracteres">
        </label>

        <label class="grid">
          <span class="label">Confirmar nova senha</span>
          <input class="input" type="password" name="new_password2" required autocomplete="new-password" placeholder="Repita a nova senha">
        </label>

        <button class="btn btn-primary" style="align-self:center">Salvar nova senha</button>

        <div id="respSenha" class="msg" style="display:none"></div>
      </form>
    </div>
  </div>

  <!-- ============================================ -->
  <!-- BLOCO: Chave OpenAI (só aparece se modo=client) -->
  <!-- ============================================ -->
  <?php require BASE_PATH . '/views/partials/openai_key_block.php'; ?>

</div>

<script>
(function(){
  const form = document.getElementById('formSenha');
  const box  = document.getElementById('respSenha');

  async function post(url, data){
    const r = await fetch(url, {
      method:'POST',
      headers:{'Content-Type':'application/x-www-form-urlencoded'},
      credentials:'same-origin',
      body: new URLSearchParams(data).toString()
    });
    const t = await r.text();
    try {
      const j = JSON.parse(t);
      if (!r.ok || j.ok === false) return { ok:false, error: j.error || 'Falha' };
      return j;
    } catch {
      return { ok:false, error: t || 'Falha' };
    }
  }

  form?.addEventListener('submit', async (e) => {
    e.preventDefault();
    const fd = new FormData(form);
    const payload = {
      action: 'change_password',
      csrf: fd.get('csrf'),
      current_password: fd.get('current_password') || '',
      new_password: fd.get('new_password') || '',
      new_password2: fd.get('new_password2') || ''
    };

    box.style.display = 'none';
    box.textContent = '';
    box.className = 'msg';

    const resp = await post('api/account.php', payload);

    if (resp.ok) {
      box.textContent = 'Senha atualizada com sucesso.';
      box.classList.add('ok');
      box.style.display = 'block';
      form.reset();
    } else {
      box.textContent = resp.error || 'Não foi possível atualizar a senha agora.';
      box.classList.add('err');
      box.style.display = 'block';
    }
  });
})();
</script>