<?php
/**
 * Neptuno ERP - Server Installer v0.0.8
 * Designed for shared hosting with limited execution time.
 */

// Maximum possible limits
@set_time_limit(0);
@ini_set('max_execution_time', 0);
@ini_set('memory_limit', '512M');
@ini_set('display_errors', 1);
error_reporting(E_ALL);

// Send headers immediately so browser doesn't timeout waiting
header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-cache');

// Start sending output RIGHT NOW
echo '<!DOCTYPE html><html><head><meta charset="utf-8"><title>Neptuno Installer</title></head>';
echo '<body style="background:#0f172a;color:#e2e8f0;font-family:monospace;padding:40px;">';
echo '<h1 style="color:#38bdf8;">⚡ Neptuno ERP — Installer (Auto-Detect)</h1>';
echo str_pad('', 4096) . "\n"; // Force browser to start rendering
ob_flush(); flush();

function out($msg, $type = 'info') {
    $colors = ['info' => '#0ea5e9', 'success' => '#10b981', 'error' => '#ef4444', 'warning' => '#f59e0b'];
    $color = $colors[$type] ?? '#e2e8f0';
    echo "<p style='color:{$color};margin:4px 0;font-size:13px;'>[".date('H:i:s')."] {$msg}</p>\n";
    echo str_pad('', 256) . "\n"; // Padding to force flush
    ob_flush(); flush();
}

out("PHP " . phpversion() . " | Memory limit: " . ini_get('memory_limit') . " | Max exec time: " . ini_get('max_execution_time'));

// Step 1: Find ZIP dynamically
$zipFiles = glob(__DIR__ . '/build-*.zip');
if (empty($zipFiles)) {
    out("❌ ZIP not found: Could not find any build-vX.X.X.zip file.", 'error');
    out("Make sure the build zip is in the same directory as this script.", 'error');
    echo '</body></html>'; exit;
}
rsort($zipFiles); // Sort descending to get the newest version if multiple exist
$zipFile = $zipFiles[0];
$sizeMB = round(filesize($zipFile) / 1024 / 1024, 1);
out("✅ Found deployment package: " . basename($zipFile) . " ({$sizeMB} MB)", 'success');

// Step 2: Check ZipArchive
if (!class_exists('ZipArchive')) {
    out("❌ ZipArchive extension not available!", 'error');
    echo '</body></html>'; exit;
}

// Step 3: Extract
out("📦 Starting extraction... This may take 1-3 minutes. Please wait.", 'warning');

$zip = new ZipArchive;
if ($zip->open($zipFile) !== true) {
    out("❌ Could not open ZIP file.", 'error');
    echo '</body></html>'; exit;
}

// Suppress notices for ob_flush
error_reporting(E_ALL & ~E_NOTICE);

$total = $zip->numFiles;
out("Archive contains {$total} entries.", 'info');

// Extract in batches with manual stream routing to fix Windows Zip backslash corruption
$batchSize = 250;
$extracted = 0;

for ($i = 0; $i < $total; $i++) {
    $entryName = $zip->getNameIndex($i);
    $cleanName = str_replace('\\', '/', $entryName); // Force POSIX paths even if Windows packed it!
    $dest = __DIR__ . '/' . $cleanName;
    
    if (substr($cleanName, -1) === '/') {
        if (!is_dir($dest)) rmkdir($dest);
    } else {
        $dir = dirname($dest);
        if (!is_dir($dir)) rmkdir($dir);
        
        // Stream it intelligently to avoid RAM limits
        $fp = $zip->getStream($entryName);
        if ($fp) {
            $out = fopen($dest, 'w');
            if ($out) {
                stream_copy_to_stream($fp, $out);
                fclose($out);
            }
            fclose($fp);
        }
    }
    
    $extracted++;
    if ($extracted % $batchSize === 0) {
        $pct = round(($extracted / $total) * 100);
        out("... {$extracted}/{$total} files ({$pct}%)", 'info');
    }
}

