<?php
/**
 * AJAX WAMP Detection Handler
 * Provides real-time WAMP detection results
 */

// Set JSON content type
header('Content-Type: application/json');

try {
    // Change working directory to parent to ensure relative paths work
    chdir(dirname(__DIR__));
    
    // Include WAMP detector
    include 'functions/wamp_detector.php';
    
    $action = $_GET['action'] ?? 'detect';
    
    switch ($action) {
        case 'detect':
            // Force fresh detection
            $detection = WampDetector::forceDetect();
            $wampStatus = WampDetector::getWampStatus();
            
            // Get recommended backup path
            $recommendedPath = WampDetector::getRecommendedBackupPath();
            
            // Test the recommended backup directory
            $backupDirTest = WampDetector::testBackupDirectory($recommendedPath);
            
            // Get available drives
            $availableDrives = WampDetector::getAvailableDrives();
            
            $result = [
                'success' => true,
                'wamp_status' => $wampStatus,
                'detection' => $detection,
                'recommended_backup_path' => $recommendedPath,
                'backup_dir_test' => $backupDirTest,
                'available_drives' => $availableDrives,
                'diagnostics' => WampDetector::getDiagnostics()
            ];
            break;
            
        case 'test_backup_dir':
            $path = $_POST['path'] ?? '';
            if (empty($path)) {
                throw new Exception("Backup path is required");
            }
            
            $testResult = WampDetector::testBackupDirectory($path);
            $result = [
                'success' => true,
                'test_result' => $testResult
            ];
            break;
            
        case 'get_drives':
            $drives = WampDetector::getAvailableDrives();
            $result = [
                'success' => true,
                'drives' => $drives
            ];
            break;
            
        default:
            throw new Exception("Invalid action");
    }
    
    echo json_encode($result, JSON_PRETTY_PRINT);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage(),
        'error' => 'Exception: ' . $e->getMessage()
    ]);
}
?>
