<?php
declare(strict_types=1);
require_once __DIR__.'/Storybook.php';
require_once __DIR__.'/Wiki.php';
ini_set('display_errors', '0');
ini_set('log_errors', '1');
ini_set('error_log', dataDir().'/php-errors.log');
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: same-origin');
header("Content-Security-Policy: default-src 'self'; img-src 'self' https://auth.timfalken.com; style-src 'self'; script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'");
header('Cache-Control: no-store');

function dataDir(): string {
    $env = getenv('VERHALENBOEK_DATA_DIR');
    if (is_string($env) && $env !== '') return rtrim($env, '/');
    return dirname(__DIR__).'/data';
}

function db(): PDO {
    static $db;
    if ($db) return $db;
    $dir = dataDir();
    if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) throw new RuntimeException('De datamap moet bestaan en schrijfbaar zijn.');
    $db = new PDO('sqlite:'.$dir.'/verhalenboek.sqlite', null, null, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
    $db->exec('PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;');
    $db->exec('CREATE TABLE IF NOT EXISTS users (
        id TEXT PRIMARY KEY,
        name TEXT NOT NULL,
        role TEXT NOT NULL DEFAULT \'user\' CHECK(role IN (\'admin\',\'user\')),
        theme TEXT NOT NULL DEFAULT \'system\' CHECK(theme IN (\'system\',\'light\',\'dark\')),
        font TEXT NOT NULL DEFAULT \'serif\' CHECK(font IN (\'serif\',\'sans\',\'rounded\')),
        created INTEGER NOT NULL
      );
      CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, payload TEXT NOT NULL, expires INTEGER NOT NULL);
      CREATE TABLE IF NOT EXISTS days (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        date TEXT NOT NULL UNIQUE,
        title TEXT NOT NULL,
        created INTEGER NOT NULL,
        updated INTEGER NOT NULL
      );
      CREATE TABLE IF NOT EXISTS stories (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
        position INTEGER NOT NULL CHECK(position BETWEEN 1 AND 3),
        title TEXT NOT NULL,
        created INTEGER NOT NULL,
        updated INTEGER NOT NULL,
        UNIQUE(day_id, position)
      );
      CREATE TABLE IF NOT EXISTS paragraphs (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        story_id INTEGER NOT NULL REFERENCES stories(id) ON DELETE CASCADE,
        position INTEGER NOT NULL CHECK(position >= 1),
        body TEXT NOT NULL,
        UNIQUE(story_id, position)
      );
      CREATE TABLE IF NOT EXISTS reads (
        user_id TEXT NOT NULL REFERENCES users(id),
        day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
        read_at INTEGER NOT NULL,
        PRIMARY KEY(user_id, day_id)
      );
      CREATE TABLE IF NOT EXISTS api_keys (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        user_id TEXT NOT NULL REFERENCES users(id),
        name TEXT NOT NULL,
        token_hash TEXT NOT NULL UNIQUE,
        token_prefix TEXT NOT NULL,
        token_cipher TEXT NOT NULL DEFAULT \'\',
        created INTEGER NOT NULL,
        revoked INTEGER
      );
      CREATE TABLE IF NOT EXISTS wiki_categories (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        slug TEXT NOT NULL UNIQUE,
        title TEXT NOT NULL,
        position INTEGER NOT NULL,
        created INTEGER NOT NULL,
        updated INTEGER NOT NULL
      );
      CREATE TABLE IF NOT EXISTS wiki_pages (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        category_id INTEGER NOT NULL REFERENCES wiki_categories(id),
        slug TEXT NOT NULL UNIQUE,
        title TEXT NOT NULL,
        content TEXT NOT NULL,
        position INTEGER NOT NULL,
        created INTEGER NOT NULL,
        updated INTEGER NOT NULL
      );
      CREATE INDEX IF NOT EXISTS wiki_pages_category ON wiki_pages(category_id, position);');
    $columns = array_column($db->query('PRAGMA table_info(api_keys)')->fetchAll(), 'name');
    if (!in_array('token_cipher', $columns, true)) {
        $db->exec("ALTER TABLE api_keys ADD COLUMN token_cipher TEXT NOT NULL DEFAULT ''");
    }
    return $db;
}

