<?php
/**
 * ChatDigi updater endpoint.
 *
 * Upload this file as:
 *   https://chatdigi.ai/updates/free/index.php
 * and/or:
 *   https://chatdigi.ai/updates/pro/index.php
 *
 * Upload the matching ChatDigi ZIP file into the same folder.
 * Keep directory browsing disabled.
 */

$secret_keys = [
    'free' => 'chatdigi-free-update-2026-key',
    'pro'  => 'chatdigi-pro-update-2026-key',
];

// Infer product from folder path, or accept ?product=free/pro.
$product = isset($_GET['product']) ? preg_replace('/[^a-z_]/', '', strtolower((string) $_GET['product'])) : basename(__DIR__);
if (!isset($secret_keys[$product])) {
    $product = 'free';
}

$secret_key = $secret_keys[$product];

$request_key = '';
if (isset($_GET['chatdigi_update_key'])) {
    $request_key = (string) $_GET['chatdigi_update_key'];
} elseif (isset($_GET['don_chat_update_key'])) {
    $request_key = (string) $_GET['don_chat_update_key'];
} elseif (!empty($_SERVER['HTTP_X_CHATDIGI_UPDATE_KEY'])) {
    $request_key = (string) $_SERVER['HTTP_X_CHATDIGI_UPDATE_KEY'];
} elseif (!empty($_SERVER['HTTP_X_DONSTUDIO_UPDATE_KEY'])) {
    $request_key = (string) $_SERVER['HTTP_X_DONSTUDIO_UPDATE_KEY'];
} elseif (!empty($_SERVER['HTTP_AUTHORIZATION']) && stripos($_SERVER['HTTP_AUTHORIZATION'], 'Bearer ') === 0) {
    $request_key = trim(substr($_SERVER['HTTP_AUTHORIZATION'], 7));
}

if (!hash_equals($secret_key, $request_key)) {
    chatdigi_status_header(403);
    header('Content-Type: text/plain; charset=utf-8');
    header('Cache-Control: private, no-store, no-cache, must-revalidate, max-age=0');
    echo 'Forbidden: invalid ChatDigi updater key';
    exit;
}

$action = isset($_GET['action']) ? preg_replace('/[^a-z_]/', '', strtolower((string) $_GET['action'])) : 'info';
$dir = __DIR__;
$zips = glob($dir . '/*.zip');

if (!$zips) {
    chatdigi_status_header(404);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['error' => 'No ZIP files found']);
    exit;
}

usort($zips, function ($a, $b) {
    $time_compare = filemtime($b) <=> filemtime($a);
    if ($time_compare !== 0) return $time_compare;
    return strcmp(basename($b), basename($a));
});

$latest = $zips[0];
$latest_basename = basename($latest);

if ($action === 'download') {
    $requested = isset($_GET['file']) ? basename((string) $_GET['file']) : $latest_basename;
    $file = $dir . '/' . $requested;

    if (!is_file($file) || strtolower(pathinfo($file, PATHINFO_EXTENSION)) !== 'zip') {
        chatdigi_status_header(404);
        header('Content-Type: text/plain; charset=utf-8');
        echo 'ZIP not found';
        exit;
    }

    while (ob_get_level()) ob_end_clean();

    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="' . basename($file) . '"');
    header('Content-Length: ' . filesize($file));
    header('Cache-Control: private, no-store, no-cache, must-revalidate, max-age=0');
    header('X-Content-Type-Options: nosniff');
    readfile($file);
    exit;
}

$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'chatdigi.ai';
$path = strtok($_SERVER['REQUEST_URI'] ?? ('/updates/' . $product . '/'), '?');
$base_url = rtrim($scheme . '://' . $host . $path, '/');
$base_url = preg_replace('#/index\.php$#i', '', $base_url);

$download_url = $base_url . '/?action=download&product=' . rawurlencode($product) . '&chatdigi_update_key=' . rawurlencode($secret_key) . '&file=' . rawurlencode($latest_basename);

// Optional: infer version from filename like chatdigi-ai-free-1.0.2.zip or chatdigi-ai-4.2.13.zip
$version = '';
if (preg_match('/(?:free-|ai\.|ai-)(\d+\.\d+\.\d+(?:\.\d+)?)/i', $latest_basename, $m)) {
    $version = $m[1];
}

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: private, no-store, no-cache, must-revalidate, max-age=0');
header('X-Content-Type-Options: nosniff');
echo json_encode([
    'product' => $product,
    'filename' => $latest_basename,
    'last_modified' => filemtime($latest),
    'last_modified_human' => date('Y-m-d H:i:s', filemtime($latest)),
    'download_url' => $download_url,
    'version' => $version,
]);
exit;

function chatdigi_status_header($code) {
    if (function_exists('http_response_code')) {
        http_response_code($code);
    } else {
        header('HTTP/1.1 ' . (int) $code);
    }
}
