<?php

/**
 * ONE-TIME deploy setup script. Runs migrations, seeds demo data, and
 * primes the config/route/event caches — everything `artisan` would do,
 * exposed over HTTP because this host has no terminal access.
 *
 * DELETE THIS FILE IMMEDIATELY AFTER A SUCCESSFUL RUN. Anyone who guesses
 * or intercepts the token below can re-run migrations/seeders against your
 * live database for as long as this file exists.
 */

define('SETUP_SECRET', 'a2a3d7b0c572b6ff36f756802701fe848f283922b701fa8c');

if (! hash_equals(SETUP_SECRET, $_GET['token'] ?? '')) {
    http_response_code(403);
    exit('Forbidden.');
}

require __DIR__.'/../vendor/autoload.php';

/** @var \Illuminate\Foundation\Application $app */
$app = require_once __DIR__.'/../bootstrap/app.php';

/** @var \Illuminate\Contracts\Console\Kernel $kernel */
$kernel = $app->make(\Illuminate\Contracts\Console\Kernel::class);
$kernel->bootstrap();

header('Content-Type: text/plain; charset=utf-8');

function runStep(string $label, callable $fn): void
{
    echo "\n=== {$label} ===\n";

    try {
        $fn();
        echo "OK\n";
    } catch (\Throwable $e) {
        echo 'FAILED: '.$e->getMessage()."\n";
        echo $e->getTraceAsString()."\n";
        echo "\n--- Stopping here. Fix the error above, then reload this page. ---\n";
        exit(1);
    }
}

echo "ChMS one-time deploy setup\n";
echo str_repeat('=', 40)."\n";

runStep('Migrating database', function () use ($kernel) {
    $kernel->call('migrate', ['--force' => true]);
    echo \Illuminate\Support\Facades\Artisan::output();
});

runStep('Seeding demo data (DevSeeder)', function () use ($kernel) {
    $kernel->call('db:seed', ['--class' => 'DevSeeder', '--force' => true]);
    echo \Illuminate\Support\Facades\Artisan::output();
});

runStep('Caching config', function () use ($kernel) {
    $kernel->call('config:cache');
    echo \Illuminate\Support\Facades\Artisan::output();
});

runStep('Caching routes', function () use ($kernel) {
    $kernel->call('route:cache');
    echo \Illuminate\Support\Facades\Artisan::output();
});

runStep('Caching events', function () use ($kernel) {
    $kernel->call('event:cache');
    echo \Illuminate\Support\Facades\Artisan::output();
});

echo "\n".str_repeat('=', 40)."\n";
echo "All done.\n\n";
echo "Login as super_admin: admin@example.com / password\n";
echo "(also seeded: region.admin@, branch.admin@, data.clerk@, viewer@example.com — all password 'password')\n\n";
echo "!!! DELETE THIS FILE (public/setup.php) RIGHT NOW VIA FILE MANAGER !!!\n";
