<?php
/**
 * ================================================
 * KAUSTASTRUKTUURI DIAGNOSTIKA
 * ================================================
 */

require_once 'config/config.php';

function scanDirectory($dir, $prefix = '') {
    $result = '';
    
    if (!is_dir($dir)) {
        return $prefix . "❌ Kaust ei eksisteeri: $dir\n";
    }
    
    $files = scandir($dir);
    if ($files === false) {
        return $prefix . "❌ Ei saa lugeda kausta: $dir\n";
    }
    
    foreach ($files as $file) {
        if ($file === '.' || $file === '..') continue;
        
        $fullPath = $dir . DIRECTORY_SEPARATOR . $file;
        
        if (is_dir($fullPath)) {
            $result .= $prefix . "📁 " . $file . "/\n";
            // Rekursiivne allkaustade skaneerimine (max 3 taset)
            if (substr_count($prefix, '  ') < 3) {
                $result .= scanDirectory($fullPath, $prefix . '  ');
            }
        } else {
            $size = filesize($fullPath);
            $sizeStr = $size ? '[' . round($size/1024, 1) . ' KB]' : '[0 KB]';
            $result .= $prefix . "📄 " . $file . " $sizeStr\n";
        }
    }
    
    return $result;
}

?>
<!DOCTYPE html>
<html lang="et">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kaustastruktuur - Estreka</title>
    <style>
        body { font-family: 'Courier New', monospace; margin: 20px; background: #f5f5f5; }
        .container { max-width: 1000px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; }
        .section { margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
        pre { background: #f8f9fa; padding: 15px; border-radius: 5px; overflow-x: auto; line-height: 1.4; }
        .info { background: #d1ecf1; border-color: #bee5eb; color: #0c5460; }
        .success { background: #d4edda; border-color: #c3e6cb; color: #155724; }
        .error { background: #f8d7da; border-color: #f5c6cb; color: #721c24; }
    </style>
</head>
<body>
    <div class="container">
        <h1>📂 Kaustastruktuuri analüüs</h1>
        
        <div class="section info">
            <h2>ℹ️ Tee informatsioon</h2>
            <pre><?php
                echo "BASE_PATH: " . (defined('BASE_PATH') ? BASE_PATH : 'MÄÄRAMATA') . "\n";
                echo "Praegune kataloog: " . __DIR__ . "\n";
                echo "Document Root: " . $_SERVER['DOCUMENT_ROOT'] . "\n";
                echo "Script nimi: " . $_SERVER['SCRIPT_NAME'] . "\n";
                echo "Tööline kataloog: " . getcwd() . "\n";
            ?></pre>
        </div>

        <div class="section">
            <h2>📁 Kogu projekti kaustastruktuur</h2>
            <pre><?php echo scanDirectory(__DIR__); ?></pre>
        </div>

        <div class="section">
            <h2>🔍 Otsime kalendri faile</h2>
            <pre><?php
                $searchPaths = [
                    'Juurkaust' => __DIR__,
                    'calendar kaust' => __DIR__ . '/calendar',
                    'assets kaust' => __DIR__ . '/assets',
                    'calendar/assets' => __DIR__ . '/calendar/assets',
                    'js kaust' => __DIR__ . '/js',
                    'css kaust' => __DIR__ . '/css',
                ];

                foreach ($searchPaths as $name => $path) {
                    echo "🔍 Otsin: $name ($path)\n";
                    if (is_dir($path)) {
                        $files = glob($path . '/*.{js,css}', GLOB_BRACE);
                        if ($files) {
                            foreach ($files as $file) {
                                echo "  ✅ Leitud: " . basename($file) . "\n";
                            }
                        } else {
                            echo "  ❌ JS/CSS faile ei leitud\n";
                        }
                    } else {
                        echo "  ❌ Kaust ei eksisteeri\n";
                    }
                    echo "\n";
                }
            ?></pre>
        </div>

        <div class="section">
            <h2>📋 Konkreetsete failide otsimine</h2>
            <pre><?php
                $filesToFind = [
                    'calendar-core.js',
                    'reminders.js', 
                    'categories.js',
                    'calendar.css'
                ];

                function findFileRecursive($dir, $filename) {
                    $iterator = new RecursiveIteratorIterator(
                        new RecursiveDirectoryIterator($dir),
                        RecursiveIteratorIterator::SELF_FIRST
                    );

                    $found = [];
                    foreach ($iterator as $file) {
                        if ($file->isFile() && $file->getFilename() === $filename) {
                            $found[] = $file->getPathname();
                        }
                    }
                    return $found;
                }

                foreach ($filesToFind as $filename) {
                    echo "🔍 Otsin: $filename\n";
                    try {
                        $found = findFileRecursive(__DIR__, $filename);
                        if ($found) {
                            foreach ($found as $path) {
                                $relativePath = str_replace(__DIR__ . '/', '', $path);
                                echo "  ✅ Leitud: $relativePath\n";
                            }
                        } else {
                            echo "  ❌ Ei leitud\n";
                        }
                    } catch (Exception $e) {
                        echo "  ❌ Viga otsimisel: " . $e->getMessage() . "\n";
                    }
                    echo "\n";
                }
            ?></pre>
        </div>

        <div class="section">
            <h2>🔧 Soovitused parandamiseks</h2>
            <div id="recommendations">
                <p>Analüüsin kaustastruktuuri ja annan soovitused...</p>
            </div>
        </div>
    </div>

    <script>
        // Analüüsi tulemused ja anna soovitused
        document.addEventListener('DOMContentLoaded', function() {
            const recommendations = document.getElementById('recommendations');
            
            // Siin saaksime JavaScript'iga analüüsida tulemusi
            recommendations.innerHTML = `
                <h3>📝 Toimingud:</h3>
                <ol>
                    <li><strong>Kontrolli kaustastruktuuri</strong> - Vaata ülal olevat struktuuri</li>
                    <li><strong>Leia JS/CSS failid</strong> - Vaata kus nad tegelikult asuvad</li>
                    <li><strong>Paranda teed</strong> - Muuda calendar.php failis skriptide teed</li>
                    <li><strong>Kopeeri failid õigesse kohta</strong> - Või loo õige kaustastruktuur</li>
                </ol>
                
                <h3>🎯 Oodatav struktuur:</h3>
                <pre>ratsaklubi.estreka/
├── calendar.php
├── debug.php
├── config/
├── calendar/
│   ├── assets/
│   │   ├── css/
│   │   │   └── calendar.css
│   │   └── js/
│   │       ├── calendar-core.js
│   │       ├── reminders.js
│   │       └── categories.js
│   └── api/
└── data/</pre>
            `;
        });
    </script>
</body>
</html>