<?php
echo "<h2>PhpSpreadsheet Structure Diagnostic</h2>";

// Check base folder
$baseDir = __DIR__ . '/phpspreadsheet';
if (!is_dir($baseDir)) {
    die("❌ 'phpspreadsheet' folder not found in " . __DIR__);
}
echo "✅ 'phpspreadsheet' folder exists.<br>";

// Recursively scan for Spreadsheet.php
$found = false;
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($baseDir));
foreach ($iterator as $file) {
    if ($file->getFilename() === 'Spreadsheet.php') {
        $found = $file->getPathname();
        break;
    }
}

if ($found) {
    echo "✅ Found Spreadsheet.php at: <code>" . htmlspecialchars(str_replace(__DIR__, '', $found)) . "</code><br>";
    // Check relative path to determine correct base directory
    $relativePath = str_replace($baseDir . '/', '', dirname($found));
    echo "📁 The class files are inside: <code>phpspreadsheet/{$relativePath}</code><br>";
    echo "💡 Your autoloader should point to: <code>__DIR__ . '/phpspreadsheet/{$relativePath}/'</code><br>";
} else {
    echo "❌ Spreadsheet.php NOT found anywhere inside 'phpspreadsheet' folder.<br>";
}

// Show folder tree for debugging
echo "<h3>Folder structure inside 'phpspreadsheet':</h3>";
function listFolder($dir, $level = 0) {
    $items = scandir($dir);
    $items = array_diff($items, ['.', '..']);
    foreach ($items as $item) {
        echo str_repeat("&nbsp;&nbsp;", $level) . "📁 " . $item . "<br>";
        if (is_dir($dir . '/' . $item)) {
            listFolder($dir . '/' . $item, $level + 1);
        }
    }
}
listFolder($baseDir);

// Suggest fix
if (!$found) {
    echo "<h3>🔧 How to fix:</h3>";
    echo "<p>You need to place the contents of the 'src' folder from the PhpSpreadsheet ZIP directly into 'phpspreadsheet'.</p>";
    echo "<p>Correct structure should be:<br>";
    echo "<code>phpspreadsheet/PhpOffice/PhpSpreadsheet/Spreadsheet.php</code></p>";
    echo "<p>Download ZIP from: https://github.com/PHPOffice/PhpSpreadsheet/archive/master.zip<br>";
    echo "Extract → go into 'PhpSpreadsheet-master' → copy the 'src' folder → rename it to 'phpspreadsheet' → upload to your server.</p>";
} else {
    echo "<h3>✅ Your autoloader (vendor_autoload.php) needs to be updated.</h3>";
    $correctBase = "__DIR__ . '/phpspreadsheet/" . $relativePath . "'";
    echo "<p>Replace your autoloader base_dir with: <code>{$correctBase}</code></p>";
}
?>