<?php
/**
 * StudyTrack — Google Sign-Up: Terms & Privacy Agreement
 * URL: /google-terms.php
 *
 * Shown ONLY to first-time Google sign-up users.
 * After agreeing, account is created and user is logged in.
 */
require_once 'includes/config.php';
require_once 'includes/mailer.php';

// Already logged in → dashboard
if (isLoggedIn()) {
    header('Location: ' . SITE_URL . '/dashboard.php');
    exit;
}

// No pending Google data → back to login
if (empty($_SESSION['google_pending'])) {
    header('Location: ' . SITE_URL . '/login.php');
    exit;
}

$pending = $_SESSION['google_pending'];

// ── Handle form submission (agreed to terms) ─────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    $agreed = $_POST['agreed'] ?? '';
    if ($agreed !== '1') {
        jsonResponse(['success' => false, 'message' => 'Please agree to the Terms & Privacy Policy to continue.']);
    }

    try {
        // Create the account now
        $pdo->prepare(
            "INSERT INTO users (name, email, google_id, google_avatar, auth_provider, is_verified, password)
             VALUES (?, ?, ?, ?, 'google', 1, ?)"
        )->execute([
            $pending['name'],
            $pending['email'],
            $pending['google_id'],
            $pending['google_avatar'],
            password_hash(bin2hex(random_bytes(32)), PASSWORD_BCRYPT),
        ]);
        $newId = $pdo->lastInsertId();

        $stmt = $pdo->prepare("SELECT * FROM users WHERE id=?");
        $stmt->execute([$newId]);
        $user = $stmt->fetch();

        // Clear pending data
        unset($_SESSION['google_pending']);

        // Log in
        session_regenerate_id(true);
        $_SESSION['user_id']    = $user['id'];
        $_SESSION['user_name']  = $user['name'];
        $_SESSION['user_email'] = $user['email'];
        $_SESSION['login_time'] = time();
        createDbSession($user['id']);

        // ── Welcome email for new Google signup ─────────────────────
        sendGoogleSignupWelcome($user['email'], $user['name']);
        // ─────────────────────────────────────────────────────────────

        jsonResponse(['success' => true, 'redirect' => SITE_URL . '/welcome.php']);

    } catch (PDOException $e) {
        // Duplicate email (race condition)
        if ($e->getCode() === '23000') {
            jsonResponse(['success' => false, 'message' => 'An account with this email already exists. Please sign in normally.']);
        }
        error_log('Google terms account create error: ' . $e->getMessage());
        jsonResponse(['success' => false, 'message' => 'Account creation failed. Please try again.']);
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Almost There — <?= SITE_NAME ?></title>
<link rel="stylesheet" href="<?= SITE_URL ?>/assets/css/style.css">
<link rel="icon" type="image/png" href="https://studytrack.edurx.icu/studytrack/images/studytrack.png">
<script>(function(){var t=localStorage.getItem('stTheme')||'dark';document.documentElement.setAttribute('data-theme',t);})();</script>
<style>
  .terms-scroll {
    max-height: 160px;
    overflow-y: auto;
    background: var(--bg-primary);
    border: 1px solid var(--border);
    border-radius: 10px;
    padding: 14px 16px;
    font-size: 12.5px;
    color: var(--text-secondary);
    line-height: 1.7;
    margin-bottom: 16px;
    scrollbar-width: thin;
  }
  .terms-scroll::-webkit-scrollbar { width: 4px; }
  .terms-scroll::-webkit-scrollbar-track { background: transparent; }
  .terms-scroll::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }

  .check-row {
    display: flex;
    align-items: flex-start;
    gap: 10px;
    padding: 12px 14px;
    border-radius: 10px;
    border: 1.5px solid var(--border);
    background: var(--bg-secondary);
    cursor: pointer;
    transition: border-color .2s, background .2s;
    margin-bottom: 10px;
    user-select: none;
  }
  .check-row:hover { border-color: var(--accent); }
  .check-row.checked { border-color: var(--accent); background: rgba(99,102,241,0.06); }
  .check-row input[type=checkbox] {
    width: 17px; height: 17px; margin-top: 1px;
    accent-color: var(--accent); flex-shrink: 0; cursor: pointer;
  }
  .check-row span { font-size: 13px; color: var(--text-secondary); line-height: 1.5; }
  .check-row span a { color: var(--accent); font-weight: 600; text-decoration: none; }
  .check-row span a:hover { text-decoration: underline; }

  .google-badge {
    display: flex; align-items: center; gap: 8px;
    background: var(--bg-secondary);
    border: 1px solid var(--border);
    border-radius: 10px;
    padding: 10px 14px;
    margin-bottom: 20px;
  }
  .google-badge img { width: 22px; height: 22px; border-radius: 50%; }
  .google-badge .gb-name { font-size: 13px; font-weight: 600; color: var(--text-primary); }
  .google-badge .gb-email { font-size: 11px; color: var(--text-muted); }
