<?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(['error' => 'Method not allowed']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['assetKey'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Asset key is required']);
    exit;
}

$assetKey = $input['assetKey'];

// Convert asset key to folder name format (lowercase with 'otc' suffix)
$folderName = strtolower($assetKey) . 'otc';

// Detect user session and get user-specific data path
detectAndStartUserSession();
$userDataPath = getCurrentUserDataPath();

if (!$userDataPath) {
    http_response_code(401);
    echo json_encode(['error' => 'User session not found']);
    exit;
}

// Path to user-specific data directory
$dataPath = $userDataPath . $folderName;

$hasData = false;

// Check if asset folder exists and has datasets
if (is_dir($dataPath)) {
    $datasets = array_merge(
        glob($dataPath . '/data_*') ?: [],
        glob($dataPath . '/dataset_*') ?: []
    );
    
    // Check if any dataset has required files
    foreach ($datasets as $dataset) {
        $combinedFile = $dataset . '/Combined_data.json';
        $candleFile = $dataset . '/candle_data.json';
        $sentimentFile = $dataset . '/sentiment_data.json';
        
        // New combined format
        if (file_exists($combinedFile)) {
            $combinedData = file_get_contents($combinedFile);
            if (!empty($combinedData)) {
                $combinedJson = json_decode($combinedData, true);
                if ($combinedJson !== null) {
                    $hasData = true;
                    break;
                }
            }
        }
        
        // Legacy format fallback
        if (file_exists($candleFile) && file_exists($sentimentFile)) {
            $candleData = file_get_contents($candleFile);
            $sentimentData = file_get_contents($sentimentFile);
            
            if (!empty($candleData) && !empty($sentimentData)) {
                $candleJson = json_decode($candleData, true);
                $sentimentJson = json_decode($sentimentData, true);
                
                if (is_array($candleJson) && count($candleJson) > 0 &&
                    is_array($sentimentJson) && count($sentimentJson) > 0) {
                    $hasData = true;
                    break;
                }
            }
        }
    }
}

echo json_encode([
    'hasData' => $hasData,
    'assetKey' => $assetKey,
    'folderName' => $folderName,
    'dataPath' => $dataPath,
    'username' => $_SESSION['username'] ?? 'unknown'
]);
?>