function query(string $sql, array $args = []): PDOStatement {
    $statement = db()->prepare($sql);
    $statement->execute($args);
    return $statement;
}

final class DatabaseSessions implements SessionHandlerInterface {
    public function open(string $path, string $name): bool { return true; }
    public function close(): bool { return true; }
    public function read(string $id): string|false {
        return query('SELECT payload FROM sessions WHERE id=? AND expires>?', [$id, time()])->fetchColumn() ?: '';
    }
    public function write(string $id, string $data): bool {
        query('INSERT OR REPLACE INTO sessions (id, payload, expires) VALUES (?,?,?)', [$id, $data, time() + 86400]);
        return true;
    }
    public function destroy(string $id): bool {
        query('DELETE FROM sessions WHERE id=?', [$id]);
        return true;
    }
    public function gc(int $max_lifetime): int|false {
        return query('DELETE FROM sessions WHERE expires<?', [time()])->rowCount();
    }
}

function localDev(): bool {
    $host = parse_url('http://'.($_SERVER['HTTP_HOST'] ?? ''), PHP_URL_HOST);
    return is_string($host) && in_array(strtolower($host), ['localhost', '127.0.0.1', '[::1]'], true)
        && in_array($_SERVER['REMOTE_ADDR'] ?? '', ['127.0.0.1', '::1'], true);
}

function config(): array {
    $dir = dataDir();
    $path = $dir.'/config.php';
    if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) throw new RuntimeException('De datamap moet schrijfbaar zijn om de configuratie te maken.');
    $lock = fopen($dir.'/config.lock', 'c');
    if ($lock === false) throw new RuntimeException('De datamap moet schrijfbaar zijn om de configuratie te maken.');
    try {
        if (!flock($lock, LOCK_EX)) throw new RuntimeException('De configuratie kon niet worden vergrendeld.');
        if (!file_exists($path)) {
            $secret = bin2hex(random_bytes(32));
            $template = <<<PHP
<?php
// Vul deze waarden op deze server in. Lege velden gebruiken omgevingsvariabelen.
// Productie-URL: https://projects.timfalken.com/verhaaltjesboek
// client_id is het geregistreerde domein, meestal projects.timfalken.com.
// Het geheim komt uit https://auth.timfalken.com/admin en hoort alleen in dit bestand.
// key_secret versleutelt API-sleutels zodat een beheerder ze opnieuw kan tonen. Laat die staan.
return [
    'base_url' => '',
    'client_id' => '',
    'client_secret' => '',
    'key_secret' => '$secret',
];

PHP;
            if (file_put_contents($path, $template) !== strlen($template)) throw new RuntimeException('data/config.php kon niet worden gemaakt.');
        }
        $values = require $path;
        if (!is_array($values)) throw new RuntimeException('data/config.php moet een array teruggeven.');
        $values = ensureKeySecret($path, $values);
    } finally {
        flock($lock, LOCK_UN);
        fclose($lock);
    }
    foreach (['base_url' => 'VERHALENBOEK_BASE_URL', 'client_id' => 'VERHALENBOEK_CLIENT_ID', 'client_secret' => 'VERHALENBOEK_CLIENT_SECRET'] as $key => $env) {
        if (($values[$key] ?? '') === '') $values[$key] = getenv($env) ?: '';
    }
    return $values;
}

function ensureKeySecret(string $path, array $values): array {
    $secret = $values['key_secret'] ?? '';
    if (is_string($secret) && preg_match('/^[a-f0-9]{64}$/', $secret)) return $values;
    $secret = bin2hex(random_bytes(32));
    $values['key_secret'] = $secret;
    $raw = file_get_contents($path);
    if (!is_string($raw)) throw new RuntimeException('data/config.php kon niet worden gelezen.');
    if (preg_match("/'key_secret'\\s*=>\\s*'[^']*'/", $raw)) {
        $updated = preg_replace("/'key_secret'\\s*=>\\s*'[^']*'/", "'key_secret' => '".$secret."'", $raw, 1);
    } else {
        $updated = preg_replace("/(\\r?\\n)(\\];)/", "$1    'key_secret' => '".$secret."',$1$2", $raw, 1);
    }
    if (!is_string($updated) || !str_contains($updated, $secret) || file_put_contents($path, $updated) !== strlen($updated)) {
        throw new RuntimeException('key_secret kon niet in data/config.php worden gezet.');
    }
    return $values;
}

