<?php

/**
 * SmarterASP has no SSH: upload this file to public/migrate-once.php (FTP), then:
 *
 * 1. In Laravel ROOT .env add (generate a random string):
 *    MIGRATE_ONCE_KEY=your-long-random-secret
 *
 * 2. Ensure DB_* in .env matches MySQL Manager (host, database, user, password).
 *
 * 3. Visit once in browser:
 *    https://barberiasr.app.viansoft.com/migrate-once.php?key=your-long-random-secret
 *
 * 4. DELETE public/migrate-once.php from the server immediately after success.
 */

declare(strict_types=1);

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

$keyFromUrl = (string) ($_GET['key'] ?? '');

/**
 * Find Laravel base path by searching upwards for bootstrap/app.php and vendor/autoload.php.
 */
function resolveBaseDir(string $startDir): ?string
{
    $dir = realpath($startDir) ?: $startDir;
    for ($i = 0; $i < 6; $i++) {
        $bootstrap = $dir . DIRECTORY_SEPARATOR . 'bootstrap' . DIRECTORY_SEPARATOR . 'app.php';
        $autoload = $dir . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
        if (is_file($bootstrap) && is_file($autoload)) {
            return $dir;
        }
        $parent = dirname($dir);
        if ($parent === $dir) {
            break;
        }
        $dir = $parent;
    }

    return null;
}

/**
 * Read MIGRATE_ONCE_KEY from .env file path.
 */
function readKeyFromEnvFile(string $envPath): ?string
{
    if (! is_readable($envPath)) {
        return null;
    }
    $lines = file($envPath, FILE_IGNORE_NEW_LINES);
    if ($lines === false) {
        return null;
    }
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '' || str_starts_with($line, '#')) {
            continue;
        }
        if (str_starts_with($line, 'MIGRATE_ONCE_KEY=')) {
            return trim(substr($line, strlen('MIGRATE_ONCE_KEY=')), " \t\"'");
        }
    }

    return null;
}

$baseDir = resolveBaseDir(__DIR__);
if (! $baseDir) {
    http_response_code(500);
    exit("Could not resolve Laravel base directory.\n");
}

require $baseDir . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
$app = require_once $baseDir . DIRECTORY_SEPARATOR . 'bootstrap' . DIRECTORY_SEPARATOR . 'app.php';

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

$expectedKey = (string) (
    getenv('MIGRATE_ONCE_KEY')
    ?: ($_ENV['MIGRATE_ONCE_KEY'] ?? '')
    ?: ($_SERVER['MIGRATE_ONCE_KEY'] ?? '')
);
if ($expectedKey === '') {
    $expectedKey = (string) (readKeyFromEnvFile($baseDir . DIRECTORY_SEPARATOR . '.env') ?? '');
}

if ($expectedKey === '') {
    http_response_code(403);
    exit("Set MIGRATE_ONCE_KEY in .env or server environment first.\n");
}

if (! hash_equals($expectedKey, $keyFromUrl)) {
    http_response_code(403);
    exit("Forbidden\n");
}

try {
    $kernel->call('migrate', ['--force' => true]);
    echo $kernel->output();
    echo "\n--- Done. DELETE public/migrate-once.php now. ---\n";
} catch (Throwable $e) {
    http_response_code(500);
    echo $e->getMessage() . "\n" . $e->getTraceAsString();
}
