<?php
include 'functions.php';

$server_url = 'https://itresources.com.pk/itr/api/get_latest_update.php';
$current_version = trim(@file_get_contents('version.txt'));

if (!$current_version) {
    die("version.txt missing or empty.\n");
}

// Fetch updates after current version
$response = file_get_contents($server_url . '?current_version=' . urlencode($current_version));
$data = json_decode($response, true);

if (empty($data['update_available']) || empty($data['updates'])) {
    die("No updates available.\n");
}

foreach ($data['updates'] as $update) {
    $version = $update['version'];
    $zip_url = $update['zip_path'];
    $zip_file = "update_temp.zip";

    echo "\n==============================\n";
    echo "Applying update: $version\n";

    // Download update ZIP
    $zip_data = file_get_contents($zip_url);
    if ($zip_data === false) {
        echo "❌ Failed to download ZIP for version $version.\n";
        continue;
    }
    file_put_contents($zip_file, $zip_data);
    echo "✅ Downloaded update ZIP.\n";

    // --- New: Download SQL file if sql_path is provided ---
    $sql_url = $update['sql_path'] ?? '';
    if ($sql_url) {
        $sql_file = __DIR__ . '/db/update_' . str_replace('.', '', $version) . '.sql';
        if (!file_exists($sql_file)) { // download only if not exists
            $sql_data = file_get_contents($sql_url);
            if ($sql_data !== false) {
                file_put_contents($sql_file, $sql_data);
                echo "✅ Downloaded SQL file for version $version.\n";
            } else {
                echo "⚠️ Failed to download SQL file for version $version.\n";
            }
        }
    }
    // -------------------------------------------------------

    // Backup current files
    $backup_dir = "backup/v$current_version/";
    @mkdir($backup_dir, 0777, true);

    $zip = new ZipArchive;
    if ($zip->open($zip_file) === TRUE) {
        for ($i = 0; $i < $zip->numFiles; $i++) {
            $entry = $zip->getNameIndex($i);
            if (substr($entry, -1) === '/') continue;

            $clean_path = preg_replace('#^[^/]+/#', '', $entry); // remove folder name
            $full_path = __DIR__ . '/' . $clean_path;

            // Backup original file
            if (file_exists($full_path)) {
                $backup_path = $backup_dir . $clean_path;
                @mkdir(dirname($backup_path), 0777, true);
                copy($full_path, $backup_path);
            }

            // Extract updated file
            $source = $zip->getStream($entry);
            if ($source) {
                @mkdir(dirname($full_path), 0777, true);
                $out = fopen($full_path, 'w');
                while (!feof($source)) {
                    fwrite($out, fread($source, 4096));
                }
                fclose($out);
                fclose($source);
            } else {
                echo "⚠️ Failed to extract: $entry\n";
            }
        }
        $zip->close();
        echo "✅ Files extracted and applied.\n";

        // Optional: Apply SQL update if exists
        $sql_path = __DIR__ . '/db/update_' . str_replace('.', '', $version) . '.sql';
        if (file_exists($sql_path)) {
            run_sql_file($sql_path);
            echo "✅ Database updated for version $version.\n";
        } else {
            echo "ℹ️ No SQL file for version $version.\n";
        }

        // Update version file
        file_put_contents('version.txt', $version);
        echo "✅ Local version updated to $version.\n";

        // Log update
        file_put_contents('update_log.txt', "Updated to $version on " . date('Y-m-d H:i:s') . "\n", FILE_APPEND);

        // Clean up
        unlink($zip_file);
    } else {
        echo "❌ Failed to open ZIP for version $version.\n";
    }
}
