<?php
/**
 * Delete Account - Confirm and remove user
 * PHP User Registration - https://rskworld.in
 * Developer: Molla Samser | RSK World
 * Contact: help@rskworld.in | +91 93305 39277
 * Year: 2026
 */

require_once __DIR__ . '/includes/init.php';
require_once __DIR__ . '/includes/functions.php';
requireLogin();

$user = getCurrentUser();
if ($user === null) {
    session_destroy();
    header('Location: login.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $confirm = trim($_POST['confirm'] ?? '');
    if (strtoupper($confirm) === 'DELETE') {
        $pdo = getDbConnection();
        $stmt = $pdo->prepare('DELETE FROM users WHERE id = ?');
        $stmt->execute([$user['id']]);
        $_SESSION = [];
        if (ini_get('session.use_cookies')) {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
        }
        session_destroy();
        setFlash('success', 'Your account has been deleted.');
        header('Location: index.php');
        exit;
    }
    $errors = ['Please type DELETE to confirm.'];
}

$pageTitle = 'Delete Account';
require_once __DIR__ . '/includes/header.php';
?>

<div class="auth-card">
    <h1><i class="fas fa-user-times"></i> Delete Account</h1>
    <p class="subtitle">PHP User Registration — <a href="https://rskworld.in" target="_blank">rskworld.in</a></p>

    <?php if (!empty($errors)): ?>
        <div class="alert alert-error"><?= htmlspecialchars(implode(' ', $errors)) ?></div>
    <?php endif; ?>

    <div class="alert alert-warning">
        <strong>This cannot be undone.</strong> All your data will be permanently removed.
    </div>
    <form method="post" action="" class="auth-form" onsubmit="return confirm('Are you sure you want to delete your account?');">
        <div class="form-group">
            <label for="confirm">Type <strong>DELETE</strong> to confirm</label>
            <input type="text" id="confirm" name="confirm" required placeholder="DELETE" autocomplete="off">
        </div>
        <button type="submit" class="btn btn-primary" style="background: var(--error);">Delete My Account</button>
    </form>
    <p class="auth-footer"><a href="profile.php">Cancel — Back to Profile</a></p>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
