<?php
// File: /api/case_data_handler.php

function getCaseData() {
    $caseDir = $_SERVER['DOCUMENT_ROOT'] . '/app/case_data/';
    $caseFiles = glob($caseDir . 'case_*.json');
    $allCases = [];

    foreach ($caseFiles as $file) {
        $caseContent = json_decode(file_get_contents($file), true);
        if ($caseContent && isset($caseContent['id'])) {
            $allCases[$caseContent['id']] = $caseContent;
        }
    }

    ksort($allCases); // Sort cases by ID
    return $allCases;
}

function getAvailableCases($isPro) {
    require_once 'demo_role.php';
    $allCases = getCaseData();
    $availableCases = [];
    $isDemo = isDemoUser();
    
    foreach ($allCases as $id => $case) {
        $title = $case['title'];
        
        // Demo cases take priority over pro status
        $isDemoCase = !($case['isPro'] ?? false) && $isDemo && $id != 1;
        
        // If demo user, block both demo and pro cases
        $isAccessible = $isDemo ? ($id == 1) : ($isPro || !($case['isPro'] ?? false));
            
        $availableCases[] = [
            'id' => $id,
            'title' => $title,
            'isPro' => $case['isPro'] ?? false,
            'isDemo' => $isDemoCase,
            'isAccessible' => $isAccessible,
            'requiresUpgrade' => $isDemo && $id != 1,
            'requiresProUpgrade' => !$isPro && ($case['isPro'] ?? false)
        ];
    }
    
    return $availableCases;
}