<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');

// Manual autoloader for PhpSpreadsheet
spl_autoload_register(function ($class) {
    $prefix = 'PhpOffice\\PhpSpreadsheet\\';
    $base_dir = __DIR__ . '/phpspreadsheet/src/PhpSpreadsheet/';

    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        return;
    }

    $relative_class = substr($class, $len);
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';

    if (file_exists($file)) {
        require $file;
    }
});

use PhpOffice\PhpSpreadsheet\IOFactory;

$uploadDir = 'uploads/';

if (isset($_GET['file'])) {
    $fileName = basename($_GET['file']);
    $filePath = $uploadDir . $fileName;

    if (file_exists($filePath)) {
        $spreadsheet = IOFactory::load($filePath);
        $sheet = $spreadsheet->getActiveSheet();
        $data = $sheet->toArray();
        echo json_encode($data);
    } else {
        http_response_code(404);
        echo json_encode(['message' => 'File not found']);
    }
} else {
    http_response_code(400);
    echo json_encode(['message' => 'No file specified']);
}
?>
