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

// Disable error display to prevent HTML output
ini_set('display_errors', 0);
error_reporting(0);

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

// Start output buffering to catch any unexpected output
ob_start();

// Check request method
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) {
        throw new Exception('User session not found');
    }
    
    // Get POST data
    $asset = $_POST['asset'] ?? '';
    $datasetFolder = $_POST['dataset_folder'] ?? '';
    
    // Convert asset name to simplified folder name (e.g., "USDINR (OTC)" -> "usdinrotc")
    $assetFolderName = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $asset));
    
    // Validate required fields
    if (empty($asset) || empty($datasetFolder)) {
        throw new Exception('Asset name and dataset folder are required');
    }
    
    // Check uploaded files
    if (!isset($_FILES['candle_data']) || !isset($_FILES['sentiment_data'])) {
        throw new Exception('Both candle data and sentiment data files are required');
    }
    
    // Check for upload errors
    if ($_FILES['candle_data']['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('Candle data upload error: ' . $_FILES['candle_data']['error']);
    }
    
    if ($_FILES['sentiment_data']['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('Sentiment data upload error: ' . $_FILES['sentiment_data']['error']);
    }
    
    // Create directory structure: data/[username]/[simplified_asset]/dataset__dd-mm-yyyy__hh-mm-ss/
    $baseDir = rtrim($userDataPath, '/');
    $assetDir = $baseDir . '/' . $assetFolderName;
    $datasetDir = $assetDir . '/' . $datasetFolder;
    
    // Create all directories at once
    if (!mkdir($datasetDir, 0777, true)) {
        throw new Exception('Failed to create dataset directory: ' . $datasetDir);
    }
    
    // Get file info
    $candleFile = $_FILES['candle_data'];
    $sentimentFile = $_FILES['sentiment_data'];
    
    // Validate file extensions (more reliable than MIME type)
    $candleExt = strtolower(pathinfo($candleFile['name'], PATHINFO_EXTENSION));
    $sentimentExt = strtolower(pathinfo($sentimentFile['name'], PATHINFO_EXTENSION));
    
    if ($candleExt !== 'json' || $sentimentExt !== 'json') {
        throw new Exception('Only JSON files are allowed');
    }
    
    // Move files to destination
    $candleDestination = $datasetDir . '/candle_data.json';
    $sentimentDestination = $datasetDir . '/sentiment_data.json';
    
    if (!move_uploaded_file($candleFile['tmp_name'], $candleDestination)) {
        throw new Exception('Failed to move candle data file');
    }
    
    if (!move_uploaded_file($sentimentFile['tmp_name'], $sentimentDestination)) {
        throw new Exception('Failed to move sentiment data file');
    }
    
    // Clean output buffer and send JSON response
    ob_clean();
    echo json_encode([
        'success' => true,
        'message' => 'Files uploaded successfully',
        'dataset_folder' => $datasetFolder,
        'asset' => $asset,
        'username' => $_SESSION['username'] ?? 'unknown'
    ]);
    
} catch (Exception $e) {
    ob_clean();
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
} catch (Error $e) {
    ob_clean();
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Server error occurred'
    ]);
}
?>