<?php
/**
 * Phoenix Diagnostician v1.0
 *
 * ARAHAN:
 * 1. Simpan fail ini sebagai 'diagnose.php'.
 * 2. Muat naik ke direktori akar (root) projek yang ingin dianalisis.
 * 3. Akses fail ini melalui pelayar web (cth: https://www.projek-klien.com/diagnose.php).
 * 4. Salin laporan yang dijana untuk digunakan dalam Protokol Onboarding.
 * 5. SELEPAS SELESAI, PADAM FAIL INI DARI SERVER DENGAN SEGERA ATAS SEBAB KESELAMATAN.
 *
 * AMARAN KESELAMATAN:
 * - Skrip ini mempunyai akses bacaan kepada fail-fail di server.
 * - Ia direka untuk TIDAK membaca fail sensitif seperti '.env'.
 * - Jangan tinggalkan skrip ini di server selepas digunakan.
 */

// Sembunyikan ralat untuk paparan yang kemas
error_reporting(0);
ini_set('display_errors', 0);

class PhoenixDiagnostician
{
    private $rootPath;
    private $report;
    private $exclusions = ['.', '..', 'vendor', 'node_modules', '.git', '.idea', 'cgi-bin'];

    public function __construct($startPath)
    {
        $this->rootPath = $startPath;
        $this->report = [
            'summary' => [],
            'ecosystem' => 'Tidak Dikenal Pasti',
            'framework' => 'Tidak Dikenal Pasti',
            'dependencies' => [],
            'env_example' => null,
            'directory_structure' => '',
            'key_files' => []
        ];
        // Tambah nama fail skrip ini ke dalam senarai pengecualian
        $this->exclusions[] = basename(__FILE__);
    }

    public function run()
    {
        $this->detectEcosystemAndFramework();
        $this->getDependencies();
        $this->getEnvExample();
        $this->buildDirectoryStructure($this->rootPath, 0);
        return $this->report;
    }

    private function detectEcosystemAndFramework()
    {
        // Peringkat 1: Ekosistem
        if (file_exists($this->rootPath . '/composer.json')) {
            $this->report['ecosystem'] = 'PHP / Composer';
            // Peringkat 2: Rangka Kerja PHP
            if (file_exists($this->rootPath . '/artisan')) $this->report['framework'] = 'Laravel';
            elseif (file_exists($this->rootPath . '/bin/console')) $this->report['framework'] = 'Symfony';
            elseif (file_exists($this->rootPath . '/spark')) $this->report['framework'] = 'CodeIgniter 4';
            elseif (file_exists($this->rootPath . '/wp-config.php')) $this->report['framework'] = 'WordPress';
            else $this->report['framework'] = 'PHP (Lain-lain/Vanilla)';
        }
        elseif (file_exists($this->rootPath . '/package.json')) {
            $this->report['ecosystem'] = 'JavaScript / Node.js';
            // Peringkat 2: Rangka Kerja JS
            if (file_exists($this->rootPath . '/next.config.js')) $this->report['framework'] = 'Next.js (React)';
            elseif (file_exists($this->rootPath . '/nuxt.config.js')) $this->report['framework'] = 'Nuxt.js (Vue)';
            elseif (file_exists($this->rootPath . '/angular.json')) $this->report['framework'] = 'Angular';
            elseif (file_exists($this->rootPath . '/svelte.config.js')) $this->report['framework'] = 'SvelteKit';
            else $this->report['framework'] = 'Node.js/Vanilla JS';
            
            if (file_exists($this->rootPath . '/tsconfig.json')) {
                 $this->report['framework'] .= ' (menggunakan TypeScript)';
            }
        }
        elseif (file_exists($this->rootPath . '/requirements.txt') || file_exists($this->rootPath . '/Pipfile')) {
            $this->report['ecosystem'] = 'Python';
            if (file_exists($this->rootPath . '/manage.py')) $this->report['framework'] = 'Django';
            else $this->report['framework'] = 'Python (Flask/Lain-lain)';
        }
         elseif (file_exists($this->rootPath . '/Gemfile')) {
            $this->report['ecosystem'] = 'Ruby';
            $this->report['framework'] = 'Ruby on Rails';
        }
    }

    private function getDependencies()
    {
        if (file_exists($this->rootPath . '/composer.json')) {
            $composerJson = @file_get_contents($this->rootPath . '/composer.json');
            $this->report['key_files']['composer.json'] = $composerJson;
            $data = json_decode($composerJson, true);
            $this->report['dependencies']['composer'] = [
                'require' => $data['require'] ?? [],
                'require-dev' => $data['require-dev'] ?? []
            ];
        }
        if (file_exists($this->rootPath . '/package.json')) {
            $packageJson = @file_get_contents($this->rootPath . '/package.json');
            $this->report['key_files']['package.json'] = $packageJson;
            $data = json_decode($packageJson, true);
            $this->report['dependencies']['npm'] = [
                'dependencies' => $data['dependencies'] ?? [],
                'devDependencies' => $data['devDependencies'] ?? []
            ];
        }
    }

