<?php
/**
 * ============================================
 * EMERGENCY FIX - Restore JavaScript Functions
 * ============================================
 */

echo "<!DOCTYPE html><html><head><title>Emergency Fix</title>";
echo "<style>body{font-family:Arial;max-width:800px;margin:50px auto;padding:20px;}";
echo ".success{background:#d1fae5;color:#065f46;padding:15px;border-radius:8px;margin:10px 0;}";
echo ".error{background:#fee2e2;color:#991b1b;padding:15px;border-radius:8px;margin:10px 0;}";
echo ".warning{background:#fef3c7;color:#92400e;padding:15px;border-radius:8px;margin:10px 0;}";
echo ".info{background:#dbeafe;color:#1e40af;padding:15px;border-radius:8px;margin:10px 0;}";
echo "h1{color:#1e293b;}pre{background:#f1f5f9;padding:10px;border-radius:5px;overflow-x:auto;font-size:12px;}";
echo "code{background:#f1f5f9;padding:2px 6px;border-radius:3px;font-family:monospace;}";
echo "</style></head><body>";

echo "<h1>🚨 Emergency Fix - Restore JavaScript</h1>";

$targetFile = __DIR__ . '/acf_kepatuhan_bayar.php';

if (!file_exists($targetFile)) {
    echo "<div class='error'>❌ File tidak ditemukan: $targetFile</div>";
    exit;
}

// Read file
$content = file_get_contents($targetFile);

// Check if functions exist
$hasToggleDropdown = (strpos($content, 'function toggleDropdown') !== false);
$hasSwitchTab = (strpos($content, 'function switchTab') !== false);

echo "<div class='info'>";
echo "📄 <strong>Status File:</strong><br>";
echo "• toggleDropdown: " . ($hasToggleDropdown ? "✅ Ditemukan" : "❌ TIDAK DITEMUKAN") . "<br>";
echo "• switchTab: " . ($hasSwitchTab ? "✅ Ditemukan" : "❌ TIDAK DITEMUKAN") . "<br>";
echo "</div>";

// If functions don't exist, we need to add them
if (!$hasToggleDropdown || !$hasSwitchTab) {
    echo "<div class='warning'>";
    echo "⚠️ <strong>Fungsi JavaScript hilang atau rusak!</strong><br>";
    echo "Mencoba restore dari backup...";
    echo "</div>";
    
    // Check if backup exists
    $backupFiles = glob(__DIR__ . '/acf_kepatuhan_bayar.php.backup.*');
    
    if (count($backupFiles) > 0) {
        // Get the latest backup
        rsort($backupFiles);
        $latestBackup = $backupFiles[0];
        
        echo "<div class='info'>";
        echo "📁 Backup ditemukan: <code>" . basename($latestBackup) . "</code><br>";
        echo "Restoring...";
        echo "</div>";
        
        // Restore from backup
        if (copy($latestBackup, $targetFile)) {
            echo "<div class='success'>";
            echo "✅ <strong>File berhasil di-restore dari backup!</strong><br>";
            echo "Silakan jalankan installer lagi dengan benar.";
            echo "</div>";
        } else {
            echo "<div class='error'>";
            echo "❌ Gagal restore dari backup!";
            echo "</div>";
        }
    } else {
        echo "<div class='error'>";
        echo "❌ <strong>Backup tidak ditemukan!</strong><br>";
        echo "Solusi: Saya akan tambahkan fungsi JavaScript yang hilang.";
        echo "</div>";
        
        // Add JavaScript functions at the end of <script> section
        $javascriptToAdd = <<<'JAVASCRIPT'

// ========================================
// FIXED JAVASCRIPT FUNCTIONS
// ========================================

function toggleDropdown(id) {
    console.log('toggleDropdown called:', id);
    
    const dropdown = document.getElementById(id);
    if (!dropdown) {
        console.error('Dropdown not found:', id);
        return;
    }
    
    const allDropdowns = document.querySelectorAll('.dropdown-container');
    
    allDropdowns.forEach(d => {
        if (d.id !== id) {
            d.classList.remove('active');
        }
    });
    
    dropdown.classList.toggle('active');
    
    if (window.event) {
        window.event.stopPropagation();
    }
}

function switchTab(tabName, evt) {
    console.log('switchTab called:', tabName);
    
    document.querySelectorAll('.tab-content').forEach(tab => {
        tab.classList.remove('active');
    });
    
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active');
    });

    const selectedTab = document.getElementById(tabName);
    if (selectedTab) {
        selectedTab.classList.add('active');
    }
    
    if (evt && evt.currentTarget) {
        evt.currentTarget.classList.add('active');
    }
}

JAVASCRIPT;

        // Find the last </script> tag and add functions before it
        $lastScriptPos = strrpos($content, '</script>');
        
        if ($lastScriptPos !== false) {
            $content = substr_replace($content, $javascriptToAdd . "\n    ", $lastScriptPos, 0);
            
            // Save the file
            if (file_put_contents($targetFile, $content)) {
                echo "<div class='success'>";
                echo "✅ <strong>Fungsi JavaScript berhasil ditambahkan!</strong><br>";
                echo "File sudah diperbaiki.";
                echo "</div>";
            } else {
                echo "<div class='error'>";
                echo "❌ Gagal menyimpan file!";
                echo "</div>";
            }
        } else {
            echo "<div class='error'>";
            echo "❌ Tidak menemukan tag &lt;/script&gt; di file!";
            echo "</div>";
        }
    }
} else {
    echo "<div class='success'>";
    echo "✅ <strong>Fungsi JavaScript masih ada!</strong><br>";
    echo "Kemungkinan masalah ada di tempat lain. Coba clear cache browser (Ctrl+Shift+Del) dan refresh (Ctrl+F5).";
    echo "</div>";
}

echo "<div class='info' style='margin-top:30px;'>";
echo "📝 <strong>Langkah Selanjutnya:</strong><br><br>";
echo "1️⃣ Close tab ini<br>";
echo "2️⃣ Buka dashboard: <code>http://localhost/inventoryACF/pages/manager/acf_kepatuhan_bayar.php</code><br>";
echo "3️⃣ Tekan <strong>Ctrl+Shift+Del</strong> untuk clear cache<br>";
echo "4️⃣ Tekan <strong>Ctrl+F5</strong> untuk hard refresh<br>";
echo "5️⃣ Tekan <strong>F12</strong> dan cek Console<br>";
echo "6️⃣ Test klik dropdown dan tabs";
echo "</div>";

echo "<div style='margin-top:30px;padding:20px;background:#f8fafc;border-radius:8px;'>";
echo "<h3>🧪 Test Dashboard</h3>";
echo "<a href='acf_kepatuhan_bayar.php' target='_blank' style='display:inline-block;background:#6366f1;color:white;padding:12px 24px;text-decoration:none;border-radius:8px;font-weight:bold;'>🚀 Buka Dashboard</a>";
echo "</div>";

echo "</body></html>";
?>
