<?php
// verify_email.php
// - Success: verifies and redirects to client login
// - Already verified / Invalid token: show an HTML card (no JSON)

// Safe logging (no error display)
ini_set('display_errors', '0');
ini_set('log_errors', '1');
if (!ini_get('error_log')) {
    ini_set('error_log', __DIR__ . '/php-error.log');
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

function render_card($title, $message, $buttonUrl = 'https://user.vistafxsolutions.com/login', $buttonText = 'Go to Login') {
    header('Content-Type: text/html; charset=UTF-8');
    $titleEsc = htmlspecialchars($title, ENT_QUOTES, 'UTF-8');
    $messageEsc = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
    $buttonUrlEsc = htmlspecialchars($buttonUrl, ENT_QUOTES, 'UTF-8');
    $buttonTextEsc = htmlspecialchars($buttonText, ENT_QUOTES, 'UTF-8');

    echo <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>{$titleEsc}</title>
<style>
  :root {
    --bg: #0f172a;         /* slate-900 */
    --card: #111827;       /* gray-900 */
    --muted: #9ca3af;      /* gray-400 */
    --text: #e5e7eb;       /* gray-200 */
    --accent: #22c55e;     /* green-500 */
    --accent2:#ef4444;     /* red-500 */
    --ring: rgba(34,197,94,0.3);
  }
  * { box-sizing: border-box; }
  body {
    margin: 0; min-height: 100vh; display: grid; place-items: center;
    background: radial-gradient(1200px 600px at 50% -10%, #1f2937 10%, transparent 60%), var(--bg);
    color: var(--text); font-family: system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, "Helvetica Neue", Arial, "Apple Color Emoji", "Segoe UI Emoji";
  }
  .card {
    width: 92vw; max-width: 520px; background: linear-gradient(180deg, rgba(255,255,255,0.04), rgba(255,255,255,0.02));
    border: 1px solid rgba(255,255,255,0.08); border-radius: 20px; padding: 28px 24px;
    box-shadow: 0 20px 40px rgba(0,0,0,0.35), inset 0 1px 0 rgba(255,255,255,0.05);
    backdrop-filter: saturate(150%) blur(8px);
  }
  .header {
    display: flex; align-items: center; gap: 14px; margin-bottom: 10px;
  }
  .badge {
    display:inline-grid; place-items:center; width: 42px; height: 42px; border-radius: 12px;
    background: rgba(34,197,94,0.12); color: var(--accent);
    box-shadow: 0 0 0 6px var(--ring);
    font-weight: 700; font-size: 20px; letter-spacing: 0.2px;
  }
  .title {
    font-size: 22px; font-weight: 800; letter-spacing: 0.2px;
  }
  .desc {
    margin: 8px 0 18px; color: var(--muted); line-height: 1.6;
  }
  .actions { display: flex; gap: 12px; }
  .btn {
    appearance: none; border: 0; cursor: pointer; text-decoration: none;
    padding: 12px 18px; border-radius: 12px; font-weight: 700; letter-spacing: 0.25px;
    transition: transform .08s ease, filter .2s ease, background .2s ease;
    will-change: transform, filter;
  }
  .btn:active { transform: translateY(1px) scale(0.99); }
  .btn-primary {
    background: linear-gradient(180deg, rgba(34,197,94,0.95), rgba(22,163,74,0.95));
    color: white; box-shadow: 0 10px 24px rgba(34,197,94,0.35);
  }
  .btn-primary:hover { filter: brightness(1.06); }
  .footer {
    margin-top: 16px; font-size: 13px; color: var(--muted);
  }
  .warn { color: #fca5a5; } /* light red text */
</style>
</head>
<body>
  <main class="card" role="main" aria-labelledby="title">
    <div class="header">
      <div class="badge">✓</div>
      <div class="title" id="title">{$titleEsc}</div>
    </div>
    <p class="desc">{$messageEsc}</p>
    <div class="actions">
      <a class="btn btn-primary" href="{$buttonUrlEsc}">{$buttonTextEsc}</a>
    </div>
    <div class="footer">
      If you reached this page by mistake, you can safely close this tab.
    </div>
  </main>
</body>
</html>
HTML;
    exit;
}

try {
    require_once __DIR__ . '/unified_config.php';

    // Connect (db() function or $conn provided)
    if (function_exists('db')) {
        $conn = db();
    } elseif (isset($conn) && $conn instanceof mysqli) {
        // ok
    } else {
        throw new Exception("Database connection not provided. Ensure unified_config.php defines db() or \$conn.");
    }

    // Get token from GET or POST
    $token = '';
    if (isset($_GET['token'])) $token = trim((string)$_GET['token']);
    if ($token === '' && isset($_POST['token'])) $token = trim((string)$_POST['token']);

    if ($token === '') {
        render_card('Invalid Verification Link', 'The verification link is missing or malformed. Please request a new verification email.', 'https://user.vistafxsolutions.com/login', 'Go to Login');
    }

    // Find user by token
    $stmt = $conn->prepare("
        SELECT id, email_confirmed
        FROM loginusers
        WHERE emailToken = ?
        LIMIT 1
    ");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $res  = $stmt->get_result();
    $user = $res->fetch_assoc();

    if (!$user) {
        render_card('Link Expired or Invalid', 'This verification link is invalid or has expired. Please request a new verification email.', 'https://user.vistafxsolutions.com/login', 'Go to Login');
    }

    // Already verified -> show card (no redirect)
    if ((int)$user['email_confirmed'] === 1) {
        render_card('You’re Already Verified', 'Your email address is already verified. You can log in to your account anytime.', 'https://user.vistafxsolutions.com/login', 'Go to Login');
    }

    // Verify now and clear token
    $uid = (int)$user['id'];
    $upd = $conn->prepare("
        UPDATE loginusers
        SET email_confirmed = 1, emailToken = NULL
        WHERE id = ?
        LIMIT 1
    ");
    $upd->bind_param("i", $uid);
    $upd->execute();

    // Success -> redirect to client login
    header("Location: https://user.vistafxsolutions.com/login");
    exit;

} catch (Throwable $e) {
    error_log("VERIFY_FATAL: " . $e->getMessage());
    render_card('Something Went Wrong', 'We could not complete your verification due to a server error. Please try again later or contact support.', 'https://user.vistafxsolutions.com/login', 'Go to Login');
}
