<?php
/**
 * SPPG Terpadu - Update Script v2
 * Extract ZIP di ROOT project, lalu akses: https://domain/update.php
 */

error_reporting(E_ALL & ~E_DEPRECATED);
ini_set('display_errors', 0);
set_time_limit(300);
ob_start();

// Root project = 1 level di atas public/
$basePath = dirname(__DIR__);
$updatePath = $basePath . '/update-data';

// Cek apakah folder update-data ada
if (!is_dir($updatePath)) {
    die("
    <html><head><meta charset='utf-8'><title>SPPG Update</title>
    <style>body{font-family:'Segoe UI',sans-serif;max-width:700px;margin:60px auto;padding:30px;background:#0f172a;color:#e2e8f0;text-align:center}
    .box{background:#1e293b;border-radius:16px;padding:30px;border:2px solid #ef4444}
    h2{color:#f87171}code{background:#0f172a;padding:3px 8px;border-radius:6px;color:#93c5fd}</style></head><body>
    <div class='box'>
    <h2>❌ Folder update-data/ tidak ditemukan</h2>
    <p>Pastikan Anda sudah extract ZIP <code>update-penerima-manfaat.zip</code> di <strong>ROOT project</strong> (bukan di public/).</p>
    <p>Setelah extract, struktur folder harus seperti ini:</p>
    <pre style='text-align:left;background:#0f172a;padding:15px;border-radius:8px;color:#86efac;font-size:13px'>
root-project/
├── app/
├── public/
│   └── update.php  ← file ini
├── update-data/    ← folder dari ZIP
│   ├── vendor/
│   ├── app/
│   └── ...
├── vendor/
└── ...</pre>
    </div></body></html>");
}

echo "<html><head><meta charset='utf-8'><title>SPPG Update</title>";
echo "<style>
body{font-family:'Segoe UI',sans-serif;max-width:800px;margin:40px auto;padding:20px;background:#0f172a;color:#e2e8f0}
h1{color:#38bdf8;border-bottom:2px solid #1e3a5f;padding-bottom:15px;text-align:center}
.step{background:#1e293b;border-radius:12px;padding:14px 20px;margin:10px 0;border-left:4px solid #334155;font-size:14px}
.ok{border-left-color:#22c55e;color:#86efac}
.fail{border-left-color:#ef4444;color:#fca5a5}
.warn{border-left-color:#f59e0b;color:#fbbf24}
code{background:#0f172a;padding:2px 6px;border-radius:4px;font-size:12px}
</style></head><body>";
echo "<h1>🔄 SPPG Terpadu — Update PhpSpreadsheet + XLSX Template</h1>";

$step = 0;
$errors = 0;

function logStep($msg, $status = 'ok') {
    global $step, $errors;
    $step++;
    if ($status === 'fail') $errors++;
    $icon = $status === 'ok' ? '✅' : ($status === 'fail' ? '❌' : '⚠️');
    echo "<div class='step {$status}'>{$icon} <strong>#{$GLOBALS['step']}</strong> {$msg}</div>\n";
    if (ob_get_level()) ob_flush();
    flush();
}

// =============================================
// STEP 1: Copy Vendor Dependencies (PhpSpreadsheet)
// =============================================
$vendorDeps = [
    'phpoffice/phpspreadsheet',
    'markbaker/complex',
    'markbaker/matrix',
    'maennchen/zipstream-php',
    'composer/pcre',
];

foreach ($vendorDeps as $dep) {
    $src = $updatePath . '/vendor/' . $dep;
    $dest = $basePath . '/vendor/' . $dep;
    if (is_dir($src)) {
        $parentDir = dirname($dest);
        if (!is_dir($parentDir)) mkdir($parentDir, 0755, true);
        if (is_dir($dest)) deleteDir($dest);
        copyDir($src, $dest);
        logStep("Vendor <code>{$dep}</code> installed");
    } else {
        logStep("Vendor <code>{$dep}</code> tidak ditemukan", 'warn');
    }
}

// =============================================
// STEP 2: Update Composer Autoload Files
// =============================================
$autoloadFiles = [
    'vendor/composer/autoload_psr4.php',
    'vendor/composer/autoload_classmap.php',
    'vendor/composer/autoload_static.php',
    'vendor/composer/installed.json',
    'vendor/composer/installed.php',
];

foreach ($autoloadFiles as $file) {
    $src = $updatePath . '/' . $file;
    $dest = $basePath . '/' . $file;
    if (file_exists($src)) {
        copy($src, $dest);
        logStep("Autoload <code>" . basename($file) . "</code> updated");
    }
}

// =============================================
// STEP 3: Copy Controllers
// =============================================
$controllers = [
    'app/Http/Controllers/DashboardController.php',
    'app/Http/Controllers/DataSiswaController.php',
];

foreach ($controllers as $ctrl) {
    $src = $updatePath . '/' . $ctrl;
    $dest = $basePath . '/' . $ctrl;
    if (file_exists($src)) {
        copy($src, $dest);
        logStep("Controller <code>" . basename($ctrl) . "</code> updated");
    } else {
        logStep("Controller <code>" . basename($ctrl) . "</code> tidak ditemukan", 'warn');
    }
}

// =============================================
// STEP 4: Copy JS Module
// =============================================
$src = $updatePath . '/public/js/modules/datasekolah.js';
$dest = $basePath . '/public/js/modules/datasekolah.js';
if (file_exists($src)) {
    copy($src, $dest);
    logStep("JS <code>datasekolah.js</code> updated");
}

// =============================================
// STEP 5: Copy Views
// =============================================
$src = $updatePath . '/resources/views/components/modals_sasaran.blade.php';
$dest = $basePath . '/resources/views/components/modals_sasaran.blade.php';
if (file_exists($src)) {
    copy($src, $dest);
    logStep("View <code>modals_sasaran.blade.php</code> updated");
}

// =============================================
// STEP 6: Copy Migration
// =============================================
$migrationsDir = $updatePath . '/database/migrations';
if (is_dir($migrationsDir)) {
    $migrationFiles = glob($migrationsDir . '/*.php');
    foreach ($migrationFiles as $migFile) {
        $destFile = $basePath . '/database/migrations/' . basename($migFile);
        copy($migFile, $destFile);
        logStep("Migration <code>" . basename($migFile) . "</code> copied");
    }
}

// =============================================
// STEP 6b: Copy Routes
// =============================================
$src = $updatePath . '/routes/web.php';
$dest = $basePath . '/routes/web.php';
if (file_exists($src)) {
    copy($src, $dest);
    logStep("Routes <code>web.php</code> updated");
}

// =============================================
// STEP 7: Run Artisan Commands
// =============================================
require $basePath . '/vendor/autoload.php';
$app = require_once $basePath . '/bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$kernel->bootstrap();

try {
    Illuminate\Support\Facades\Artisan::call('config:clear');
    logStep('Config cache cleared');
} catch (\Throwable $e) {
    logStep('Config clear: ' . $e->getMessage(), 'warn');
}

try {
    Illuminate\Support\Facades\Artisan::call('route:clear');
    logStep('Route cache cleared');
} catch (\Throwable $e) {
    logStep('Route clear: ' . $e->getMessage(), 'warn');
}

try {
    Illuminate\Support\Facades\Artisan::call('view:clear');
    logStep('View cache cleared');
} catch (\Throwable $e) {
    logStep('View clear: ' . $e->getMessage(), 'warn');
}

try {
    Illuminate\Support\Facades\Artisan::call('cache:clear');
    logStep('App cache cleared');
} catch (\Throwable $e) {
    logStep('Cache clear: ' . $e->getMessage(), 'warn');
}

try {
    Illuminate\Support\Facades\Artisan::call('migrate', ['--force' => true]);
    $output = trim(Illuminate\Support\Facades\Artisan::output());
    logStep('Migrations: <code>' . nl2br($output) . '</code>');
} catch (\Throwable $e) {
    logStep('Migration error: ' . $e->getMessage(), 'fail');
}

// =============================================
// DONE
// =============================================
echo "<div style='background:" . ($errors === 0 ? '#064e3b' : '#7c2d12') . ";border-radius:16px;padding:25px;margin-top:30px;text-align:center;border:2px solid " . ($errors === 0 ? '#10b981' : '#f59e0b') . "'>";
if ($errors === 0) {
    echo "<h2 style='color:#34d399;margin:0'>🎉 Update Berhasil!</h2>";
    echo "<p style='color:#a7f3d0;margin:10px 0 0'>Total {$step} langkah selesai tanpa error.</p>";
} else {
    echo "<h2 style='color:#fbbf24;margin:0'>⚠️ Update selesai dengan {$errors} error</h2>";
}
echo "<p style='color:#6ee7b7;font-size:13px;margin-top:12px'>⚡ Lakukan <strong>Ctrl+Shift+R</strong> (hard refresh) di browser.</p>";
echo "<p style='color:#94a3b8;font-size:12px;margin-top:8px'>Hapus folder <code>update-data/</code> dan file <code>update.php</code> setelah selesai.</p>";
echo "</div></body></html>";

// =============================================
// Helper Functions
// =============================================
function copyDir($src, $dst) {
    if (!is_dir($dst)) mkdir($dst, 0755, true);
    $dir = opendir($src);
    while (($file = readdir($dir)) !== false) {
        if ($file === '.' || $file === '..') continue;
        $srcPath = $src . '/' . $file;
        $dstPath = $dst . '/' . $file;
        is_dir($srcPath) ? copyDir($srcPath, $dstPath) : copy($srcPath, $dstPath);
    }
    closedir($dir);
}

function deleteDir($dir) {
    if (!is_dir($dir)) return;
    $items = array_diff(scandir($dir), ['.', '..']);
    foreach ($items as $item) {
        $path = $dir . '/' . $item;
        is_dir($path) ? deleteDir($path) : unlink($path);
    }
    rmdir($dir);
}
