<?php
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(0);

ini_set("log_errors", 1);
ini_set("error_log", __DIR__ . "/php-error.log");

require_once("../config/session.php");
require_once("../config/config.php");
require_once("../config/function.php");

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

function respond($success, $message) {
    echo json_encode(["success" => $success, "message" => $message]);
    exit;
}

if (isset($_SESSION["is_login"], $_SESSION["login_token"]) && $_SESSION["is_login"] === true && !empty($_SESSION["login_token"])) {

    $user_data = user_data($_SESSION["login_token"]);
    if (empty($user_data['user_id']) || $user_data['login_token'] !== $_SESSION["login_token"]) {
        session_unset();
        session_destroy();
        redirect("../members/logout", 0);
        exit;
    }

    if ($user_data['user_id'] == '1' && $user_data['usertype'] == 'Admin') {

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents("php://input"), true);

            if (!$input || !isset($input['update_url']) || !isset($input['version']) || !isset($input['extractPath'])) {
                respond(false, "❌ Invalid request received.");
            }

            $updateUrl = $input['update_url'];
            $newVersion = $input['version'];
            $extractPath = realpath(__DIR__ . '/' . $input['extractPath']);
            $zipFile = __DIR__ . '/update.zip';

            if (!$extractPath) {
                respond(false, "❌ Invalid extraction path.");
            }

            if (!is_dir($extractPath)) {
                if (!mkdir($extractPath, 0777, true)) {
                    respond(false, "❌ Failed to create directory: $extractPath");
                }
            }

            function downloadFile($url, $path) {
                $ch = curl_init($url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                $data = curl_exec($ch);

                if (curl_errno($ch)) {
                    respond(false, "❌ cURL Error: " . curl_error($ch));
                }

                file_put_contents($path, $data);
                return true;
            }

            $success = downloadFile($updateUrl, $zipFile);
            if (!$success) {
                respond(false, "❌ Failed to download update.");
            }

            // ✅ Manual extraction to detect file-level permission issues
            $zip = new ZipArchive;
            if ($zip->open($zipFile) === TRUE) {

                for ($i = 0; $i < $zip->numFiles; $i++) {
                    $entry = $zip->getNameIndex($i);
                    $fullPath = $extractPath . '/' . $entry;

                    if (substr($entry, -1) === '/') {
                        if (!is_dir($fullPath)) {
                            mkdir($fullPath, 0777, true);
                        }
                        continue;
                    }

                    $stream = $zip->getStream($entry);
                    if (!$stream) continue;

                    $dirPath = dirname($fullPath);
                    if (!is_dir($dirPath)) {
                        mkdir($dirPath, 0777, true);
                    }

                    $fp = @fopen($fullPath, 'w');
                    if (!$fp) {
                        fclose($stream);
                        $relativeFailPath = str_replace($_SERVER['DOCUMENT_ROOT'], 'public_html', $fullPath);
                        $zip->close();
                        unlink($zipFile);
                        respond(false, "❌ Extraction Failed: Permission denied in " . $relativeFailPath);
                    }

                    while (!feof($stream)) {
                        fwrite($fp, fread($stream, 1024));
                    }

                    fclose($fp);
                    fclose($stream);
                }

                $zip->close();
                unlink($zipFile);

            } else {
                respond(false, "❌ Failed to open ZIP file. The file may be corrupted.");
            }

            $sqlFile = $extractPath . '/update.sql';
            if (!file_exists($sqlFile)) {
                respond(false, "❌ update.sql not found in extracted files.");
            }

            mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
            try {
                $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
            } catch (Exception $e) {
                respond(false, "❌ Database connection failed: " . $e->getMessage());
            }

            $sqlQueries = file_get_contents($sqlFile);
            $queries = explode(";", $sqlQueries);

            foreach ($queries as $query) {
                $query = trim($query);
                if (!empty($query)) {
                    try {
                        $conn->query($query);
                    } catch (mysqli_sql_exception $e) {
                        $errorMessage = $e->getMessage();
                        if (strpos($errorMessage, 'Duplicate column name') !== false) {
                            continue;
                        }
                        respond(false, "❌ SQL Error: " . $errorMessage . " | Query: " . $query);
                    }
                }
            }

            unlink($sqlFile);
            $conn->close();
            file_put_contents(__DIR__ . '/current_version.txt', $newVersion);

            respond(true, "✅ Update applied successfully and database updated!");
        }

    } else {
        respond(false, "❌ Unauthorized Access.");
    }

} else {
    session_unset();
    session_destroy();
    redirect("../members/logout", 0);
    exit;
}
