<?php
header('Content-Type: application/json');

// Helper function to return JSON and exit
function respond($success, $message) {
    echo json_encode(["success" => $success, "message" => $message]);
    exit;
}

// Get POSTed JSON
$input = json_decode(file_get_contents("php://input"), true);

if (empty($input['update_url']) || empty($input['version'])) {
    respond(false, "❌ Missing parameters.");
}

$updateUrl = filter_var($input['update_url'], FILTER_VALIDATE_URL);
$version   = preg_replace('/[^0-9.]/', '', $input['version']);

if (!$updateUrl) {
    respond(false, "❌ Invalid update URL.");
}

// ---------------- TEMP FOLDER ----------------
$baseDir = __DIR__ . '/temp_update';
$zipFile = $baseDir . '/update.zip';
$extractPath = $baseDir . '/extracted';

if (!is_dir($baseDir)) mkdir($baseDir, 0755, true);
if (!is_dir($extractPath)) mkdir($extractPath, 0755, true);

// ---------------- DOWNLOAD ZIP ----------------
$data = @file_get_contents($updateUrl);
if (!$data) respond(false, "❌ Failed to download update.");

file_put_contents($zipFile, $data);

// ---------------- EXTRACT ZIP ----------------
$zip = new ZipArchive();
if ($zip->open($zipFile) !== TRUE) respond(false, "❌ Invalid ZIP file.");
if (!$zip->extractTo($extractPath)) respond(false, "❌ Failed to extract ZIP.");
$zip->close();
unlink($zipFile);

// ---------------- COPY FILES TO ROOT ----------------
$it = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($extractPath, RecursiveDirectoryIterator::SKIP_DOTS),
    RecursiveIteratorIterator::SELF_FIRST
);

foreach ($it as $file) {
    $destPath = $_SERVER['DOCUMENT_ROOT'] . '/' . $it->getSubPathName();

    if ($file->isDir()) {
        if (!is_dir($destPath)) mkdir($destPath, 0755, true);
    } else {
        copy($file, $destPath);
    }
}

// ---------------- CLEANUP ----------------
function rrmdir($dir) {
    if (!is_dir($dir)) return;
    $files = array_diff(scandir($dir), ['.', '..']);
    foreach ($files as $file) {
        $path = "$dir/$file";
        is_dir($path) ? rrmdir($path) : unlink($path);
    }
    rmdir($dir);
}

rrmdir($extractPath);
rrmdir($baseDir);

// ---------------- UPDATE VERSION ----------------
$currentVersionFile = $_SERVER['DOCUMENT_ROOT'] . '/update/current_version.txt';
file_put_contents($currentVersionFile, $version);

respond(true, "✅ Update installed successfully.");
