<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';
require_once 'includes/mailer.php';
requireLogin();
$uid = $_SESSION['user_id'];

// ── AJAX handlers ─────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    $action = $_POST['action'] ?? '';

    if ($action === 'delete_check_password') {
        $stmt = $pdo->prepare("SELECT password, email, name, auth_provider FROM users WHERE id=?");
        $stmt->execute([$uid]);
        $user = $stmt->fetch();

        if (!empty($user['auth_provider']) && in_array($user['auth_provider'], ['google','facebook']) && empty($_POST['password'])) {
            $otp     = generateOTP();
            $expires = date('Y-m-d H:i:s', time() + 600);
            $pdo->prepare("UPDATE users SET otp_code=?, otp_expires=? WHERE id=?")->execute([$otp, $expires, $uid]);
            $emailBody = '<p style="color:#94a3b8;">Hello <strong style="color:#f8fafc;">' . htmlspecialchars($user['name']) . '</strong>,</p><p style="color:#94a3b8;">We received a request to <strong style="color:#ef4444;">permanently delete</strong> your StudyTrack account.</p><p style="color:#94a3b8;">Your verification code is:</p><div style="text-align:center;margin:30px 0;"><span style="background:linear-gradient(135deg,#ef4444,#dc2626);color:#fff;font-size:36px;font-weight:700;padding:16px 32px;border-radius:12px;letter-spacing:8px;display:inline-block;">' . $otp . '</span></div><p style="color:#94a3b8;">This code expires in <strong style="color:#f8fafc;">10 minutes</strong>.</p><p style="color:#ef4444;font-weight:600;">⚠️ If you did NOT request this, please contact support immediately.</p>';
            $sent = sendEmail($user['email'], $user['name'], '⚠️ Account Deletion Verification - StudyTrack', $emailBody);
            if (!$sent) jsonResponse(['success' => false, 'message' => 'Could not send OTP email. Please try again.']);
            jsonResponse(['success' => true, 'google_user' => true, 'message' => 'OTP sent to ' . $user['email']]);
        }

        $password = $_POST['password'] ?? '';
        if (!$user || !password_verify($password, $user['password'])) {
            jsonResponse(['success' => false, 'message' => 'Incorrect password. Please try again.']);
        }

        $otp     = generateOTP();
        $expires = date('Y-m-d H:i:s', time() + 600);
        $pdo->prepare("UPDATE users SET otp_code=?, otp_expires=? WHERE id=?")->execute([$otp, $expires, $uid]);
        $emailBody = '<p style="color:#94a3b8;">Hello <strong style="color:#f8fafc;">' . htmlspecialchars($user['name']) . '</strong>,</p><p style="color:#94a3b8;">We received a request to <strong style="color:#ef4444;">permanently delete</strong> your StudyTrack account.</p><p style="color:#94a3b8;">Your verification code is:</p><div style="text-align:center;margin:30px 0;"><span style="background:linear-gradient(135deg,#ef4444,#dc2626);color:#fff;font-size:36px;font-weight:700;padding:16px 32px;border-radius:12px;letter-spacing:8px;display:inline-block;">' . $otp . '</span></div><p style="color:#94a3b8;">This code expires in <strong style="color:#f8fafc;">10 minutes</strong>.</p><p style="color:#ef4444;font-weight:600;">⚠️ If you did NOT request this, please change your password immediately.</p>';
        $sent = sendEmail($user['email'], $user['name'], '⚠️ Account Deletion Verification - StudyTrack', $emailBody);
        if (!$sent) jsonResponse(['success' => false, 'message' => 'Could not send OTP email. Please try again.']);
        jsonResponse(['success' => true, 'message' => 'OTP sent to ' . $user['email']]);
    }

    if ($action === 'delete_verify_otp') {
        $otp = trim($_POST['otp'] ?? '');
        $stmt = $pdo->prepare("SELECT otp_code, otp_expires FROM users WHERE id=?");
        $stmt->execute([$uid]);
        $row = $stmt->fetch();
        if (!$row || $row['otp_code'] !== $otp) jsonResponse(['success' => false, 'message' => 'Invalid OTP code. Please try again.']);
        if (strtotime($row['otp_expires']) < time()) jsonResponse(['success' => false, 'message' => 'OTP has expired. Please restart the process.']);
        try {
            $userStmt = $pdo->prepare("SELECT email, name, avatar FROM users WHERE id=?");
            $userStmt->execute([$uid]);
            $userToDelete = $userStmt->fetch();
            if ($userToDelete && $userToDelete['avatar'] && file_exists(__DIR__ . '/' . $userToDelete['avatar'])) @unlink(__DIR__ . '/' . $userToDelete['avatar']);
            $pdo->prepare("DELETE FROM users WHERE id=?")->execute([$uid]);
            if ($userToDelete && !empty($userToDelete['email'])) sendAccountDeleted($userToDelete['email'], $userToDelete['name']);
            session_destroy();
            jsonResponse(['success' => true, 'redirect' => SITE_URL . '/login']);
        } catch (Exception $e) {
            jsonResponse(['success' => false, 'message' => 'Deletion failed. Please contact support.']);
        }
    }

    jsonResponse(['success' => false, 'message' => 'Unknown action.']);
}

