<?php

declare(strict_types=1);

/**
 * PPPHP visitor-log pruner — enforces the analytics retention window off the
 * request path, so a busy site never pays a full-table DELETE on a page load.
 *
 *   # daily (crontab):
 *   #   40 4 * * * php /path/to/PpPhp/bin/analytics-prune.php >> storage/logs/analytics.log 2>&1
 *
 * Deletes visits (and their journey hits) older than the configured retention
 * (Visitors → Settings → "Keep visits for N days"; 0 = keep forever). Prints a
 * one-line result; exits 0 always (nothing to prune is success).
 *
 * CLI only — web-cron hosts use the token-guarded /cron/analytics-prune URL.
 */

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();

$removed = \PpPhp\Core\Analytics\VisitorLog::prune();
echo '[' . date('Y-m-d H:i:s') . '] pruned ' . $removed . " expired visit(s).\n";
exit(0);