    private function getEnvExample()
    {
        if (file_exists($this->rootPath . '/.env.example')) {
            $this->report['env_example'] = @file_get_contents($this->rootPath . '/.env.example');
        }
    }

    private function buildDirectoryStructure($dir, $depth)
    {
        if ($depth > 5) return; // Hadkan kedalaman untuk elak rekursi melampau
        $items = @scandir($dir);
        if (!$items) return;

        foreach ($items as $item) {
            if (in_array($item, $this->exclusions)) continue;
            
            $path = $dir . '/' . $item;
            $prefix = str_repeat('    ', $depth);
            
            if (is_dir($path)) {
                $this->report['directory_structure'] .= $prefix . '📁 ' . $item . "\n";
                $this->buildDirectoryStructure($path, $depth + 1);
            } else {
                $this->report['directory_structure'] .= $prefix . '📄 ' . $item . "\n";
            }
        }
    }

    public function render()
    {
        $report = $this->run();
        ?>
        <!DOCTYPE html>
        <html lang="ms">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Laporan Diagnostik Phoenix</title>
            <script src="https://cdn.tailwindcss.com"></script>
            <style>
                body { background-color: #111827; color: #E5E7EB; font-family: sans-serif; }
                .card { background-color: #1F2937; border: 1px solid #374151; }
                pre { background-color: #111827; border: 1px solid #4B5563; color: #D1D5DB; white-space: pre-wrap; word-wrap: break-word; }
                .copy-btn { background-color: #D97706; color: #111827; transition: background-color 0.3s ease; }
                .copy-btn:hover { background-color: #F59E0B; }
            </style>
        </head>
        <body class="p-4 sm:p-8">
            <div class="max-w-4xl mx-auto">
                <div class="text-center mb-8">
                    <h1 class="text-4xl font-bold text-white"><span class="text-amber-500">Phoenix</span> Diagnostician</h1>
                    <p class="text-lg text-gray-400 mt-2">Laporan Analisis Projek Automatik</p>
                    <div class="mt-4 text-xs text-red-400 bg-red-900/50 border border-red-700 p-3 rounded-lg">
                        <strong>AMARAN:</strong> Sila padam fail ini (<code><?php echo basename(__FILE__); ?></code>) dari server anda selepas menyalin laporan ini.
                    </div>
                </div>

                <div class="card rounded-xl shadow-2xl p-6 space-y-6">
                    <div>
                        <h2 class="text-2xl font-bold text-amber-400 border-b border-gray-700 pb-2 mb-3">Ringkasan Diagnostik</h2>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-center">
                            <div class="card p-4 rounded-lg">
                                <h3 class="text-sm font-semibold text-gray-400">Ekosistem Dikesan</h3>
                                <p class="text-xl font-bold text-white"><?php echo htmlspecialchars($report['ecosystem']); ?></p>
                            </div>
                            <div class="card p-4 rounded-lg">
                                <h3 class="text-sm font-semibold text-gray-400">Rangka Kerja Dikesan</h3>
                                <p class="text-xl font-bold text-white"><?php echo htmlspecialchars($report['framework']); ?></p>
                            </div>
                        </div>
                    </div>

                    <div>
                        <h2 class="text-2xl font-bold text-amber-400 border-b border-gray-700 pb-2 mb-3">Struktur Direktori Utama</h2>
                        <pre class="p-4 rounded-lg text-sm" id="dir-structure"><?php echo htmlspecialchars($report['directory_structure']); ?></pre>
                    </div>

                    <?php if ($report['env_example']): ?>
                    <div>
                        <h2 class="text-2xl font-bold text-amber-400 border-b border-gray-700 pb-2 mb-3">Kandungan <code>.env.example</code></h2>
                        <pre class="p-4 rounded-lg text-xs" id="env-content"><?php echo htmlspecialchars($report['env_example']); ?></pre>
                    </div>
                    <?php endif; ?>

                    <?php foreach($report['key_files'] as $filename => $content): ?>
                    <div>
                        <h2 class="text-2xl font-bold text-amber-400 border-b border-gray-700 pb-2 mb-3">Kandungan <code><?php echo htmlspecialchars($filename); ?></code></h2>
                        <pre class="p-4 rounded-lg text-xs" id="file-<?php echo str_replace('.', '-', $filename); ?>"><?php echo htmlspecialchars($content); ?></pre>
                    </div>
                    <?php endforeach; ?>
                </div>
                
                <div class="text-center mt-6 text-xs text-gray-500">
                    Laporan dijana oleh Phoenix Diagnostician v1.0 pada <?php echo date('d-m-Y H:i:s'); ?>
                </div>
            </div>
        </body>
        </html>
        <?php
    }
}

// Jalankan diagnostik dan paparkan laporan
$diagnostician = new PhoenixDiagnostician(__DIR__);
$diagnostician->render();
?>
