<?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 data folder are required');
    }
    
    // Check uploaded file
    if (!isset($_FILES['combined_data'])) {
        throw new Exception('Combined data file is required');
    }
    
    // Check for upload errors
    if ($_FILES['combined_data']['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('Combined data upload error: ' . $_FILES['combined_data']['error']);
    }
    
    // Create directory structure: data/[username]/[simplified_asset]/data__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 data directory: ' . $datasetDir);
    }
    
    // Get file info
    $combinedFile = $_FILES['combined_data'];
    
    // Validate file extension (more reliable than MIME type)
    $combinedExt = strtolower(pathinfo($combinedFile['name'], PATHINFO_EXTENSION));
    
    if ($combinedExt !== 'json') {
        throw new Exception('Only JSON files are allowed');
    }
    
    // Move file to destination
    $combinedDestination = $datasetDir . '/Combined_data.json';
    
    if (!move_uploaded_file($combinedFile['tmp_name'], $combinedDestination)) {
        throw new Exception('Failed to move combined data file');
    }
    
    // Clean output buffer and send JSON response
    ob_clean();
    echo json_encode([
        'success' => true,
        'message' => 'Data file uploaded successfully',
        'data_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'
    ]);
}
?>