<?php
// File: verify_delete.php
// Verify and complete account deletion

require_once 'config.php';

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(false, 'Method not allowed', null, 405);
}

$input = getJsonInput();

// Validate input
if (empty($input['email']) || empty($input['code'])) {
    sendResponse(false, 'Email and code are required');
}

$email = sanitizeInput($input['email']);
$code = sanitizeInput($input['code']);

// Validate email format
if (!validateEmail($email)) {
    sendResponse(false, 'Invalid email format');
}

// Validate code format
if (!preg_match('/^\d{4}$/', $code)) {
    sendResponse(false, 'Invalid code format');
}

try {
    $conn = getDBConnection();
    if (!$conn) {
        sendResponse(false, 'Database connection failed', null, 500);
    }
    
    // Verify the code
    $stmt = $conn->prepare("
        SELECT id 
        FROM verification_codes 
        WHERE email = ? 
        AND code = ? 
        AND purpose = 'delete_account'
        AND is_used = 0 
        AND expires_at > NOW()
        ORDER BY created_at DESC 
        LIMIT 1
    ");
    $stmt->execute([$email, $code]);
    $verificationCode = $stmt->fetch();
    
    if (!$verificationCode) {
        logActivity("Invalid or expired account deletion code for: $email");
        sendResponse(false, 'Invalid or expired verification code');
    }
    
    // Get user
    $stmt = $conn->prepare("SELECT id, is_deleted FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();
    
    if (!$user) {
        sendResponse(false, 'User not found');
    }
    
    if ($user['is_deleted'] == 1) {
        sendResponse(false, 'This account is already deleted.');
    }
    
    // Mark account as deleted (soft delete)
    $stmt = $conn->prepare("UPDATE users SET is_deleted = 1, updated_at = NOW() WHERE id = ?");
    $stmt->execute([$user['id']]);
    
    // Mark code as used
    $stmt = $conn->prepare("UPDATE verification_codes SET is_used = 1 WHERE id = ?");
    $stmt->execute([$verificationCode['id']]);
    
    logActivity("Account deleted (soft delete) for: $email");
    
    sendResponse(true, 'Your account has been deleted successfully. We\'re sorry to see you go!');
    
} catch (Exception $e) {
    logActivity("Account deletion verification error: " . $e->getMessage());
    sendResponse(false, 'An error occurred. Please try again later.', null, 500);
}
?>
