<?php
/**
 * Bryant Trust short links — the front door.
 *
 * Every request to the domain arrives here, because .htaccess sends it here.
 * Three things can happen: a known slug redirects, the admin screen opens, or
 * anything else goes to the home destination. There is no fourth case and no
 * 404 page: a domain whose only job is short links should never leave someone
 * staring at an error because a letter was mistyped.
 */
declare(strict_types=1);
require __DIR__ . '/lib.php';

$path = trim((string) parse_url((string) ($_SERVER['REQUEST_URI'] ?? '/'), PHP_URL_PATH), '/');
$cfg  = btl_config();

/* --- the admin screen, and the one-time setup behind it ------------- */
if ($path === 'admin' || strpos($path, 'admin/') === 0) {
    require __DIR__ . '/admin.php';
    exit;
}

/* --- a check you can run from anywhere, including from a phone ------ */
if ($path === 'health') {
    header('Content-Type: text/plain; charset=utf-8');
    $ok = static fn(bool $b): string => $b ? 'yes' : 'NO';
    echo "Bryant Trust short links\n";
    echo "PHP version       : " . PHP_VERSION . "\n";
    echo "PDO SQLite        : " . $ok(in_array('sqlite', PDO::getAvailableDrivers(), true)) . "\n";
    echo "data/ writable    : " . $ok(is_writable(BTL_DATA)) . "\n";
    echo "set up            : " . $ok(btl_is_set_up()) . "\n";
    echo "served over https : " . $ok(btl_is_https()) . "\n";
    if (btl_is_set_up()) {
        try {
            echo "links stored      : " . (int) btl_db()->query('SELECT COUNT(*) FROM links')->fetchColumn() . "\n";
        } catch (Throwable $e) {
            echo "database          : FAILED — " . $e->getMessage() . "\n";
        }
    }
    exit;
}

/* --- nothing is set up yet: say so, rather than redirecting nowhere - */
if (!btl_is_set_up()) {
    header('Content-Type: text/html; charset=utf-8');
    echo '<!doctype html><meta charset="utf-8"><title>Not set up yet</title>'
       . '<body style="font:16px/1.6 system-ui;max-width:34rem;margin:12vh auto;padding:0 1rem">'
       . '<h1 style="font-weight:600">Almost there</h1>'
       . '<p>The short-link service is installed but has not been set up. '
       . 'Open <a href="/admin">/admin</a> to choose a password and a home destination.</p>';
    exit;
}

/* --- the home page is not a page: it is wherever you point it ------- */
if ($path === '' || $path === 'favicon.ico' || $path === 'robots.txt') {
    if ($path === 'robots.txt') {
        // Nothing here is for indexing; every URL is a redirect.
        header('Content-Type: text/plain; charset=utf-8');
        echo "User-agent: *\nDisallow: /\n";
        exit;
    }
    btl_redirect($cfg['home'] !== '' ? $cfg['home'] : 'https://' . (string) ($_SERVER['HTTP_HOST'] ?? ''), 'home');
}

/* --- the actual job ------------------------------------------------- */
$slug = btl_slug($path);
try {
    $st = btl_db()->prepare('SELECT id, target FROM links WHERE slug = ?');
    $st->execute([$slug]);
    $row = $st->fetch();
} catch (Throwable $e) {
    // A broken database must still send the visitor somewhere.
    btl_redirect($cfg['home'] !== '' ? $cfg['home'] : btl_base_url(), 'error');
}

if (!$row) {
    // A mistyped or retired link lands on the home destination rather than an
    // error. The header is the difference between "never existed" and
    // "deliberately pointed at the home page", which matters when a slug is
    // about to be printed and cannot be checked any other way from outside.
    btl_redirect($cfg['home'] !== '' ? $cfg['home'] : btl_base_url(), 'miss');
}

// Counted before the redirect, so a slow browser cannot lose the click.
try {
    btl_record_click($slug, (int) $row['id']);
    btl_prune();
} catch (Throwable $e) {
    // Never let bookkeeping cost somebody their destination.
}
btl_redirect((string) $row['target'], 'hit');
