<?php
/**
 * StudyTrack — Facebook Sign-Up: Terms & Privacy Agreement
 * URL: /fb-terms.php
 */
require_once 'includes/config.php';
require_once 'includes/mailer.php';

if (isLoggedIn()) {
    header('Location: ' . SITE_URL . '/dashboard.php');
    exit;
}
if (empty($_SESSION['fb_pending'])) {
    header('Location: ' . SITE_URL . '/login.php');
    exit;
}

$pending = $_SESSION['fb_pending'];

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

    $finalEmail = $pending['email'];

    // If user needs to provide email, validate it
    if (!empty($pending['needs_email'])) {
        $inputEmail = strtolower(trim(filter_var($_POST['email'] ?? '', FILTER_SANITIZE_EMAIL)));
        if (!$inputEmail || !filter_var($inputEmail, FILTER_VALIDATE_EMAIL)) {
            jsonResponse(['success' => false, 'message' => 'Please enter a valid email address.']);
        }
        // Check if email already taken
        $chk = $pdo->prepare("SELECT id FROM users WHERE email = ?");
        $chk->execute([$inputEmail]);
        if ($chk->fetch()) {
            jsonResponse(['success' => false, 'message' => 'This email is already registered. Please use a different email or sign in normally.']);
        }
        $finalEmail = $inputEmail;
        // Update pending session so name in badge stays correct
        $_SESSION['fb_pending']['email'] = $finalEmail;
    }

    try {
        $pdo->prepare(
            "INSERT INTO users (name, email, facebook_id, google_avatar, auth_provider, is_verified, password)
             VALUES (?, ?, ?, ?, 'facebook', 1, ?)"
        )->execute([
            $pending['name'],
            $finalEmail,
            $pending['facebook_id'],
            $pending['fb_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();

        unset($_SESSION['fb_pending']);

        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 — new Facebook account
        sendFacebookSignupWelcome($user['email'], $user['name']);
        jsonResponse(['success' => true, 'redirect' => SITE_URL . '/welcome.php']);

    } catch (PDOException $e) {
        if ($e->getCode() === '23000') {
            jsonResponse(['success' => false, 'message' => 'This email is already registered. Please use a different email or sign in normally.']);
        }
        error_log('Facebook 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-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: #1877f2; }
  .check-row.checked { border-color: #1877f2; background: rgba(24,119,242,0.06); }
  .check-row input[type=checkbox] {
    width: 17px; height: 17px; margin-top: 1px;
    accent-color: #1877f2; flex-shrink: 0; cursor: pointer;
  }
  .check-row span { font-size: 13px; color: var(--text-secondary); line-height: 1.5; }
  .check-row span a { color: #1877f2; font-weight: 600; text-decoration: none; }
  .check-row span a:hover { text-decoration: underline; }
  .fb-badge {
    display: flex; align-items: center; gap: 10px;
    background: var(--bg-secondary); border: 1px solid var(--border);
    border-radius: 10px; padding: 10px 14px; margin-bottom: 20px;
  }
  .fb-badge img { width: 40px; height: 40px; border-radius: 50%; object-fit: cover; }
  .fb-badge .fb-name { font-size: 13px; font-weight: 600; color: var(--text-primary); }
  .fb-badge .fb-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>

  <!-- Facebook account preview -->
  <div class="fb-badge">
    <?php if (!empty($pending['fb_avatar'])): ?>
    <img src="<?= htmlspecialchars($pending['fb_avatar']) ?>" alt="avatar">
    <?php else: ?>
    <div style="width:40px;height:40px;border-radius:50%;background:#1877f2;display:flex;align-items:center;justify-content:center;font-size:18px;color:#fff;font-weight:700;flex-shrink:0">
      <?= strtoupper($pending['name'][0]) ?>
    </div>
    <?php endif; ?>
    <div style="flex:1;min-width:0">
      <div class="fb-name"><?= htmlspecialchars($pending['name']) ?></div>
      <div class="fb-email"><?= htmlspecialchars(str_contains($pending['email'], '@facebook.placeholder') ? 'Facebook account' : $pending['email']) ?></div>
    </div>
    <!-- Facebook logo -->
    <svg width="22" height="22" viewBox="0 0 24 24" fill="#1877f2" style="flex-shrink:0">
      <path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/>
    </svg>
  </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>

  <?php if (!empty($pending['needs_email'])): ?>
  <!-- Email required — Facebook didn't provide it -->
  <div style="background:rgba(251,191,36,0.08);border:1px solid rgba(251,191,36,0.25);border-radius:12px;padding:12px 14px;margin-bottom:16px;display:flex;align-items:flex-start;gap:10px">
    <span style="font-size:16px;flex-shrink:0;margin-top:1px">ℹ️</span>
    <div style="font-size:12.5px;color:var(--text-secondary);line-height:1.6">
      Facebook didn't share your email address (due to your privacy settings). Please enter your email below to continue.
    </div>
  </div>
  <div class="form-group" style="margin-bottom:16px">
    <label class="form-label" style="font-size:13px;font-weight:600">Your Email Address <span style="color:var(--danger)">*</span></label>
    <div class="input-icon">
      <span class="icon">✉️</span>
      <input type="email" id="userEmailInput" class="form-control" placeholder="you@email.com" required
        oninput="document.getElementById('msgBox').style.display='none'">
    </div>
  </div>
  <?php endif; ?>

  <!-- 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 Facebook 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-full" onclick="submitTerms()" disabled
    style="margin-top:8px;opacity:0.5;cursor:not-allowed;transition:opacity .2s;background:#1877f2;border-color:#1877f2;color:#fff">
    <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="vertical-align:middle;margin-right:6px">
      <path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/>
    </svg>
    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:#1877f2;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) {
    setTimeout(function() {
      const chk = document.getElementById(id);
      document.getElementById(rowId).classList.toggle('checked', chk.checked);
      checkBoth();
    }, 0);
  };

  window.checkBoth = function() {
    const ok = document.getElementById('chk1').checked && document.getElementById('chk2').checked;
    const btn = document.getElementById('continueBtn');
    btn.disabled    = !ok;
    btn.style.opacity = ok ? '1' : '0.5';
    btn.style.cursor  = ok ? 'pointer' : 'not-allowed';
  };

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

    // Validate email if field is present
    const emailInput = document.getElementById('userEmailInput');
    if (emailInput) {
      const emailVal = emailInput.value.trim();
      if (!emailVal) {
        showMsg('Please enter your email address.', 'error');
        emailInput.focus(); return;
      }
      const emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRe.test(emailVal)) {
        showMsg('Please enter a valid email address.', 'error');
        emailInput.focus(); 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');
      if (emailInput) fd.append('email', emailInput.value.trim());
      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.', 'error');
        btn.disabled = false;
        btn.innerHTML = 'Create Account &amp; Continue →';
      }
    } catch (e) {
      showMsg('Connection error. Please try again.', 'error');
      btn.disabled = false;
      btn.innerHTML = 'Create Account &amp; Continue →';
    }
  };
})();
</script>
</body>
</html>