</style>
</head>
<body>
<div class="auth-wrapper">
<div class="auth-card animate-in" id="termsCard">

  <div class="auth-logo">
    <div class="logo-icon">📚</div>
    <h1><?= SITE_NAME ?></h1>
    <p>One last step to get started!</p>
  </div>

  <!-- Google account preview -->
  <div class="google-badge">
    <?php if (!empty($pending['google_avatar'])): ?>
    <img src="<?= htmlspecialchars($pending['google_avatar']) ?>" alt="avatar">
    <?php else: ?>
    <div style="width:22px;height:22px;border-radius:50%;background:var(--gradient);display:flex;align-items:center;justify-content:center;font-size:11px;color:#fff;font-weight:700">
      <?= strtoupper($pending['name'][0]) ?>
    </div>
    <?php endif; ?>
    <div>
      <div class="gb-name"><?= htmlspecialchars($pending['name']) ?></div>
      <div class="gb-email"><?= htmlspecialchars($pending['email']) ?></div>
    </div>
    <div style="margin-left:auto">
      <svg width="16" height="16" viewBox="0 0 48 48" style="display:block">
        <path fill="#EA4335" d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z"/>
        <path fill="#4285F4" d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z"/>
        <path fill="#FBBC05" d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z"/>
        <path fill="#34A853" d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.18 1.48-4.97 2.31-8.16 2.31-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z"/>
      </svg>
    </div>
  </div>

  <div id="msgBox" style="display:none" class="alert"></div>

  <p style="font-size:13px;color:var(--text-muted);margin-bottom:14px;line-height:1.6">
    Before creating your StudyTrack account, please review and accept our Terms &amp; Privacy Policy.
  </p>

  <!-- Terms scroll preview -->
  <div class="terms-scroll">
    <strong style="color:var(--text-primary);font-size:13px">Terms of Service — Summary</strong><br><br>
    By using StudyTrack you agree to use the platform for educational purposes only. You are responsible for maintaining the security of your account. We reserve the right to suspend accounts that violate our policies. All study data you enter is yours and can be deleted at any time.<br><br>
    <strong style="color:var(--text-primary);font-size:13px">Privacy Policy — Summary</strong><br><br>
    We collect your name, email, and study data to provide the StudyTrack service. We do not sell your personal data to third parties. Your Google profile picture is used only as your avatar. You can delete your account and all associated data at any time from your Profile page.
  </div>

  <!-- Checkbox 1: Terms -->
  <label class="check-row" id="row1" onclick="toggleCheck('chk1','row1')">
    <input type="checkbox" id="chk1" onchange="checkBoth()">
    <span>I have read and agree to the
      <a href="<?= SITE_URL ?>/terms" target="_blank" onclick="event.stopPropagation()">Terms &amp; Conditions</a>
    </span>
  </label>

  <!-- Checkbox 2: Privacy -->
  <label class="check-row" id="row2" onclick="toggleCheck('chk2','row2')">
    <input type="checkbox" id="chk2" onchange="checkBoth()">
    <span>I have read and agree to the
      <a href="<?= SITE_URL ?>/privacy" target="_blank" onclick="event.stopPropagation()">Privacy Policy</a>
    </span>
  </label>

  <button id="continueBtn" class="btn btn-primary btn-full" onclick="submitTerms()" disabled
    style="margin-top:8px;opacity:0.5;cursor:not-allowed;transition:opacity .2s">
    Create Account &amp; Continue →
  </button>

  <p style="text-align:center;margin-top:16px;font-size:13px;color:var(--text-muted)">
    Not you?
    <a href="<?= SITE_URL ?>/login.php" style="color:var(--accent);font-weight:600">Use a different account</a>
  </p>

</div>
</div>

<script src="<?= SITE_URL ?>/assets/js/app.js"></script>
<script>
(function () {
  'use strict';

  const msgBox = document.getElementById('msgBox');

  function showMsg(msg, type) {
    msgBox.className = 'alert alert-' + type;
    msgBox.innerHTML = (type === 'error' ? '⚠️ ' : '✅ ') + msg;
    msgBox.style.display = 'flex';
  }

  window.toggleCheck = function(id, rowId) {
    // Clicking the label toggles the checkbox — just update row style
    setTimeout(function() {
      const chk = document.getElementById(id);
      const row = document.getElementById(rowId);
      row.classList.toggle('checked', chk.checked);
      checkBoth();
    }, 0);
  };

  window.checkBoth = function() {
    const c1 = document.getElementById('chk1').checked;
    const c2 = document.getElementById('chk2').checked;
    const btn = document.getElementById('continueBtn');
    if (c1 && c2) {
      btn.disabled = false;
      btn.style.opacity = '1';
      btn.style.cursor  = 'pointer';
    } else {
      btn.disabled = true;
      btn.style.opacity = '0.5';
      btn.style.cursor  = 'not-allowed';
    }
  };

  window.submitTerms = async function() {
    const c1 = document.getElementById('chk1').checked;
    const c2 = document.getElementById('chk2').checked;
    if (!c1 || !c2) {
      showMsg('Please agree to both the Terms and Privacy Policy.', 'error');
      return;
    }

    const btn = document.getElementById('continueBtn');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner"></span>&nbsp; Creating account...';

    try {
      const fd = new FormData();
      fd.append('agreed', '1');
      const res  = await fetch(window.location.href, {
        method: 'POST', body: fd,
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
      });
      const data = await res.json();

      if (data.success) {
        showMsg('Account created! Redirecting...', 'success');
        btn.innerHTML = '✓';
        setTimeout(() => { window.location.href = data.redirect; }, 900);
      } else {
        showMsg(data.message || 'Something went wrong. Please try again.', 'error');
        btn.disabled = false;
        btn.innerHTML = 'Create Account &amp; Continue →';
      }
    } catch (err) {
      showMsg('Connection error. Please try again.', 'error');
      btn.disabled = false;
      btn.innerHTML = 'Create Account &amp; Continue →';
    }
  };
})();
</script>
</body>
</html>
