<?php
declare(strict_types=1);

function e(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function nestor_url(string $path = ''): string
{
    $base = rtrim(SITE_URL, '/');
    $path = ltrim(str_replace('\\', '/', $path), '/');
    if ($path === '') {
        return ($base === '' ? '' : $base) . '/';
    }
    return ($base === '' ? '' : $base . '/') . $path;
}

/**
 * URL статичного файлу з cache-busting (?v= час зміни або ASSET_VERSION).
 * На проді знімає проблему «старого» style.css після деплою.
 */
function nestor_asset_url(string $relativePath): string
{
    $relativePath = ltrim(str_replace('\\', '/', $relativePath), '/');
    $url = nestor_url($relativePath);
    $full = dirname(__DIR__) . '/' . $relativePath;
    $v = (string) ASSET_VERSION;
    if (is_readable($full)) {
        $v = (string) filemtime($full);
    }
    return $url . '?v=' . rawurlencode($v);
}

/**
 * Шлях до зображення: якщо файл є в assets/images/ — локально, інакше — резервне фото (Unsplash).
 * Покладіть свої PNG у assets/images/ з тими ж іменами — вони автоматично підхопляться.
 */
function nestor_img(string $filename): string
{
    $safe = basename($filename);
    $full = dirname(__DIR__) . '/assets/images/' . $safe;
    if (is_readable($full)) {
        return nestor_url('assets/images/' . $safe);
    }

    static $fallback = [
        'minimalist_workspace_with_sleek_tech_endoftext.png' =>
            'https://images.unsplash.com/photo-1497215842964-222b430dc094?auto=format&fit=crop&w=1400&q=82',
        'elegant_photo_studio_website_mockup.png' =>
            'https://images.unsplash.com/photo-1516035069371-29a1b244cc32?auto=format&fit=crop&w=1200&q=82',
        'elegant_portfolio_mockup_with_tech_devices.png' =>
            'https://images.unsplash.com/photo-1460925895917-afdab827c52f?auto=format&fit=crop&w=1400&q=82',
        'elegant_wedding_photographer_web_design_mockup.png' =>
            'https://images.unsplash.com/photo-1519741497674-611481863552?auto=format&fit=crop&w=1400&q=82',
        'collaborative_design_in_a_stylish_studio.png' =>
            'https://images.unsplash.com/photo-1522071820081-009f0129c71c?auto=format&fit=crop&w=1200&q=82',
    ];

    return $fallback[$safe] ?? nestor_url('assets/images/' . $safe);
}

/**
 * Зображення кейсу: assets/images/projects/, public/images/projects/ або резервний URL.
 */
function nestor_project_img(string $filename): string
{
    $safe = basename($filename);
    $root = dirname(__DIR__);
    $candidates = [
        [$root . '/assets/images/projects/' . $safe, 'assets/images/projects/' . $safe],
        [$root . '/public/images/projects/' . $safe, 'public/images/projects/' . $safe],
        [$root . '/assets/images/' . $safe, 'assets/images/' . $safe],
    ];
    foreach ($candidates as [$full, $webPath]) {
        if (is_readable($full)) {
            return nestor_url($webPath);
        }
    }

    /* Mockup Astra: ніколи не підставляти сторонні сток-фото — лише локальний шаблон-посилання */
    if (strpos($safe, 'astra-portrait-') === 0) {
        $atelierClean = $root . '/assets/images/projects/atelier-mode-mockup-clean.png';
        if (is_readable($atelierClean)) {
            return nestor_url('assets/images/projects/atelier-mode-mockup-clean.png');
        }
    }

    static $fallback = [
        /* mockup-clean та оригінали — резерв лише якщо локального файлу немає */
        'velora-wedding-mockup-clean.png' =>
            'https://images.unsplash.com/photo-1519741497674-611481863552?auto=format&fit=crop&w=1600&q=82',
        'family-moments-mockup-clean.png' =>
            'https://images.unsplash.com/photo-1609220136736-443140cffec6?auto=format&fit=crop&w=1600&q=82',
        'soft-nest-maternity-mockup-clean.png' =>
            'https://images.unsplash.com/photo-1519689680058-324335c77eba?auto=format&fit=crop&w=1600&q=82',
        'atelier-mode-mockup-clean.png' =>
            'https://images.unsplash.com/photo-1509631179647-0177331693ae?auto=format&fit=crop&w=1600&q=82',
        'aurelia-photo-studio-mockup-clean.png' =>
            'https://images.unsplash.com/photo-1516035069371-29a1b244cc32?auto=format&fit=crop&w=1600&q=82',
        'malkina-photographer-mockup-clean.png' =>
            'https://images.unsplash.com/photo-1460925895917-afdab827c52f?auto=format&fit=crop&w=1600&q=82',
        'little-bloom-baby-mockup-clean.png' =>
            'https://images.unsplash.com/photo-1492691527719-9d1e07e534b4?auto=format&fit=crop&w=1600&q=82',
        'velora-wedding-mockup.png' =>
            'https://images.unsplash.com/photo-1519741497674-611481863552?auto=format&fit=crop&w=1600&q=82',
        'family-moments-mockup.png' =>
            'https://images.unsplash.com/photo-1609220136736-443140cffec6?auto=format&fit=crop&w=1600&q=82',
        'soft-nest-maternity-mockup.png' =>
            'https://images.unsplash.com/photo-1519689680058-324335c77eba?auto=format&fit=crop&w=1600&q=82',
        'atelier-mode-mockup.png' =>
            'https://images.unsplash.com/photo-1509631179647-0177331693ae?auto=format&fit=crop&w=1600&q=82',
        'aurelia-photo-studio-mockup.png' =>
            'https://images.unsplash.com/photo-1516035069371-29a1b244cc32?auto=format&fit=crop&w=1600&q=82',
        'malkina-photographer-mockup.png' =>
            'https://images.unsplash.com/photo-1460925895917-afdab827c52f?auto=format&fit=crop&w=1600&q=82',
        'little-bloom-baby-mockup.png' =>
            'https://images.unsplash.com/photo-1492691527719-9d1e07e534b4?auto=format&fit=crop&w=1600&q=82',
        'elegant_web_design_studio_showcase.png' =>
            'https://images.unsplash.com/photo-1519741497674-611481863552?auto=format&fit=crop&w=1600&q=82',
        'elegant_web_design_for_family_photographer.png' =>
            'https://images.unsplash.com/photo-1609220136736-443140cffec6?auto=format&fit=crop&w=1600&q=82',
        'soft_nest_maternity_website_mockup.png' =>
            'https://images.unsplash.com/photo-1519689680058-324335c77eba?auto=format&fit=crop&w=1600&q=82',
        'elegant_fashion_website_design_showcase.png' =>
            'https://images.unsplash.com/photo-1509631179647-0177331693ae?auto=format&fit=crop&w=1600&q=82',
        'elegant_photo_studio_website_mockup.png' =>
            'https://images.unsplash.com/photo-1516035069371-29a1b244cc32?auto=format&fit=crop&w=1600&q=82',
        'elegant_web_design_portfolio_showcase.png' =>
            'https://images.unsplash.com/photo-1460925895917-afdab827c52f?auto=format&fit=crop&w=1600&q=82',
        'elegant_web_studio_portfolio_showcase.png' =>
            'https://images.unsplash.com/photo-1492691527719-9d1e07e534b4?auto=format&fit=crop&w=1600&q=82',
    ];

    return $fallback[$safe] ?? nestor_url('assets/images/projects/' . $safe);
}

/** Додаткові кадри кейсу (якщо файли з’являться у projects/). */
function nestor_project_gallery_urls(array $project): array
{
    $out = [];
    foreach ($project['gallery'] ?? [] as $file) {
        if (!is_string($file) || $file === '') {
            continue;
        }
        $out[] = nestor_project_img($file);
    }
    return $out;
}

function sanitize_post_html(string $html): string
{
    $allowed = '<p><br><strong><b><em><i><u><ul><ol><li><a><h2><h3><blockquote><span><div>';
    $clean = strip_tags($html, $allowed);
    $clean = preg_replace('/\son\w+\s*=\s*("[^"]*"|\'[^\']*\')/i', '', $clean) ?? $clean;
    $clean = preg_replace_callback(
        '/<a\s+([^>]*)>/i',
        static function (array $m): string {
            $inner = $m[1];
            if (preg_match('/href\s*=\s*"(javascript:|vbscript:|data:|file:)/i', $inner)) {
                return '<a>';
            }
            if (preg_match('/href\s*=\s*\'(javascript:|vbscript:|data:|file:)/i', $inner)) {
                return '<a>';
            }
            return '<a ' . $inner . '>';
        },
        $clean
    ) ?? $clean;
    return $clean;
}

function excerpt(string $text, int $length = 180): string
{
    $clean = trim(strip_tags($text));
    if (mb_strlen($clean) <= $length) {
        return $clean;
    }
    return mb_substr($clean, 0, $length - 1) . '…';
}

function csrf_token(): string
{
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function verify_csrf(?string $token): bool
{
    return is_string($token) && isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}
