<?php
include 'db.php';
include 'linkrel.php';
// Removed sidebar.php include for full-width content
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";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>System Update - ITR POS</title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<div class="main-wrapper">
  <div class="page-wrapper">
    <div class="content">
      <div class="page-header d-flex justify-content-between align-items-center mb-4">
        <div class="page-title">
          <h4><i class="fas fa-sync-alt text-success me-2"></i>System Update</h4>
          <p class="text-muted mb-0">Your ITR POS is being updated. Please review the log below.</p>
        </div>
        <img src="assets/img/logo.png" alt="Logo" style="height: 48px;">
      </div>
      <div class="card shadow-sm border-start border-success border-3 mb-4">
        <div class="card-body">
          <div class="fw-bold mb-2">Update Progress</div>
          <div class="progress mb-3" style="height: 24px;">
            <div class="progress-bar bg-success" role="progressbar" style="width: 100%">Completed</div>
          </div>
          <div class="mb-3"><span class="fw-bold text-primary">Update Log</span></div>
          <div class="update-log" style="max-height: 400px; overflow-y: auto; background: #f6f6f6; border-radius: 6px; padding: 18px;">
            <pre style="background: none; border: none; padding: 0; margin: 0; font-size: 1rem;">
<?php
// The update log content will be displayed here
?>
            </pre>
          </div>
          <div class="mt-4 text-end">
            <span class="text-success fw-bold me-3">Update process completed. Please review the log above for details.</span>
            <a href="index.php" class="btn btn-primary">Back to Home</a>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<script src="assets/js/bootstrap.bundle.min.js"></script>
<script src="assets/js/feather.min.js"></script>
<script>if(window.feather) feather.replace();</script>
</body>
</html>