$userQ = $pdo->prepare("SELECT * FROM users WHERE id=?"); $userQ->execute([$uid]); $user = $userQ->fetch();
require_once 'includes/header.php';
renderHeader('Delete Account', 'profile');

$isSocial = !empty($user['auth_provider']) && in_array($user['auth_provider'], ['google','facebook']);
$provider  = $user['auth_provider'] ?? '';
$initial   = strtoupper($user['name'][0]);
?>

<style>
@import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700;800;900&family=Plus Jakarta Sans:wght@400;500;600;700&display=swap');

:root {
  --da-font: 'Outfit', sans-serif;
  --da-body: 'Plus Jakarta Sans', sans-serif;
}

.da-wrap {
  font-family: var(--da-body);
  max-width: 560px;
  margin: 0 auto;
  padding-bottom: 60px;
}

/* ── Back link ── */
.da-back {
  display: inline-flex;
  align-items: center;
  gap: 7px;
  color: var(--text-muted);
  font-size: 13px;
  font-weight: 600;
  text-decoration: none;
  margin-bottom: 28px;
  transition: color .18s;
}
.da-back:hover { color: var(--text-primary); }
.da-back svg { flex-shrink: 0; }

/* ── Warning banner ── */
.da-banner {
  background: rgba(239,68,68,.06);
  border: 1px solid rgba(239,68,68,.22);
  border-radius: 18px;
  padding: 28px 24px 24px;
  text-align: center;
  margin-bottom: 24px;
  animation: da-rise .45s ease both;
}
.da-banner-icon {
  width: 72px; height: 72px;
  border-radius: 50%;
  background: rgba(239,68,68,.12);
  border: 2px solid rgba(239,68,68,.28);
  display: flex; align-items: center; justify-content: center;
  margin: 0 auto 16px;
  font-size: 32px;
}
.da-banner-title {
  font-family: var(--da-font);
  font-size: 22px; font-weight: 800;
  color: var(--danger, #ef4444);
  letter-spacing: -.3px;
  margin-bottom: 8px;
}
.da-banner-desc {
  font-size: 14px;
  color: var(--text-muted);
  line-height: 1.7;
  max-width: 380px;
  margin: 0 auto;
}

/* ── Data list card ── */
.da-data-card {
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: 16px;
  padding: 20px 22px;
  margin-bottom: 20px;
  animation: da-rise .45s .06s ease both;
}
.da-data-title {
  font-size: 11px; font-weight: 700;
  color: var(--text-muted);
  text-transform: uppercase;
  letter-spacing: .7px;
  margin-bottom: 14px;
  display: flex; align-items: center; gap: 7px;
}
.da-data-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 6px 12px;
}
@media(max-width:480px){ .da-data-grid { grid-template-columns: 1fr; } }
.da-data-item {
  display: flex; align-items: center; gap: 8px;
  padding: 8px 12px;
  background: rgba(239,68,68,.04);
  border: 1px solid rgba(239,68,68,.1);
  border-radius: 10px;
  font-size: 12px;
  color: var(--text-muted);
}
.da-data-item span { font-size: 15px; }

