<?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 = glob($dataPath . '/dataset_*');
    
    // Check if any dataset has both required files
    foreach ($datasets as $dataset) {
        $candleFile = $dataset . '/candle_data.json';
        $sentimentFile = $dataset . '/sentiment_data.json';
        
        if (file_exists($candleFile) && file_exists($sentimentFile)) {
            // Verify files are not empty and contain valid data
            $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'
]);
?>