<?php
// File: delete_account.php
// Request account deletion - send verification code

require_once 'config.php';
require_once 'send_email.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'])) {
    sendResponse(false, 'Email is required');
}

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

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

try {
    $conn = getDBConnection();
    if (!$conn) {
        sendResponse(false, 'Database connection failed', null, 500);
    }
    
    // Check if user exists
    $stmt = $conn->prepare("SELECT id, is_deleted, user_name 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.');
    }
    
    if (!$user['user_name']) {
        sendResponse(false, 'Please complete your registration first.');
    }
    
    // Check rate limiting
    $stmt = $conn->prepare("
        SELECT COUNT(*) as count 
        FROM verification_codes 
        WHERE email = ? 
        AND purpose = 'delete_account' 
        AND created_at > DATE_SUB(NOW(), INTERVAL 10 MINUTE)
    ");
    $stmt->execute([$email]);
    $result = $stmt->fetch();
    
    if ($result['count'] >= 3) {
        sendResponse(false, 'Too many requests. Please wait 10 minutes before requesting another code.');
    }
    
    // Generate verification code
    $code = generateVerificationCode();
    $expiresAt = date('Y-m-d H:i:s', strtotime('+15 minutes'));
    
    // Delete old unused codes
    $stmt = $conn->prepare("DELETE FROM verification_codes WHERE email = ? AND purpose = 'delete_account' AND is_used = 0");
    $stmt->execute([$email]);
    
    // Insert new verification code
    $stmt = $conn->prepare("INSERT INTO verification_codes (email, code, purpose, expires_at) VALUES (?, ?, 'delete_account', ?)");
    $stmt->execute([$email, $code, $expiresAt]);
    
    // Send email
    $subject = "ensi.lk - Account Deletion Verification";
    $bodyHTML = "
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: linear-gradient(135deg, #FF7675 0%, #FF6584 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }
                .content { background: #f8f9fa; padding: 30px; border-radius: 0 0 10px 10px; }
                .code { font-size: 32px; font-weight: bold; color: #FF7675; text-align: center; letter-spacing: 10px; padding: 20px; background: white; border-radius: 10px; margin: 20px 0; }
                .warning { background: #FFF3CD; padding: 15px; border-left: 4px solid #FFC947; margin: 20px 0; }
                .footer { text-align: center; color: #636E72; padding: 20px; font-size: 12px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>Account Deletion Request ⚠️</h1>
                </div>
                <div class='content'>
                    <h2>Verify Account Deletion</h2>
                    <p>We received a request to delete your account. Use the following verification code to confirm:</p>
                    <div class='code'>$code</div>
                    <p><strong>This code will expire in 15 minutes.</strong></p>
                    <div class='warning'>
                        <strong>⚠️ Warning:</strong> This action will mark your account as deleted. All your data will be preserved but you won't be able to access your account anymore.
                    </div>
                    <p>If you didn't request account deletion, please ignore this email and your account will remain active. We also recommend changing your password.</p>
                </div>
                <div class='footer'>
                    <p>&copy; 2025 ensi.lk - We're sad to see you go!</p>
                </div>
            </div>
        </body>
        </html>
    ";
    
    $emailSent = sendIdeasEmail($email, $subject, $bodyHTML);
    
    if ($emailSent) {
        logActivity("Account deletion code sent to: $email");
        sendResponse(true, 'Verification code sent to your email. Please verify to complete account deletion.');
    } else {
        logActivity("Failed to send account deletion email to: $email");
        sendResponse(false, 'Failed to send verification email. Please try again later.', null, 500);
    }
    
} catch (Exception $e) {
    logActivity("Account deletion request error: " . $e->getMessage());
    sendResponse(false, 'An error occurred. Please try again later.', null, 500);
}
?>