function authPublicBase(): string {
    if (localDev()) return baseUrl();
    $base = rtrim((string)(config()['base_url'] ?? ''), '/');
    if (str_starts_with($base, 'https://')) return $base;
    $env = getenv('VERHALENBOEK_BASE_URL');
    if (is_string($env) && str_starts_with($env = rtrim($env, '/'), 'https://')) return $env;
    return '';
}

function authHint(string $kind): string {
    $base = authPublicBase();
    $keys = ($base !== '' ? $base : '').'/#/sleutels';
    $docs = ($base !== '' ? $base.'/' : '').'docs.php';
    $how = 'Stuur de header Authorization: Bearer vb_… met een API-sleutel. Een beheerder maakt sleutels aan onder Sleutels op '.$keys.'. Uitleg: '.$docs;
    return match ($kind) {
        'missing' => 'Er is geen Authorization-header. '.$how,
        'format' => 'De Authorization-header heeft het verkeerde formaat. Gebruik Bearer, gevolgd door vb_ en 64 hexadecimale tekens. '.$how,
        'rejected' => 'Deze API-sleutel is onbekend of ingetrokken. '.$how,
        'writer' => 'Dit mag alleen met een API-sleutel of als beheerder. '.$how,
        'admin' => 'Sleutels beheren kan alleen als ingelogde beheerder, niet met een API-sleutel. Open Sleutels op '.$keys.'. Uitleg: '.$docs,
        'users' => 'Gebruikers beheren kan alleen als ingelogde beheerder, niet met een API-sleutel. Open Beheer op '.($base !== '' ? $base : '').'/#/beheer. Uitleg: '.$docs,
        default => $how,
    };
}

function baseUrl(): string {
    if (localDev()) {
        $dir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/');
        if ($dir === '/' || $dir === '.') $dir = '';
        return 'http://'.$_SERVER['HTTP_HOST'].$dir;
    }
    $base = rtrim((string)config()['base_url'], '/');
    if (!str_starts_with($base, 'https://')) throw new RuntimeException("Zet 'base_url' in data/config.php op de HTTPS-URL van deze installatie, of zet VERHALENBOEK_BASE_URL. De datamap wordt niet meegedeployed.");
    return $base;
}

function assetVersion(): string {
    static $version;
    if ($version !== null) return $version;
    $file = dirname(__DIR__).'/asset-version.txt';
    if (is_readable($file)) {
        $hash = trim((string)file_get_contents($file));
        if ($hash !== '' && preg_match('/^[0-9a-f]{7,64}$/i', $hash)) return $version = $hash;
    }
    $env = getenv('CI_COMMIT_SHA') ?: getenv('VERHALENBOEK_ASSET_VERSION') ?: '';
    if (is_string($env) && preg_match('/^[0-9a-f]{7,64}$/i', trim($env))) return $version = trim($env);
    $git = dirname(__DIR__, 2).'/.git';
    if (is_dir($git)) {
        $out = @shell_exec('git -C '.escapeshellarg(dirname($git)).' rev-parse HEAD 2>/dev/null');
        if (is_string($out) && preg_match('/^[0-9a-f]{7,64}$/i', trim($out))) return $version = trim($out);
    }
    $js = dirname(__DIR__).'/assets/app.js';
    return $version = is_file($js) ? (string)filemtime($js) : '0';
}

function assetUrl(string $path): string {
    $path = ltrim($path, '/');
    $version = rawurlencode(assetVersion());
    return str_contains($path, '?') ? $path.'&v='.$version : $path.'?v='.$version;
}

function pwaHead(): void {
    $icon = htmlspecialchars(assetUrl('assets/favicon.svg'), ENT_QUOTES);
    $png32 = htmlspecialchars(assetUrl('assets/favicon-32.png'), ENT_QUOTES);
    $png16 = htmlspecialchars(assetUrl('assets/favicon-16.png'), ENT_QUOTES);
    $mask = htmlspecialchars(assetUrl('assets/mask-icon.svg'), ENT_QUOTES);
    $script = htmlspecialchars(assetUrl('assets/pwa.js'), ENT_QUOTES);
    echo <<<HTML
<link rel="icon" href="{$icon}" type="image/svg+xml" sizes="any">
<link rel="icon" href="{$png32}" type="image/png" sizes="32x32">
<link rel="icon" href="{$png16}" type="image/png" sizes="16x16">
<link rel="apple-touch-icon" href="assets/apple-touch-icon.png" sizes="180x180">
<link rel="manifest" href="manifest.webmanifest">
<link rel="mask-icon" href="{$mask}" color="#3a5fc8">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="Verhalenboek">
<meta name="apple-mobile-web-app-status-bar-style" content="default">
<script src="{$script}"></script>

HTML;
}

