<?php
// File: phpspreadsheet-autoloader.php
// Include this at the beginning of upload_import.php

// Check if Composer's autoloader exists and use it if available
if (file_exists('vendor/autoload.php')) {
    require_once 'vendor/autoload.php';
    return; // Exit early if Composer's autoloader is available
}

// Base path to PhpSpreadsheet
$basePath = __DIR__ . '/vendor/phpoffice/vendor/phpoffice/phpspreadsheet/src/';

// Register an autoloader for PhpSpreadsheet classes
spl_autoload_register(function ($class) use ($basePath) {
    // PhpOffice namespace prefix
    $prefix = 'PhpOffice\\PhpSpreadsheet\\';
    
    // Check if the class uses the namespace prefix
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        return; // Class doesn't use the namespace prefix
    }
    
    // Get the relative class name
    $relativeClass = substr($class, $len);
    
    // Replace namespace separators with directory separators
    $file = $basePath . str_replace('\\', '/', $relativeClass) . '.php';
    
    // If the file exists, require it
    if (file_exists($file)) {
        require_once $file;
    } else {
        error_log("PhpSpreadsheet autoloader could not find: $file");
    }
});

// Manually require core files that might be needed
$coreFiles = [
    'PhpSpreadsheet/Calculation/Calculation.php',
    'PhpSpreadsheet/Cell/Cell.php',
    'PhpSpreadsheet/Cell/DataType.php',
    'PhpSpreadsheet/IOFactory.php',
    'PhpSpreadsheet/Reader/IReader.php',
    'PhpSpreadsheet/Reader/BaseReader.php',
    'PhpSpreadsheet/Reader/Xlsx.php',
    'PhpSpreadsheet/Reader/Csv.php',
    'PhpSpreadsheet/Shared/XMLWriter.php',
    'PhpSpreadsheet/Shared/File.php',
    'PhpSpreadsheet/Worksheet/Worksheet.php',
    'PhpSpreadsheet/Style/Style.php',
    'PhpSpreadsheet/Spreadsheet.php',
];

foreach ($coreFiles as $file) {
    $fullPath = $basePath . $file;
    if (file_exists($fullPath)) {
        require_once $fullPath;
    }
}
?>