$zip->close();
out("✅ Extraction complete! All {$extracted} files dynamically unpacked with corrected paths.", 'success');

// Helper for recursive mkdir
function rmkdir($path) {
    if (empty($path) || $path === '.' || $path === '/') return;
    if (!is_dir($path)) {
        rmkdir(dirname($path));
        @mkdir($path, 0755);
    }
}

// Step 4: Create required directories
out("📁 Creating required directories...", 'info');
$dirs = [
    __DIR__ . '/storage/app/public',
    __DIR__ . '/storage/framework/cache/data',
    __DIR__ . '/storage/framework/sessions',
    __DIR__ . '/storage/framework/views',
    __DIR__ . '/storage/logs',
    __DIR__ . '/bootstrap/cache',
];
foreach ($dirs as $dir) {
    if (!is_dir($dir)) {
        @mkdir($dir, 0775, true);
    }
}
out("✅ Directories ready.", 'success');

// Step 5: Fix permissions on critical dirs
out("🔧 Setting permissions...", 'info');
$fixDirs = [__DIR__ . '/storage', __DIR__ . '/bootstrap/cache'];
foreach ($fixDirs as $d) {
    if (is_dir($d)) @chmod($d, 0775);
}
out("✅ Permissions set.", 'success');

// Step 6: Check .env
$envFile = __DIR__ . '/.env';
if (file_exists($envFile)) {
    $env = file_get_contents($envFile);
    if (strpos($env, 'APP_KEY=base64:') !== false) {
        out("✅ APP_KEY already configured.", 'success');
    } else {
        $key = 'base64:' . base64_encode(random_bytes(32));
        $env = preg_replace('/APP_KEY=.*/', 'APP_KEY=' . $key, $env);
        file_put_contents($envFile, $env);
        out("✅ Generated new APP_KEY.", 'success');
    }
} else {
    out("⚠️ .env file not found.", 'warning');
}

// Step 7: Clear server cache (CRITICAL for OpCache on shared hosting)
out("🧹 Clearing server-side caches (OpCache)...", 'info');
if (function_exists('opcache_reset')) {
    opcache_reset();
    out("✅ OpCache reset successfully.", 'success');
}
if (function_exists('apcu_clear_cache')) {
    apcu_clear_cache();
}

// Step 8: Verify
out("🔍 Verifying deployment...", 'info');
$checks = [
    'index.html' => 'Landing Page',
    'public/index.php' => 'Laravel Entry Point',
    'public/.htaccess' => 'Laravel Routing',
    'vendor/autoload.php' => 'Composer Dependencies',
    'routes/web.php' => 'Web Routes',
    'routes/auth.php' => 'Auth Routes',
    '.env' => 'Environment Config',
];

$allOk = true;
foreach ($checks as $file => $label) {
    if (file_exists(__DIR__ . '/' . $file)) {
        out("✅ {$label} ({$file})", 'success');
    } else {
        out("❌ MISSING: {$label} ({$file})", 'error');
        $allOk = false;
    }
}

// Final
echo '<hr style="border-color:#334155;margin:20px 0;">';
if ($allOk) {
    echo '<h2 style="color:#10b981;">🎉 DEPLOYMENT SUCCESSFUL!</h2>';
    out("Landing page: http://" . $_SERVER['HTTP_HOST'] . "/", 'info');
    out("ERP Dashboard: http://" . $_SERVER['HTTP_HOST'] . "/public/", 'info');
    out("⚠️ Next: Run fix_permissions.php, then delete installer files!", 'warning');
} else {
    echo '<h2 style="color:#ef4444;">⚠️ Deployment completed with issues</h2>';
    out("Check the missing files above.", 'error');
}

out("Server: " . ($_SERVER['SERVER_SOFTWARE'] ?? 'Unknown') . " | Doc Root: " . ($_SERVER['DOCUMENT_ROOT'] ?? 'Unknown'));
echo '</body></html>';
?>