/* ── Step cards ── */
.da-step-card {
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: 18px;
  padding: 24px;
  margin-bottom: 16px;
  animation: da-rise .45s .1s ease both;
}
.da-step-card.hidden { display: none; }

.da-step-hd {
  display: flex; align-items: center; gap: 12px;
  margin-bottom: 18px;
}
.da-step-num {
  width: 34px; height: 34px;
  border-radius: 50%;
  background: rgba(239,68,68,.1);
  border: 1.5px solid rgba(239,68,68,.3);
  display: flex; align-items: center; justify-content: center;
  font-family: var(--da-font);
  font-size: 14px; font-weight: 800;
  color: var(--danger, #ef4444);
  flex-shrink: 0;
}
.da-step-num.done {
  background: rgba(16,185,129,.1);
  border-color: rgba(16,185,129,.3);
  color: #10b981;
}
.da-step-label {
  font-family: var(--da-font);
  font-size: 15px; font-weight: 700;
  color: var(--text-primary);
}
.da-step-sub { font-size: 12px; color: var(--text-muted); margin-top: 2px; }

/* ── OTP boxes ── */
.da-otp-row {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin: 20px 0;
}
.da-otp-box {
  width: 48px; height: 56px;
  text-align: center;
  font-family: var(--da-font);
  font-size: 22px; font-weight: 800;
  color: var(--text-primary);
  background: var(--bg-secondary);
  border: 2px solid var(--border);
  border-radius: 12px;
  outline: none;
  transition: border-color .18s, box-shadow .18s;
  -moz-appearance: textfield;
}
.da-otp-box:focus {
  border-color: var(--danger, #ef4444);
  box-shadow: 0 0 0 3px rgba(239,68,68,.15);
}
.da-otp-box::-webkit-inner-spin-button,
.da-otp-box::-webkit-outer-spin-button { -webkit-appearance: none; }
@media(max-width:400px){
  .da-otp-box { width: 40px; height: 50px; font-size: 18px; }
  .da-otp-row { gap: 7px; }
}

/* ── Timer ── */
.da-timer-row {
  text-align: center;
  font-size: 12px;
  color: var(--text-muted);
  margin-bottom: 18px;
}
.da-timer { font-weight: 800; color: var(--accent); }

/* ── Confirm delete button ── */
.da-delete-btn {
  width: 100%;
  padding: 15px;
  background: rgba(239,68,68,.1);
  color: var(--danger, #ef4444);
  border: 1.5px solid rgba(239,68,68,.35);
  border-radius: 14px;
  font-family: var(--da-body);
  font-size: 15px; font-weight: 700;
  cursor: pointer;
  transition: background .18s, border-color .18s, transform .12s;
  display: flex; align-items: center; justify-content: center; gap: 8px;
  margin-bottom: 10px;
}
.da-delete-btn:hover {
  background: rgba(239,68,68,.18);
  border-color: rgba(239,68,68,.5);
  transform: translateY(-1px);
}
.da-delete-btn:disabled { opacity: .55; cursor: not-allowed; transform: none; }

/* ── Cancel link ── */
.da-cancel {
  display: block;
  text-align: center;
  font-size: 13px;
  color: var(--text-muted);
  font-weight: 600;
  cursor: pointer;
  padding: 10px;
  border-radius: 10px;
  transition: color .15s, background .15s;
  text-decoration: none;
}
.da-cancel:hover { color: var(--text-primary); background: var(--bg-secondary); }

/* ── Social badge ── */
.da-social-badge {
  display: flex; align-items: center; gap: 12px;
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 14px;
  padding: 14px 16px;
  margin-bottom: 18px;
}
.da-social-logo {
  width: 40px; height: 40px;
  border-radius: 10px;
  display: flex; align-items: center; justify-content: center;
  flex-shrink: 0;
}
.da-social-info-title { font-size: 13px; font-weight: 700; color: var(--text-primary); }
.da-social-info-sub { font-size: 12px; color: var(--text-muted); margin-top: 2px; }

/* ── Success screen ── */
.da-success {
  text-align: center;
  padding: 40px 20px;
  display: none;
}
.da-success-icon { font-size: 56px; margin-bottom: 16px; }
.da-success-title {
  font-family: var(--da-font);
  font-size: 22px; font-weight: 800;
  color: var(--text-primary);
  margin-bottom: 8px;
}
.da-success-sub { font-size: 14px; color: var(--text-muted); }

/* ── Alert overrides ── */
.da-alert {
  padding: 11px 15px;
  border-radius: 12px;
  font-size: 13px;
  font-weight: 600;
  margin-bottom: 14px;
  display: none;
}
.da-alert.error {
  background: rgba(239,68,68,.08);
  border: 1px solid rgba(239,68,68,.25);
  color: #fca5a5;
}
.da-alert.success {
  background: rgba(16,185,129,.08);
  border: 1px solid rgba(16,185,129,.25);
  color: #6ee7b7;
}

/* ── Animations ── */
@keyframes da-rise {
  from { opacity:0; transform:translateY(14px); }
  to   { opacity:1; transform:translateY(0); }
}
@keyframes da-shake {
  0%,100%{ transform:translateX(0) }
  20%    { transform:translateX(-8px) }
  40%    { transform:translateX(8px) }
  60%    { transform:translateX(-6px) }
  80%    { transform:translateX(6px) }
}

/* ── Progress steps indicator ── */
.da-progress {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0;
  margin-bottom: 28px;
  animation: da-rise .4s ease both;
}
.da-prog-step {
  display: flex; flex-direction: column; align-items: center;
  gap: 6px;
  flex: 1;
  max-width: 120px;
}
.da-prog-dot {
  width: 32px; height: 32px;
  border-radius: 50%;
  background: var(--bg-secondary);
  border: 2px solid var(--border);
  display: flex; align-items: center; justify-content: center;
  font-size: 13px; font-weight: 700;
  color: var(--text-muted);
  transition: background .3s, border-color .3s, color .3s;
  position: relative;
  z-index: 1;
}
.da-prog-dot.active {
  background: rgba(239,68,68,.15);
  border-color: var(--danger, #ef4444);
  color: var(--danger, #ef4444);
}
.da-prog-dot.done {
  background: rgba(16,185,129,.15);
  border-color: #10b981;
  color: #10b981;
}
.da-prog-label {
  font-size: 10px; font-weight: 700;
  color: var(--text-muted);
  text-transform: uppercase;
  letter-spacing: .5px;
  text-align: center;
  white-space: nowrap;
}
.da-prog-label.active { color: var(--danger, #ef4444); }
.da-prog-label.done { color: #10b981; }
.da-prog-line {
  flex: 1;
  height: 2px;
  background: var(--border);
  margin: 0 -1px;
  margin-bottom: 22px;
  transition: background .3s;
}
.da-prog-line.done { background: #10b981; }
</style>

<div class="da-wrap">

  <!-- Back button -->
  <a href="<?= SITE_URL ?>/profile" class="da-back">
    <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24">
      <path d="M19 12H5M12 5l-7 7 7 7"/>
    </svg>
    Back to Profile
  </a>

  <!-- Main content (shown while not deleted) -->
  <div id="daMainContent">

    <!-- Warning Banner -->
    <div class="da-banner">
      <div class="da-banner-icon">🗑️</div>
      <div class="da-banner-title">Delete Your Account</div>
      <div class="da-banner-desc">
        This will <strong style="color:var(--danger)">permanently remove</strong> all your data from StudyTrack.
        This action <strong style="color:var(--text-primary)">cannot be undone</strong>.
      </div>
    </div>

    <!-- Progress Steps -->
    <div class="da-progress" id="daProgress">
      <div class="da-prog-step">
        <div class="da-prog-dot active" id="prog1">1</div>
        <div class="da-prog-label active" id="progL1"><?= $isSocial ? 'Confirm' : 'Password' ?></div>
      </div>
      <div class="da-prog-line" id="progLine1"></div>
      <div class="da-prog-step">
        <div class="da-prog-dot" id="prog2">2</div>
        <div class="da-prog-label" id="progL2">Verify OTP</div>
      </div>
      <div class="da-prog-line" id="progLine2"></div>
      <div class="da-prog-step">
        <div class="da-prog-dot" id="prog3">3</div>
        <div class="da-prog-label" id="progL3">Deleted</div>
      </div>
    </div>

    <!-- What will be deleted -->
    <div class="da-data-card">
      <div class="da-data-title">
        <svg width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
        Permanently deleted
      </div>
      <div class="da-data-grid">
        <?php foreach(['📖 Study sessions','📊 Marks & results','📝 Notes','🎯 Goals','✅ Tasks','🏆 Achievements','🔔 Reminders','📅 Timetable'] as $item): ?>
          <div class="da-data-item"><span><?= mb_substr($item, 0, 2) ?></span><?= htmlspecialchars(mb_substr($item, 2)) ?></div>
        <?php endforeach; ?>
      </div>
    </div>

    <!-- ─── STEP 1 ─────────────────────────────────────────── -->
    <div class="da-step-card" id="daStep1">
      <div class="da-step-hd">
        <div class="da-step-num" id="step1Num">1</div>
        <div>
          <div class="da-step-label">
            <?= $isSocial ? 'Confirm Your Identity' : 'Enter Your Password' ?>
          </div>
          <div class="da-step-sub">
            <?= $isSocial
              ? 'We\'ll send a one-time code to your email to verify your identity.'
              : 'Enter your current password to proceed with account deletion.' ?>
          </div>
        </div>
      </div>

      <div class="da-alert error" id="step1Alert"></div>

      <?php if ($isSocial): ?>
        <!-- Social user: show provider info, no password needed -->
        <div class="da-social-badge">
          <div class="da-social-logo" style="background:<?= $provider==='facebook'?'rgba(24,119,242,.1)':'rgba(234,67,53,.1)' ?>">
            <?php if ($provider === 'facebook'): ?>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="#1877f2"><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>
            <?php else: ?>
              <svg width="22" height="22" viewBox="0 0 48 48"><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>
            <?php endif; ?>
          </div>
          <div>
            <div class="da-social-info-title">Signed in via <?= $provider === 'facebook' ? 'Facebook' : 'Google' ?></div>
            <div class="da-social-info-sub"><?= htmlspecialchars($user['email']) ?></div>
          </div>
        </div>
        <p style="font-size:13px;color:var(--text-muted);line-height:1.7;margin-bottom:18px">
          Since you signed in with <?= $provider === 'facebook' ? 'Facebook' : 'Google' ?>, we'll send a verification code to your email address to confirm this is really you.
        </p>
        <button class="da-delete-btn" id="step1SocialBtn" onclick="socialStep1Submit()">
          📧 Send Verification Code
        </button>

      <?php else: ?>
        <!-- Password user -->
        <div class="form-group" style="margin-bottom:16px">
          <label style="display:block;font-size:12px;font-weight:700;color:var(--text-muted);text-transform:uppercase;letter-spacing:.7px;margin-bottom:7px">Current Password</label>
          <div class="input-icon">
            <span class="icon">🔒</span>
            <input type="password" id="daDeletePassword" class="form-control"
                   placeholder="Enter your password"
                   onkeydown="if(event.key==='Enter') step1Submit()">
            <button type="button" class="toggle-password">👁️</button>
          </div>
        </div>
        <button class="da-delete-btn" id="step1Btn" onclick="step1Submit()">
          Continue → Send Verification Code
        </button>

      <?php endif; ?>

      <a href="<?= SITE_URL ?>/profile" class="da-cancel">Cancel — Keep My Account</a>
    </div>

    <!-- ─── STEP 2 ─────────────────────────────────────────── -->
    <div class="da-step-card hidden" id="daStep2">
      <div class="da-step-hd">
        <div class="da-step-num done" id="step2NumDone">✓</div>
        <div>
          <div class="da-step-label">Verify Your Identity</div>
          <div class="da-step-sub" id="daOtpSubtitle">Enter the 6-digit code sent to your email</div>
        </div>
      </div>

      <div class="da-alert error" id="step2Alert"></div>
      <div class="da-alert success" id="step2SuccessAlert"></div>

      <div class="da-otp-row" id="daOtpRow">
        <input type="text" inputmode="numeric" maxlength="1" class="da-otp-box" id="daOtp0" oninput="daOtpNext(this,1)" onkeydown="daOtpKey(event,this,null,document.getElementById('daOtp1'))">
        <input type="text" inputmode="numeric" maxlength="1" class="da-otp-box" id="daOtp1" oninput="daOtpNext(this,2)" onkeydown="daOtpKey(event,this,document.getElementById('daOtp0'),document.getElementById('daOtp2'))">
        <input type="text" inputmode="numeric" maxlength="1" class="da-otp-box" id="daOtp2" oninput="daOtpNext(this,3)" onkeydown="daOtpKey(event,this,document.getElementById('daOtp1'),document.getElementById('daOtp3'))">
        <input type="text" inputmode="numeric" maxlength="1" class="da-otp-box" id="daOtp3" oninput="daOtpNext(this,4)" onkeydown="daOtpKey(event,this,document.getElementById('daOtp2'),document.getElementById('daOtp4'))">
        <input type="text" inputmode="numeric" maxlength="1" class="da-otp-box" id="daOtp4" oninput="daOtpNext(this,5)" onkeydown="daOtpKey(event,this,document.getElementById('daOtp3'),document.getElementById('daOtp5'))">
        <input type="text" inputmode="numeric" maxlength="1" class="da-otp-box" id="daOtp5" oninput="daOtpDone()"       onkeydown="daOtpKey(event,this,document.getElementById('daOtp4'),null)">
      </div>

      <div class="da-timer-row">
        Code expires in <span class="da-timer" id="daOtpTimer">10:00</span>
        &nbsp;·&nbsp;
        <button onclick="daResend()" id="daResendBtn"
          style="background:none;border:none;color:var(--accent);cursor:pointer;font-size:12px;font-weight:600;padding:0">
          Resend
        </button>
      </div>

      <button class="da-delete-btn" id="step2Btn" onclick="step2Submit()">
        🗑️ Permanently Delete My Account
      </button>
      <a href="<?= SITE_URL ?>/profile" class="da-cancel">Cancel — Keep My Account</a>
    </div>

  </div><!-- /#daMainContent -->

  <!-- ─── SUCCESS SCREEN ─────────────────────────────────── -->
  <div class="da-success" id="daSuccess">
    <div class="da-success-icon">👋</div>
    <div class="da-success-title">Account Deleted</div>
    <div class="da-success-sub">Your account and all data have been permanently removed. Redirecting…</div>
  </div>

</div>

<script>
// ── Helpers ────────────────────────────────────────────────────────────
function showStep1Alert(msg, type='error') {
  var el = document.getElementById('step1Alert');
  el.className = 'da-alert ' + type;
  el.innerHTML = (type==='error' ? '⚠️ ' : '✅ ') + msg;
  el.style.display = 'block';
}
function showStep2Alert(msg, type='error') {
  var el = document.getElementById('step2Alert');
  el.className = 'da-alert ' + type;
  el.innerHTML = (type==='error' ? '⚠️ ' : '✅ ') + msg;
  el.style.display = 'block';
  document.getElementById('step2SuccessAlert').style.display = 'none';
}
function clearAlerts() {
  ['step1Alert','step2Alert','step2SuccessAlert'].forEach(id => {
    var el = document.getElementById(id);
    if (el) el.style.display = 'none';
  });
}

// ── Progress bar ───────────────────────────────────────────────────────
function setProgress(step) {
  // step: 1 = on step1, 2 = on step2, 3 = done
  var dots   = [document.getElementById('prog1'), document.getElementById('prog2'), document.getElementById('prog3')];
  var labels = [document.getElementById('progL1'), document.getElementById('progL2'), document.getElementById('progL3')];
  var lines  = [document.getElementById('progLine1'), document.getElementById('progLine2')];
  var icons  = ['<?= $isSocial ? "✓" : "1" ?>', '2', '3'];

  dots.forEach((d, i) => {
    d.className = 'da-prog-dot';
    labels[i].className = 'da-prog-label';
    if (i + 1 < step) {
      d.className += ' done';
      labels[i].className += ' done';
      d.textContent = '✓';
    } else if (i + 1 === step) {
      d.className += ' active';
      labels[i].className += ' active';
      d.textContent = i + 1;
    } else {
      d.textContent = i + 1;
    }
  });
  lines.forEach((l, i) => {
    l.className = 'da-prog-line' + (i + 1 < step ? ' done' : '');
  });
}

// ── Step 1: Password user ──────────────────────────────────────────────
async function step1Submit() {
  clearAlerts();
  var pw = document.getElementById('daDeletePassword')?.value?.trim() ?? '';
  if (!pw) { showStep1Alert('Please enter your password.'); return; }
  var btn = document.getElementById('step1Btn');
  btn.disabled = true;
  btn.innerHTML = '<span class="spinner"></span> Verifying…';
  try {
    var fd = new FormData();
    fd.append('action', 'delete_check_password');
    fd.append('password', pw);
    var res  = await fetch(window.location.href, { method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'} });
    var data = await res.json();
    if (data.success) {
      goToStep2(data.message);
    } else {
      showStep1Alert(data.message);
    }
  } catch(e) { showStep1Alert('Connection error. Please try again.'); }
  btn.disabled = false;
  btn.innerHTML = 'Continue → Send Verification Code';
}

// ── Step 1: Social user ────────────────────────────────────────────────
async function socialStep1Submit() {
  clearAlerts();
  var btn = document.getElementById('step1SocialBtn');
  btn.disabled = true;
  btn.innerHTML = '<span class="spinner"></span> Sending code…';
  try {
    var fd = new FormData();
    fd.append('action', 'delete_check_password');
    var res  = await fetch(window.location.href, { method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'} });
    var data = await res.json();
    if (data.success) {
      goToStep2(data.message);
    } else {
      showStep1Alert(data.message);
    }
  } catch(e) { showStep1Alert('Connection error. Please try again.'); }
  btn.disabled = false;
  btn.innerHTML = '📧 Send Verification Code';
}

// ── Transition to Step 2 ───────────────────────────────────────────────
function goToStep2(sentMsg) {
  document.getElementById('daStep1').classList.add('hidden');
  document.getElementById('daStep2').classList.remove('hidden');
  setProgress(2);
  document.getElementById('daOtpSubtitle').textContent = sentMsg || 'Enter the 6-digit code sent to your email';
  startOtpTimer();
  clearOtpBoxes();
  setTimeout(() => document.getElementById('daOtp0').focus(), 100);
}

// ── Step 2: OTP submit ─────────────────────────────────────────────────
async function step2Submit() {
  clearAlerts();
  var otp = '';
  for (var i = 0; i < 6; i++) otp += (document.getElementById('daOtp' + i).value || '');
  if (otp.length < 6) { showStep2Alert('Please enter the full 6-digit code.'); return; }
  var btn = document.getElementById('step2Btn');
  btn.disabled = true;
  btn.innerHTML = '<span class="spinner"></span> Deleting account…';
  try {
    var fd = new FormData();
    fd.append('action', 'delete_verify_otp');
    fd.append('otp', otp);
    var res  = await fetch(window.location.href, { method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'} });
    var data = await res.json();
    if (data.success) {
      clearInterval(_otpTimerInterval);
      setProgress(3);
      document.getElementById('daMainContent').style.display = 'none';
      document.getElementById('daSuccess').style.display = 'block';
      setTimeout(() => { window.location.href = data.redirect; }, 2800);
    } else {
      showStep2Alert(data.message);
      document.getElementById('daOtpRow').style.animation = 'none';
      setTimeout(() => { document.getElementById('daOtpRow').style.animation = 'da-shake .4s ease'; }, 10);
      clearOtpBoxes();
      document.getElementById('daOtp0').focus();
      btn.disabled = false;
      btn.innerHTML = '🗑️ Permanently Delete My Account';
    }
  } catch(e) {
    showStep2Alert('Connection error. Please try again.');
    btn.disabled = false;
    btn.innerHTML = '🗑️ Permanently Delete My Account';
  }
}

// ── Resend ─────────────────────────────────────────────────────────────
async function daResend() {
  var btn = document.getElementById('daResendBtn');
  btn.textContent = 'Sending…'; btn.disabled = true;
  clearOtpBoxes(); clearAlerts();
  // Go back to step 1 visually
  document.getElementById('daStep2').classList.add('hidden');
  document.getElementById('daStep1').classList.remove('hidden');
  setProgress(1);
  btn.textContent = 'Resend'; btn.disabled = false;
  clearInterval(_otpTimerInterval);
}

// ── OTP helpers ────────────────────────────────────────────────────────
function daOtpNext(el, nextIdx) {
  el.value = el.value.replace(/\D/g, '');
  if (el.value && nextIdx < 6) document.getElementById('daOtp' + nextIdx).focus();
}
function daOtpDone() {
  document.getElementById('daOtp5').value = document.getElementById('daOtp5').value.replace(/\D/g, '');
}
function daOtpKey(e, el, prev, next) {
  if (e.key === 'Backspace' && !el.value && prev) prev.focus();
  if (e.key === 'ArrowLeft'  && prev) { e.preventDefault(); prev.focus(); }
  if (e.key === 'ArrowRight' && next) { e.preventDefault(); next.focus(); }
  if (e.key === 'Enter') step2Submit();
}
function clearOtpBoxes() {
  for (var i = 0; i < 6; i++) {
    var b = document.getElementById('daOtp' + i);
    if (b) b.value = '';
  }
}

// ── Paste on OTP ───────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', function() {
  var b = document.getElementById('daOtp0');
  if (b) b.addEventListener('paste', function(e) {
    e.preventDefault();
    var text = (e.clipboardData || window.clipboardData).getData('text').replace(/\D/g, '').slice(0, 6);
    for (var i = 0; i < text.length; i++) {
      var box = document.getElementById('daOtp' + i);
      if (box) box.value = text[i];
    }
    var last = Math.min(text.length, 5);
    document.getElementById('daOtp' + last).focus();
  });
});

// ── Timer ──────────────────────────────────────────────────────────────
var _otpTimerInterval = null;
function startOtpTimer() {
  clearInterval(_otpTimerInterval);
  var seconds = 600;
  function tick() {
    var m = Math.floor(seconds / 60), s = seconds % 60;
    var el = document.getElementById('daOtpTimer');
    if (el) {
      el.textContent = String(m).padStart(2, '0') + ':' + String(s).padStart(2, '0');
      el.style.color = seconds <= 60 ? 'var(--danger)' : 'var(--accent)';
    }
    if (seconds <= 0) {
      clearInterval(_otpTimerInterval);
      if (el) { el.textContent = 'Expired'; el.style.color = 'var(--danger)'; }
    }
    seconds--;
  }
  tick();
  _otpTimerInterval = setInterval(tick, 1000);
}

// Init progress
setProgress(1);
</script>

<?php require_once 'includes/footer.php'; renderFooter(); ?>