function authRequest(string $path, ?array $form = null, ?string $token = null): array {
    $ch=curl_init('https://auth.timfalken.com'.$path);
    $headers = ['Accept: application/json', 'User-Agent: Verhalenboek/1.0'];
    if ($token) $headers[] = 'Authorization: Bearer '.$token;
    curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15, CURLOPT_HTTPHEADER => $headers]);
    if ($form !== null) curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query($form)]);
    $body = curl_exec($ch);
    $status = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    curl_close($ch);
    $data = is_string($body) ? json_decode($body, true) : null;
    if ($status !== 200 || !is_array($data)) throw new RuntimeException('De authenticatiedienst is niet bereikbaar of de sessie is verlopen. Log opnieuw in.');
    return $data;
}

/** @return array{0:string,1:string} */
function authIdentity(array $profile): array {
    if (!isset($profile['id'], $profile['username']) || !is_string($profile['username'])) {
        throw new RuntimeException('Het accountantwoord mist een id of gebruikersnaam.');
    }
    $raw = $profile['id'];
    $numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw));
    if (!$numeric || (int)$raw < 1) throw new RuntimeException('Ongeldig account-id.');
    return ['auth:'.(int)$raw, $profile['username']];
}

function loginUser(string $id, string $name): void {
    if (!preg_match('/^(?:local:test_user_[12]|auth:[1-9][0-9]{0,17})$/', $id)) throw new RuntimeException('Ongeldig account.');
    $name = trim($name);
    if ($name === '' || mb_strlen($name) > 64 || preg_match('/[\x00-\x1F]/', $name)) throw new RuntimeException('Ongeldige gebruikersnaam.');
    transaction(function () use ($id, $name): void {
        $existing = query('SELECT id FROM users WHERE id=?', [$id])->fetch();
        if ($existing) {
            query('UPDATE users SET name=? WHERE id=?', [$name, $id]);
            return;
        }
        $count = (int)query('SELECT COUNT(*) FROM users')->fetchColumn();
        query('INSERT INTO users (id, name, role, theme, font, created) VALUES (?,?,?,?,?,?)', [
            $id, $name, $count === 0 ? 'admin' : 'user', 'system', 'serif', time(),
        ]);
    });
    session_regenerate_id(true);
    $_SESSION['user'] = $id;
    $_SESSION['csrf'] = bin2hex(random_bytes(24));
}

config();
session_name('verhalenboek_session');
ini_set('session.use_strict_mode', '1');
$sessionLifetime = 86400;
$sessionPath = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/').'/';
if ($sessionPath === '//') $sessionPath = '/';
$sessionSecure = !localDev();
session_set_cookie_params(['lifetime' => $sessionLifetime, 'path' => $sessionPath, 'secure' => $sessionSecure, 'httponly' => true, 'samesite' => 'Lax']);
session_set_save_handler(new DatabaseSessions(), true);
session_start();
if (session_status() === PHP_SESSION_ACTIVE && session_id() !== '') {
    setcookie(session_name(), session_id(), [
        'expires' => time() + $sessionLifetime,
        'path' => $sessionPath,
        'secure' => $sessionSecure,
        'httponly' => true,
        'samesite' => 'Lax',
    ]);
}
if (localDev() && !in_array($_SESSION['user'] ?? '', ['local:test_user_1', 'local:test_user_2'], true)) {
    unset($_SESSION['token'], $_SESSION['expires'], $_SESSION['validated']);
    loginUser('local:test_user_1', 'test_user_1');
}

