<?php

/* Secure defaults shared by every public and private page. */
if (!headers_sent()) {
    header('X-Content-Type-Options: nosniff');
    header('X-Frame-Options: DENY');
    header('Referrer-Policy: strict-origin-when-cross-origin');
    header('Permissions-Policy: camera=(), microphone=(), geolocation=()');
    header("Content-Security-Policy: default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; font-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'self'; object-src 'none'; upgrade-insecure-requests");
}

function sparrow_config(?string $key = null)
{
    static $config = null;

    if ($config === null) {
        $config = require __DIR__ . '/config.php';
    }

    if ($key === null) {
        return $config;
    }

    return $config[$key] ?? null;
}

function sparrow_url(string $path = ''): string
{
    $base = rtrim((string) (sparrow_config('base_url') ?: ''), '/');
    $path = trim($path);

    if ($path === '') {
        return $base . '/';
    }

    // Leave full external URLs and special links unchanged.
    if (
        preg_match('/^[a-z][a-z0-9+.-]*:/i', $path)
        || str_starts_with($path, '//')
        || str_starts_with($path, '#')
    ) {
        return $path;
    }

    $path = '/' . ltrim($path, '/');

    // Prevent /sparrowseed from being added twice.
    if (
        $path === $base
        || str_starts_with($path, $base . '/')
        || str_starts_with($path, $base . '?')
        || str_starts_with($path, $base . '#')
    ) {
        return $path;
    }

    return $base . $path;
}

function sparrow_redirect(string $path): void
{
    header('Location: ' . sparrow_url($path));
    exit;
}

function sparrow_escape(?string $value): string
{
    return htmlspecialchars($value ?? '', ENT_QUOTES, 'UTF-8');
}

function sparrow_get_daily_verse(PDO $pdo): array
{
    $stmt = $pdo->prepare("
        SELECT value
        FROM backyard_settings
        WHERE category = :category
        ORDER BY id ASC
        LIMIT 1
    ");

    $stmt->execute([
        ':category' => 'daily_verse',
    ]);

    $raw = trim((string) ($stmt->fetchColumn() ?: ''));

    if ($raw === '') {
        return [
            'reference' => '',
            'text' => '',
        ];
    }

    $lines = array_values(array_filter(array_map('trim', preg_split('/\r\n|\r|\n/', $raw))));

    if (empty($lines)) {
        return [
            'reference' => '',
            'text' => '',
        ];
    }

    /*
     * Same verse all day, changes by date.
     * This avoids changing every refresh.
     */
    $day_number = (int) date('z');
    $line = $lines[$day_number % count($lines)];

    if (str_contains($line, '|')) {
        [$reference, $text] = array_map('trim', explode('|', $line, 2));
    } else {
        $reference = '';
        $text = $line;
    }

    return [
        'reference' => $reference,
        'text' => $text,
    ];
}

function sparrow_get_daily_prayer(PDO $pdo): string
{
    $stmt = $pdo->prepare("
        SELECT value 
        FROM backyard_settings 
        WHERE category = 'daily_prayer'
        LIMIT 1
    ");
    $stmt->execute();
    return $stmt->fetchColumn() ?: '';
}
