<?php
require_once '../config.php';
require_once '../middleware.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get the encrypted payload
    $encrypted_payload = file_get_contents('php://input');
    if (empty($encrypted_payload)) {
        sendResponse(400, 'Empty request body');
    }

    // Decrypt the payload
    $data = decryptRequestPayload($encrypted_payload);
    if (!$data) {
        sendResponse(400, 'Invalid request body');
    }

    $device_id = $_SERVER['HTTP_DEVICE_ID'] ?? '';
    $session_token = $_SERVER['HTTP_SESSION_TOKEN'] ?? '';

    validateInput($data, ['user_id']);
    $user_id = $data['user_id'];

    authenticateSession($user_id, $device_id, $session_token);
    rateLimit($user_id);

    $conn = getDbConnection();
    $conn->begin_transaction();

    try {
        // Delete associated data
        $stmt = $conn->prepare("DELETE FROM session_tokens WHERE user_id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();

        $stmt = $conn->prepare("DELETE FROM redeem_history WHERE user_id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();

        $stmt = $conn->prepare("DELETE FROM promo_code_usage WHERE user_id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();

        $stmt = $conn->prepare("DELETE FROM referral_rewards WHERE referrer_id = ? OR referred_id = ?");
        $stmt->bind_param("ii", $user_id, $user_id);
        $stmt->execute();

        // Update referred_by for users who were referred by this user
        $stmt = $conn->prepare("UPDATE users SET referred_by = NULL WHERE referred_by = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();

        // Delete the user
        $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();

        $conn->commit();
        sendResponse(200, 'Account deleted successfully');
    } catch (Exception $e) {
        $conn->rollback();
        sendResponse(500, 'Failed to delete account: ' . $e->getMessage());
    }

    $stmt->close();
    $conn->close();
}
?>