<?php
require __DIR__ . '/../api/bootstrap.php';

use App\Core\Csrf;
use App\Core\Database;

$csrf = Csrf::token();
$token = trim((string)($_GET['token'] ?? ''));
$title = 'Account activation';
$message = 'Activation link is missing or invalid.';
$success = false;
$canResend = true;
$prefillEmail = '';
$eyebrow = 'Activation issue';

if ($token !== '') {
    try {
        $pdo = Database::connection();
        $stmt = $pdo->prepare('SELECT id, full_name, email, status, email_verified_at, activation_expires_at FROM users WHERE activation_token = ? LIMIT 1');
        $stmt->execute([$token]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$user) {
            $message = 'This activation link is invalid or has already been used. If your account is not active yet, request a fresh activation email below.';
        } elseif (!empty($user['email_verified_at']) && ($user['status'] ?? '') === 'active') {
            $success = true;
            $canResend = false;
            $eyebrow = 'Activated';
            $message = 'Your account is already active. You can log in now.';
        } elseif (!empty($user['activation_expires_at']) && strtotime((string)$user['activation_expires_at']) < time()) {
            $prefillEmail = (string)($user['email'] ?? '');
            $pdo->prepare('UPDATE users SET status = "inactive", activation_token = NULL, activation_expires_at = NULL, updated_at = NOW() WHERE id = ?')->execute([(int)$user['id']]);
            $message = 'This activation link expired. Please request a fresh activation email below.';
        } else {
            $pdo->prepare('UPDATE users SET status = "active", email_verified_at = NOW(), activated_at = NOW(), activation_token = NULL, failed_login_count = 0, locked_until = NULL, updated_at = NOW() WHERE id = ?')->execute([(int)$user['id']]);
            $success = true;
            $canResend = false;
            $eyebrow = 'Activated';
            $message = 'Your account has been activated successfully. You can log in now.';
        }
    } catch (Throwable $e) {
        $message = 'Activation failed: ' . $e->getMessage();
    }
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?= htmlspecialchars($title) ?> | Pyrk</title>
  <link rel="stylesheet" href="assets/css/app.css">
  <link rel="stylesheet" href="assets/css/activation_dates.css">
  <link rel="stylesheet" href="assets/css/activation_resend_pro.css?v=1">
</head>
<body class="auth-page">
  <div class="auth-shell single-auth">
    <div class="panel activation-panel activation-resend-panel">
      <div class="brand-badge">PYRK</div>
      <p class="eyebrow"><?= htmlspecialchars($eyebrow) ?></p>
      <h1><?= htmlspecialchars($title) ?></h1>
      <p class="<?= $success ? 'notice ok' : 'notice bad' ?>"><?= htmlspecialchars($message) ?></p>

      <?php if ($canResend): ?>
        <div class="activation-resend-card">
          <strong>Need a new activation link?</strong>
          <span>Enter the email used during registration and we will send a fresh activation email.</span>
          <form id="activationResendForm" class="activation-resend-form">
            <input name="email" type="email" placeholder="Email address" autocomplete="email" value="<?= htmlspecialchars($prefillEmail) ?>" required>
            <button class="btn" type="submit">Resend activation email</button>
          </form>
          <p id="activationResendMsg" class="notice"></p>
        </div>
      <?php endif; ?>

      <a class="btn btn-light activation-login-btn" href="login-dev.php">Go to login</a>
    </div>
  </div>

<script>
window.PYRK_API_BASE='../api';
window.PYRK_CSRF='<?= htmlspecialchars($csrf) ?>';
</script>
<script src="assets/js/api.js"></script>
<script>
const activationResendForm = document.getElementById('activationResendForm');
if (activationResendForm) {
  activationResendForm.addEventListener('submit', async event => {
    event.preventDefault();
    const msg = document.getElementById('activationResendMsg');
    const btn = activationResendForm.querySelector('button[type="submit"]');
    if (btn) btn.disabled = true;
    msg.textContent = 'Sending activation email...';
    msg.className = 'notice';

    const data = Object.fromEntries(new FormData(activationResendForm));
    const res = await Pyrk.post('auth.php', {action: 'resend_activation', ...data});

    msg.textContent = res.message || (res.ok ? 'Request completed.' : 'Could not resend activation email.');
    msg.className = 'notice ' + (res.ok ? 'ok' : 'bad');
    if (btn) btn.disabled = false;
  });
}
</script>
</body>
</html>
