<?php

declare(strict_types=1);

/**
 * PPPHP unattended updater — run from cron on a server you want to keep current.
 *
 *   # every 15 minutes (crontab):
 *   #   [slash]15 * * * * php /path/to/PpPhp/bin/pp-auto-update.php >> storage/logs/auto-update.log 2>&1
 *
 * It checks the signed update index, and if a newer release for this install's
 * edition is on offer, downloads + applies it with a restore point. Does nothing
 * unless automatic updates are enabled in the Update Engine console. Prints a
 * one-line result and exits 0 (up to date / applied) or 1 (error), so a cron
 * wrapper can alert on failure.
 *
 * CLI only — refuses to run over the web (use the token-guarded /platform/updates
 * /auto-run URL for web-cron hosts instead).
 */

if (PHP_SAPI !== 'cli') {
    http_response_code(404);
    exit("This script runs from the command line only.\n");
}

define('BASE_PATH', dirname(__DIR__));
error_reporting(E_ALL & ~E_DEPRECATED);

// Same clock as the web console (default Asia/Kathmandu) — one clock everywhere.
$__tz = (string) (((array) (is_file(BASE_PATH . '/config/app.php') ? require BASE_PATH . '/config/app.php' : []))['timezone'] ?? 'Asia/Kathmandu');
if ($__tz !== '') { @date_default_timezone_set($__tz); if (!defined('PP_TIMEZONE')) define('PP_TIMEZONE', $__tz); }

require_once BASE_PATH . '/core/Autoloader.php';
$autoloader = new \PpPhp\Core\Autoloader();
$autoloader->addNamespace('PpPhp\\Core\\', BASE_PATH . '/core/');
$autoloader->addNamespace('PpPhp\\Plugins\\', BASE_PATH . '/plugins/');
$autoloader->register();

require_once BASE_PATH . '/core/Helpers.php';

$dbConfig = require BASE_PATH . '/config/database.php';
$container = new \PpPhp\Core\Container();
$container->set(\PpPhp\Core\Config::class, new \PpPhp\Core\Config([
    'base_url'   => '',
    'assets_url' => '/assets',
    'db_config'  => new \PpPhp\Core\Config($dbConfig),
]));
\PpPhp\Core\DB::Init();
\PpPhp\Core\DB::SetConnection();

$force = in_array('--force', $argv, true);
$res   = (new \PpPhp\Core\Update\AutoUpdater(BASE_PATH))->run(['force' => $force]);

echo '[' . date('Y-m-d H:i:s') . '] ' . ($res['message'] ?? 'done') . "\n";
exit(strpos((string) ($res['message'] ?? ''), 'failed') !== false ? 1 : 0);
