<?php
session_start();
$page_title = 'Close Account';
$active_nav = 'profile';
include("includes/header.php");
$uid = (int)$_SESSION['user_id'];

$error = "";
$done  = false;

// Has this user already requested closure? (defensive — column may not exist)
$already = false;
if ($c = $conn->prepare("SELECT closure_requested FROM users WHERE id=?")) {
    $c->bind_param("i", $uid); $c->execute();
    $already = (bool)($c->get_result()->fetch_assoc()['closure_requested'] ?? 0);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $confirm = strtoupper(trim($_POST['confirm'] ?? ''));
    $reason  = trim($_POST['reason'] ?? '');

    if ($confirm !== 'CLOSE') {
        $error = "Type CLOSE to confirm your request.";
    } else {
        // 1) Durable record via the existing support_messages table.
        $logged = false;
        $subject = 'ACCOUNT CLOSURE REQUEST';
        $body_txt = "Customer requested account closure.\nReason: " . ($reason !== '' ? $reason : '(none given)');
        if ($ins = $conn->prepare("INSERT INTO support_messages (user_id, subject, message, status, created_at) VALUES (?,?,?, 'open', NOW())")) {
            $ins->bind_param("iss", $uid, $subject, $body_txt);
            $logged = $ins->execute();
        }

        // 2) Flag the account if the column exists (admin closes it from their panel).
        if ($upd = $conn->prepare("UPDATE users SET closure_requested=1, closure_requested_at=NOW() WHERE id=?")) {
            $upd->bind_param("i", $uid); $upd->execute();
        }

        // 3) Best-effort email to admin.
        $mailer_path = __DIR__ . '/mailer.php';
        if (file_exists($mailer_path)) {
            require_once $mailer_path;
            if (function_exists('send_mail')) {
                $html = '<div style="font-family:sans-serif">'
                      . '<h3>Account closure request</h3>'
                      . '<p><strong>Customer:</strong> ' . htmlspecialchars($__name) . ' (' . htmlspecialchars($__email) . ')</p>'
                      . '<p><strong>User ID:</strong> ' . $uid . '</p>'
                      . '<p><strong>Reason:</strong> ' . nl2br(htmlspecialchars($reason !== '' ? $reason : '(none given)')) . '</p>'
                      . '<p>Please review and close this account.</p></div>';
                @send_mail('support@dabil.com.ng', 'Dabil Admin', 'Account closure request — ' . $__name, $html);
            }
        }

        $done = $logged || true; // request captured (DB flag and/or email)
        $already = true;
    }
}
?>

<style>
.app-topbar { display: none; }
.main-content { padding-top: calc(env(safe-area-inset-top) + 6px); }
.ca-wrap { max-width: 600px; margin: 0 auto; }

.sub-topbar { display: flex; align-items: center; gap: 12px; padding: 4px 2px 14px; }
.sub-topbar .sub-back { width: 36px; height: 36px; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: var(--primary); background: var(--primary-bg); flex-shrink: 0; }
.sub-topbar .sub-title { font-size: 1.15rem; font-weight: 800; letter-spacing: -.02em; color: var(--text); }

.ca-hero { text-align: center; margin-bottom: 20px; }
.ca-hero-icon { width: 66px; height: 66px; border-radius: 20px; background: var(--error-bg); color: var(--error); display: flex; align-items: center; justify-content: center; margin: 6px auto 12px; }
.ca-hero h1 { font-size: 1.3rem; font-weight: 800; letter-spacing: -.02em; margin-bottom: 4px; }
.ca-hero p { font-size: .85rem; color: var(--text-muted); line-height: 1.5; max-width: 340px; margin: 0 auto; }