function user(): string {
    if (!isset($_SESSION['user'])) fail('Log in om verder te gaan.', 401, 'missing');
    if (!localDev() && (($_SESSION['expires'] ?? 0) < time())) {
        unset($_SESSION['user']);
        fail('Je sessie is verlopen. Log opnieuw in.', 401, 'missing');
    }
    return $_SESSION['user'];
}

function fail(string $message, int $status = 400, ?string $auth = null): never {
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    $body = ['error' => $message];
    if ($auth !== null) {
        $body['how_to_authenticate'] = authHint($auth);
        $body['hint'] = $body['how_to_authenticate'];
        if ($status === 401) header('WWW-Authenticate: Bearer');
    }
    echo json_encode($body, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
    exit;
}

function jsonOut(mixed $data, int $status = 200): never {
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
    exit;
}

function bearerToken(): ?string {
    $header = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '';
    if ($header === '' && function_exists('getallheaders')) {
        $headers = getallheaders();
        if (is_array($headers)) {
            foreach ($headers as $name => $value) {
                if (strcasecmp((string)$name, 'Authorization') === 0) { $header = (string)$value; break; }
            }
        }
    }
    if ($header === '') return null;
    if (preg_match('/^Bearer\s+(\S+)\s*$/i', $header, $match)) return $match[1];
    throw new AppException('De Authorization-header heeft het verkeerde formaat.', 401, 'format');
}

function authenticate(): array {
    $token = bearerToken();
    if ($token !== null) return actorFromToken($token);
    $id = user();
    if (!localDev() && time() - ($_SESSION['validated'] ?? 0) > 60) {
        try {
            authRequest('/api/me', null, (string)($_SESSION['token'] ?? ''));
            if (($_SESSION['expires'] ?? 0) - time() < 900) {
                $extended = authRequest('/api/session/extend', [], (string)$_SESSION['token']);
                $_SESSION['expires'] = time() + (int)$extended['expires_in'];
            }
            $_SESSION['validated'] = time();
        } catch (Throwable $e) {
            unset($_SESSION['user']);
            fail('Log opnieuw in.', 401, 'missing');
        }
    }
    $row = query('SELECT id, role FROM users WHERE id=?', [$id])->fetch();
    if (!$row) fail('Log opnieuw in.', 401, 'missing');
    return ['kind' => 'user', 'userId' => $row['id'], 'role' => $row['role']];
}

function requireCsrf(array $actor): void {
    if ($actor['kind'] === 'token') return;
    $sent = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
    $expected = $_SESSION['csrf'] ?? '';
    if (!is_string($sent) || !is_string($expected) || $expected === '' || !hash_equals($expected, $sent)) {
        fail('Ongeldige sessie. Laad de pagina opnieuw.', 403);
    }
}

function requireWriter(array $actor): void {
    if ($actor['kind'] === 'token') return;
    if (($actor['role'] ?? '') !== 'admin') fail('Alleen een beheerder mag dit wijzigen.', 403, 'writer');
}

function requireAdminSession(array $actor, string $message = 'Alleen een beheerder mag sleutels beheren.', string $auth = 'admin'): void {
    if ($actor['kind'] !== 'user' || ($actor['role'] ?? '') !== 'admin') fail($message, 403, $auth);
}

function requireReader(array $actor): void {
    if ($actor['kind'] !== 'user') fail('Leesstatus hoort bij een ingelogde lezer.', 403);
}

function readJson(): array {
    $raw = file_get_contents('php://input');
    if ($raw === false || trim($raw) === '') throw new AppException('De aanvraag heeft een JSON-object nodig.');
    try {
        $data = json_decode($raw, true, 64, JSON_THROW_ON_ERROR);
    } catch (JsonException) {
        throw new AppException('De JSON is ongeldig.');
    }
    if (!is_array($data) || array_is_list($data)) throw new AppException('De JSON moet een object zijn.');
    return $data;
}

function apiRoute(): string {
    $candidates = [];
    $info = $_SERVER['PATH_INFO'] ?? '';
    if (is_string($info) && $info !== '') $candidates[] = $info;
    $uri = rawurldecode(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/');
    if (preg_match('#/api\.php(/.*)$#', $uri, $match)) $candidates[] = $match[1];
    foreach ($candidates as $candidate) {
        $candidate = '/'.trim((string)$candidate, '/');
        if ($candidate !== '/') return $candidate;
    }
    return '/';
}
