<?php
require_once dirname(__DIR__) . '/config.php';
require_once 'session_manager.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

try {
    // Detect user session and get user-specific data path
    detectAndStartUserSession();
    $userDataPath = getCurrentUserDataPath();
    
    if (!$userDataPath) {
        echo json_encode(['success' => false, 'message' => 'User session not found']);
        exit;
    }
    
    $dataPath = rtrim($userDataPath, '/');
    
    if (!is_dir($dataPath)) {
        echo json_encode(['success' => false, 'message' => 'User data folder not found']);
        exit;
    }
    
    // Function to recursively delete directory
    function deleteDirectory($dir) {
        if (!is_dir($dir)) {
            return false;
        }
        
        $files = array_diff(scandir($dir), array('.', '..'));
        
        foreach ($files as $file) {
            $filePath = $dir . DIRECTORY_SEPARATOR . $file;
            if (is_dir($filePath)) {
                deleteDirectory($filePath);
            } else {
                unlink($filePath);
            }
        }
        
        return rmdir($dir);
    }
    
    // Delete the user's data directory
    if (deleteDirectory($dataPath)) {
        // Recreate the empty user data directory
        mkdir($dataPath, 0777, true);
        echo json_encode([
            'success' => true, 
            'message' => 'User data folder deleted successfully',
            'username' => $_SESSION['username'] ?? 'unknown'
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to delete user data folder']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>