#!/usr/bin/env php
<?php
declare(strict_types=1);

/*
 * Malongo Arabia CLI.
 *   php bin/console migrate                 Apply pending database migrations
 *   php bin/console seed base|demo          Run a seeder (database/seeds/<name>.php)
 *   php bin/console make:admin <email> <password> [first] [last]   Create/upgrade a super admin
 *   php bin/console cache:clear             Clear file cache + asset bundles
 *   php bin/console routes                  List routes
 *   php bin/console cron                    Housekeeping (prune carts, rate limits) — schedule hourly in cPanel
 */

if (PHP_SAPI !== 'cli') {
    exit(1);
}

define('BASE_PATH', dirname(__DIR__));
require BASE_PATH . '/app/bootstrap.php';

use App\Core\App;
use App\Core\Cache;
use App\Core\DB;
use App\Core\Migrator;
use App\Core\RateLimiter;
use App\Core\Router;

$cmd = $argv[1] ?? 'help';
$args = array_slice($argv, 2);
$out = static fn (string $s) => fwrite(STDOUT, $s . PHP_EOL);

try {
    switch ($cmd) {
        case 'migrate':
            $done = Migrator::migrate();
            $out($done ? 'Applied: ' . implode(', ', $done) : 'Nothing to migrate.');
            break;

        case 'seed':
            $name = $args[0] ?? 'base';
            $file = DATABASE_PATH . '/seeds/' . preg_replace('/[^a-z0-9_-]/', '', $name) . '.php';
            if (!is_file($file)) {
                throw new RuntimeException("Seeder not found: {$name}");
            }
            $fn = require $file;
            $fn();
            \App\Core\Settings::flush();
            Cache::flush();
            $out("Seeded: {$name}");
            break;

        case 'make:admin':
            [$email, $password] = [$args[0] ?? '', $args[1] ?? ''];
            if (!filter_var($email, FILTER_VALIDATE_EMAIL) || strlen($password) < 8) {
                throw new RuntimeException('Usage: make:admin <email> <password(min 8)> [first] [last]');
            }
            $roleId = (int) DB::value("SELECT id FROM roles WHERE slug = 'super_admin'");
            if ($roleId === 0) {
                throw new RuntimeException('Run "seed base" first.');
            }
            $existing = DB::value('SELECT id FROM users WHERE email = :e', ['e' => strtolower($email)]);
            $data = [
                'role_id' => $roleId, 'password_hash' => password_hash($password, PASSWORD_DEFAULT),
                'first_name' => $args[2] ?? 'Store', 'last_name' => $args[3] ?? 'Admin', 'status' => 'active', 'locale' => 'en',
            ];
            if ($existing) {
                DB::update('users', $data + ['updated_at' => DB::now()], ['id' => $existing]);
                $out("Updated super admin #{$existing}");
            } else {
                $id = DB::insert('users', $data + ['email' => strtolower($email), 'created_at' => DB::now(), 'email_verified_at' => DB::now()]);
                $out("Created super admin #{$id}");
            }
            break;

        case 'cache:clear':
            Cache::flush();
            foreach (glob(PUBLIC_PATH . '/assets/cache/*.{css,js}', GLOB_BRACE) ?: [] as $f) {
                @unlink($f);
            }
            $out('Cache cleared.');
            break;

        case 'routes':
            $router = new Router();
            App::loadRoutes($router);
            foreach ($router->routes() as $r) {
                $out(str_pad(implode('|', array_diff($r['methods'], ['HEAD'])), 10) . str_pad($r['pattern'], 60) . $r['name'] . (is_array($r['handler']) ? '  → ' . $r['handler'][0] . '@' . $r['handler'][1] : ''));
            }
            break;

        case 'cron':
            $carts = DB::exec('DELETE FROM carts WHERE user_id IS NULL AND updated_at < DATE_SUB(NOW(), INTERVAL 30 DAY)');
            $limits = RateLimiter::prune();
            $out("Pruned {$carts} guest carts, {$limits} rate-limit rows.");
            $hook = APP_PATH . '/Services/CronService.php';
            if (is_file($hook) && class_exists(\App\Services\CronService::class)) {
                \App\Services\CronService::run($out);
            }
            break;

        default:
            $out(file_get_contents(__FILE__) !== false ? 'Commands: migrate | seed base|demo | make:admin <email> <password> | cache:clear | routes | cron' : '');
    }
} catch (Throwable $e) {
    fwrite(STDERR, 'Error: ' . $e->getMessage() . PHP_EOL);
    exit(1);
}
