<?php

declare(strict_types=1);

/**
 * PPPHP geo-database updater — keeps the offline IP-location database fresh.
 *
 *   # daily (crontab) — DB-IP Lite publishes monthly, so a daily check is cheap
 *   # and only downloads when a newer build exists:
 *   #   30 4 * * * php /path/to/PpPhp/bin/geoip-update.php >> storage/logs/geoip.log 2>&1
 *
 * Downloads the free DB-IP Lite country database (no registration) when the
 * installed one is missing or older than 30 days, validates it, and installs it
 * atomically. Prints a one-line result; exits 0 (current / updated) or 1 (error).
 *
 * CLI only — web-cron hosts use the token-guarded /cron/geoip URL 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);

$__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   = \PpPhp\Core\Analytics\GeoIp::runScheduledUpdate($force);

echo '[' . date('Y-m-d H:i:s') . '] ' . ($res['message'] ?? 'done') . "\n";
exit(empty($res['success']) ? 1 : 0);
