<?php
declare(strict_types=1);

function is_admin(?array $user): bool
{
    return $user && (($user['role'] ?? 'user') === 'admin');
}

function require_admin(): array
{
    $user = current_user();
    if (!$user) {
        // /admin dizinini ele verme — giriş yalnızca /temo
        http_response_code(404);
        header('Content-Type: text/html; charset=UTF-8');
        echo '<!DOCTYPE html><html lang="tr"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
            . '<meta name="robots" content="noindex,nofollow"><title>404</title>'
            . '<style>body{margin:0;min-height:100vh;display:grid;place-items:center;font-family:system-ui,sans-serif;background:#f5f5f5;color:#222}'
            . 'p{margin:0}</style></head><body><p>404</p></body></html>';
        exit;
    }
    if (!is_admin($user)) {
        http_response_code(404);
        header('Content-Type: text/html; charset=UTF-8');
        echo '<!DOCTYPE html><html lang="tr"><head><meta charset="UTF-8"><meta name="robots" content="noindex,nofollow"><title>404</title></head><body><p>404</p></body></html>';
        exit;
    }
    return $user;
}

function app_base_path(): string
{
    $script = str_replace('\\', '/', (string) ($_SERVER['SCRIPT_NAME'] ?? ''));
    $dir = dirname($script);

    if (str_ends_with($dir, '/admin') || str_ends_with($dir, '/temo')) {
        $dir = dirname($dir);
    }

    $dir = rtrim($dir, '/');
    if ($dir === '/' || $dir === '\\' || $dir === '.') {
        return '';
    }

    return $dir;
}

function app_base_url(): string
{
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $fwd = strtolower((string) ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? ''));
    if ($fwd === 'https' || (!empty($_SERVER['SERVER_PORT']) && (string) $_SERVER['SERVER_PORT'] === '443')) {
        $scheme = 'https';
    }
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    return $scheme . '://' . $host . app_base_path();
}

function url(string $path): string
{
    $path = ltrim($path, '/');
    $base = app_base_path();
    return ($base === '' ? '' : $base) . '/' . $path;
}

function product_share_url(string $productId): string
{
    $url = app_base_url() . '/urun.php?id=' . urlencode($productId);
    // WhatsApp önizleme cache’ini ürün / OG metin değişince kır
    if (function_exists('store_find')) {
        $p = store_find('products', $productId);
        if (is_array($p)) {
            $stamp = (string) ($p['updated_at'] ?? $p['created_at'] ?? '');
            $ogVer = function_exists('og_share_rev') ? (string) og_share_rev() : '1';
            $url .= '&t=' . substr(md5($stamp . '|' . $ogVer), 0, 8);
        }
    }
    return $url;
}

function profile_share_url(string $userId): string
{
    return app_base_url() . '/uye.php?id=' . urlencode($userId);
}

function absolute_url(string $path): string
{
    if (preg_match('#^https?://#i', $path)) {
        return $path;
    }

    $path = '/' . ltrim(str_replace('\\', '/', $path), '/');
    $basePath = app_base_path(); // örn. /deneme

    // url() zaten /deneme/... döndürdüyse tekrar ekleme → /deneme/deneme/... olmasın
    if ($basePath !== '' && (str_starts_with($path, $basePath . '/') || $path === $basePath)) {
        $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        // Proxy arkasında HTTPS
        if (
            (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower((string) $_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https')
            || (!empty($_SERVER['SERVER_PORT']) && (string) $_SERVER['SERVER_PORT'] === '443')
        ) {
            $scheme = 'https';
        }
        $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
        return $scheme . '://' . $host . $path;
    }

    return rtrim(app_base_url(), '/') . $path;
}

function product_og_image(array $product): string
{
    if (function_exists('product_og_card_url')) {
        return product_og_card_url($product);
    }
    return absolute_url(product_image_url($product));
}