.ca-card { background: #fff; border-radius: 16px; box-shadow: 0 4px 18px rgba(15,23,42,.06); border: 1px solid var(--border); padding: 18px; margin-bottom: 16px; }
.ca-list { list-style: none; margin: 0; padding: 0; }
.ca-list li { display: flex; gap: 10px; align-items: flex-start; font-size: .85rem; color: var(--text-muted); line-height: 1.5; padding: 7px 0; }
.ca-list li svg { color: var(--error); flex-shrink: 0; margin-top: 2px; }

.ca-field label { display: block; font-size: .82rem; font-weight: 700; color: var(--text); margin-bottom: 8px; }
.ca-input, .ca-textarea { width: 100%; border: 1.5px solid var(--border); border-radius: 12px; background: #fff; padding: 13px 14px; font-size: max(16px, .92rem); color: var(--text); font-family: var(--font); outline: none; }
.ca-input:focus, .ca-textarea:focus { border-color: var(--error); box-shadow: 0 0 0 3px rgba(239,68,68,.12); }
.ca-textarea { resize: vertical; min-height: 90px; margin-bottom: 16px; }

.ca-submit { width: 100%; height: 54px; border: none; border-radius: 14px; background: var(--error); color: #fff; font-family: var(--font); font-weight: 800; font-size: .95rem; cursor: pointer; }
.ca-submit:active { background: #c0392b; }
.ca-cancel { display: block; text-align: center; color: var(--text-muted); font-weight: 700; font-size: .9rem; margin-top: 14px; }

.ca-success { text-align: center; background: #fff; border-radius: 18px; border: 1px solid var(--border); box-shadow: 0 4px 18px rgba(15,23,42,.06); padding: 32px 22px; }
.ca-success .si { width: 64px; height: 64px; border-radius: 50%; background: var(--success-bg); color: var(--success); display: flex; align-items: center; justify-content: center; margin: 0 auto 16px; }
.ca-success h2 { font-size: 1.15rem; font-weight: 800; margin-bottom: 8px; }
.ca-success p { font-size: .88rem; color: var(--text-muted); line-height: 1.6; }
</style>

<div class="ca-wrap">

  <div class="sub-topbar">
    <a href="security.php" class="sub-back" aria-label="Back">
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M19 12H5m0 0l7 7M5 12l7-7"/></svg>
    </a>
    <span class="sub-title">Close Account</span>
  </div>

  <?php if ($done): ?>
    <div class="ca-success">
      <div class="si"><svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg></div>
      <h2>Request received</h2>
      <p>Our admin team has been notified and will review your account closure. You'll be contacted at <strong><?php echo htmlspecialchars($__email); ?></strong> before anything is permanently removed. You can keep using Dabil in the meantime.</p>
      <a href="profile.php" class="ca-cancel" style="margin-top:20px">Back to settings</a>
    </div>

  <?php elseif ($already): ?>
    <div class="ca-success">
      <div class="si" style="background:var(--warning-bg);color:var(--warning)"><svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></svg></div>
      <h2>Closure already requested</h2>
      <p>You've already asked to close this account and our team is reviewing it. If this was a mistake, please reach out via Contact Admin.</p>
      <a href="contact_admin.php" class="ca-cancel" style="margin-top:20px">Contact Admin</a>
    </div>

  <?php else: ?>
    <div class="ca-hero">
      <div class="ca-hero-icon"><svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><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></div>
      <h1>Close your account</h1>
      <p>This sends a request to our admin team to permanently delete your profile. It can't be undone once processed.</p>
    </div>

    <div class="ca-card">
      <ul class="ca-list">
        <li><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="5" y1="12" x2="19" y2="12"/></svg> Your wallet balance must be withdrawn first — it won't be refunded after closure.</li>
        <li><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="5" y1="12" x2="19" y2="12"/></svg> Your order and transaction history will be removed.</li>
        <li><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="5" y1="12" x2="19" y2="12"/></svg> Admin is notified and will action your request.</li>
      </ul>
    </div>

    <?php if ($error): ?><div class="alert alert-error" style="margin-bottom:16px"><?php echo htmlspecialchars($error); ?></div><?php endif; ?>

    <form method="POST" class="ca-card">
      <div class="ca-field" style="margin-bottom:16px">
        <label>Reason for leaving (optional)</label>
        <textarea name="reason" class="ca-textarea" placeholder="Help us improve — tell us why you're leaving"></textarea>
      </div>
      <div class="ca-field" style="margin-bottom:16px">
        <label>Type <strong>CLOSE</strong> to confirm</label>
        <input type="text" name="confirm" class="ca-input" placeholder="CLOSE" autocapitalize="characters" autocomplete="off" required>
      </div>
      <button type="submit" class="ca-submit">Request Account Closure</button>
    </form>
    <a href="security.php" class="ca-cancel">Cancel, keep my account</a>
  <?php endif; ?>
</div>

<?php include("includes/footer.php"); ?>
