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

$update_url = 'https://github.com/hotspotbilling/phpnuxbill/archive/refs/heads/master.zip';
$cache_dir = __DIR__ . '/system/cache/';
$web_dir = __DIR__ . '/';
$file = $cache_dir . 'phpnuxbill.zip';
$folder = $cache_dir . 'phpnuxbill-master/';
$log = [];

function logMessage($message, $type = 'success') {
    global $log;
    $log[] = ['message' => $message, 'type' => $type];
}

// Check folder permissions
if (!is_writable($cache_dir)) {
    logMessage("Error: system/cache/ is not writable", 'error');
    echo json_encode($log);
    exit;
}
if (!is_writable($web_dir)) {
    logMessage("Error: Root directory is not writable", 'error');
    echo json_encode($log);
    exit;
}

// Ensure PHP ZIP extension
if (!extension_loaded('zip')) {
    logMessage("Error: PHP ZIP extension is not enabled", 'error');
    echo json_encode($log);
    exit;
}

// Download update
logMessage("Downloading update...");
$fp = fopen($file, 'w+');
$ch = curl_init($update_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_FILE, $fp);
$result = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
fclose($fp);
if (!file_exists($file)) {
    logMessage("Failed to download update file. Error: $error", 'error');
    echo json_encode($log);
    exit;
}
logMessage("File downloaded successfully: $file");

// Extract update
logMessage("Extracting update...");
$zip = new ZipArchive();
if ($zip->open($file) === true) {
    $zip->extractTo($cache_dir);
    $zip->close();
    logMessage("Update extracted to: $folder");
} else {
    logMessage("Failed to extract update", 'error');
    echo json_encode($log);
    exit;
}

// Copy files
logMessage("Copying files...");
function copyFolder($from, $to) {
    $files = scandir($from);
    foreach ($files as $file) {
        if (!in_array($file, ['.', '..'])) {
            if (is_file($from . $file)) {
                copy($from . $file, $to . $file);
            } else {
                if (!file_exists($to . $file)) {
                    mkdir($to . $file);
                }
                copyFolder($from . $file . '/', $to . $file . '/');
            }
        }
    }
}
//copyFolder($folder, $web_dir);
logMessage("Files copied successfully!");

// Cleanup
logMessage("Cleaning up...");
unlink($file);
function deleteFolder($path) {
    $files = scandir($path);
    foreach ($files as $file) {
        if (!in_array($file, ['.', '..'])) {
            $filePath = $path . $file;
            is_dir($filePath) ? deleteFolder($filePath . '/') : unlink($filePath);
        }
    }
    rmdir($path);
}
deleteFolder($folder);
logMessage("Cleanup completed.");

// Update complete
logMessage("Update completed! Please refresh the page.");
echo json_encode($log);
