<?php
declare(strict_types=1);

/** Panel yolları — site kapalıyken de açık kalır (/temo giriş, /admin oturum sonrası). */
function site_control_is_admin_request(): bool
{
    $script = str_replace('\\', '/', (string) ($_SERVER['SCRIPT_NAME'] ?? ''));
    return str_contains($script, '/admin/')
        || str_contains($script, '/temo/')
        || str_ends_with($script, '/temo/index.php');
}

function site_control_is_mobile(): bool
{
    $ua = (string) ($_SERVER['HTTP_USER_AGENT'] ?? '');
    if ($ua === '') {
        return false;
    }
    return (bool) preg_match(
        '/Mobile|Android|iPhone|iPad|iPod|webOS|BlackBerry|IEMobile|Opera Mini|Windows Phone/i',
        $ua
    );
}

function site_status(): string
{
    $s = setting('site_status', 'on');
    return $s === 'off' ? 'off' : 'on';
}

function site_device_mode(): string
{
    $m = setting('site_device_mode', 'all');
    return in_array($m, ['all', 'mobile_only', 'desktop_only'], true) ? $m : 'all';
}

function site_redirect_url(): string
{
    $url = trim(setting('site_redirect_url'));
    if ($url === '') {
        return '';
    }
    if (!preg_match('#^https?://#i', $url)) {
        return '';
    }
    return $url;
}

/** Engelli erişim: sebep yazılmaz (bilgi sızdırmaz). Link varsa oraya gider. */
function site_control_deny_access(): never
{
    $redirect = site_redirect_url();
    if ($redirect !== '') {
        header('Location: ' . $redirect, true, 302);
        exit;
    }

    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;font-size:1rem}</style></head><body><p>404</p></body></html>';
    exit;
}

function site_control_is_preview(): bool
{
    if ((string) ($_GET['preview'] ?? '') !== '1') {
        return false;
    }
    return function_exists('current_user')
        && function_exists('is_admin')
        && is_admin(current_user());
}

/**
 * WhatsApp / Facebook / Twitter vb. link önizleme botları.
 * Bunlar çoğu zaman “masaüstü” gibi gelir; engellenirse OG kartı bozulur.
 * Googlebot / Bingbot burada YOK — dizinleme ayrı konu.
 */
function site_control_is_social_crawler(): bool
{
    $ua = (string) ($_SERVER['HTTP_USER_AGENT'] ?? '');
    if ($ua === '') {
        return false;
    }

    // Arama / SEO botları asla muaf değil
    if (preg_match('/Googlebot|Google-InspectionTool|AdsBot-Google|Mediapartners-Google|Bingbot|DuckDuckBot|YandexBot|Baiduspider|SemrushBot|AhrefsBot|DotBot|MJ12bot|Bytespider|PetalBot|Sogou/i', $ua)) {
        return false;
    }

    // Resmi / bilinen önizleme imzaları (mümkün olduğunca net)
    if (preg_match(
        '/'
        . 'facebookexternalhit\/|'
        . 'Facebot|'
        . 'FacebookBot|'
        . 'meta-externalagent|'
        . 'meta-externalfetcher|'
        . 'Instagram\s*[0-9]|'
        . 'WhatsApp|'
        . 'whatsapp|'
        . 'Twitterbot\/|'
        . 'LinkedInBot\/|'
        . 'Slackbot|'
        . 'Slack-ImgProxy|'
        . 'TelegramBot|'
        . 'Discordbot\/|'
        . 'DiscordBot|'
        . 'Pinterest\/|Pinterestbot|'
        . 'SkypeUriPreview|'
        . 'vkShare|VK\/\d|'
        . 'redditbot\/|'
        . 'Applebot\/|'
        . 'Embedly|'
        . 'Quora\s+Link\s+Preview|'
        . 'Iframely|'
        . 'Bitlybot\/|'
        . 'Xing-contenttabreceiver|'
        . 'Viber|'
        . 'Snap\s+URL\s+Preview|Snapchat|'
        . 'Line\/\d|'
        . 'Yahoo\s+Link\s+Preview|'
        . 'OpenGraphChecker|'
        . 'Notion\/'
        . '/i',
        $ua
    )) {
        return true;
    }

    // WhatsApp bazen sade UA ile gelir
    if (preg_match('/\bWhatsApp\b/i', $ua)) {
        return true;
    }

    $from = strtolower((string) ($_SERVER['HTTP_FROM'] ?? ''));
    if ($from !== '' && preg_match('/facebook\.com|twitter\.com|x\.com|linkedin\.com|pinterest\.com|slack\.com|telegram/i', $from)) {
        return true;
    }

    return false;
}

/**
 * Vitrin erişimini uygula.
 * Sadece /admin ve /temo muaf — admin oturumu vitrini baypas ETMEZ
 * (yoksa “kapalı” ayarı test edilemez).
 */
function site_control_enforce(): void
{
    if (site_control_is_admin_request()) {
        return;
    }

    if (site_control_is_preview()) {
        return;
    }

    // Link paylaşım önizlemesi (OG) için sosyal botlar geçer
    if (site_control_is_social_crawler()) {
        return;
    }

    // Client Hints iste — masaüstü platformunu daha net ayırt etmek için
    header('Accept-CH: Sec-CH-UA-Mobile, Sec-CH-UA-Platform');
    header('Critical-CH: Sec-CH-UA-Mobile, Sec-CH-UA-Platform');
    header('Vary: Sec-CH-UA-Mobile, Sec-CH-UA-Platform, User-Agent');

    if (site_status() === 'off') {
        site_control_deny_access();
    }

    $mode = site_device_mode();
    $mobile = site_control_is_mobile();

    // Client Hints: masaüstü platformunu ele verir (emülatör bazen UA’yı bozar)
    $chMobile = (string) ($_SERVER['HTTP_SEC_CH_UA_MOBILE'] ?? '');
    $chPlatform = strtolower((string) ($_SERVER['HTTP_SEC_CH_UA_PLATFORM'] ?? ''));
    $chPlatform = trim($chPlatform, '"');
    $desktopPlatform = in_array($chPlatform, ['windows', 'macos', 'linux', 'chrome os'], true);

    if ($mode === 'mobile_only') {
        if (!$mobile || $chMobile === '?0' || $desktopPlatform) {
            site_control_deny_access();
        }
    }

    if ($mode === 'desktop_only') {
        if ($mobile || $chMobile === '?1') {
            site_control_deny_access();
        }
    }
}

/**
 * Emülatör / DevTools cihaz modunu yakalamak için erken JS kapısı.
 * Chrome cihaz modu ekran boyutunu da taklit eder; masaüstü GPU (ANGLE/NVIDIA…) sızar.
 */
function site_control_client_gate_script(): string
{
    if (site_control_is_admin_request() || site_control_is_preview() || site_control_is_social_crawler()) {
        return '';
    }

    $mode = site_device_mode();
    $needGate = ($mode === 'mobile_only' || $mode === 'desktop_only' || site_status() === 'off');
    if (!$needGate) {
        return '';
    }

    $redirect = site_redirect_url();
    $redirectJs = json_encode($redirect !== '' ? $redirect : 'about:blank', JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    $modeJs = json_encode($mode, JSON_UNESCAPED_UNICODE);

    return '<style id="sc-gate">html{visibility:hidden!important;background:#fff}</style>'
        . '<script>(function(){'
        . 'var mode=' . $modeJs . ',go=' . $redirectJs . ';'
        . 'function deny(){try{document.documentElement.innerHTML="";}catch(e){}location.replace(go);}'
        . 'function show(){var s=document.getElementById("sc-gate");if(s)s.remove();document.documentElement.style.visibility="visible";}'
        . 'function gpu(){try{var c=document.createElement("canvas");var g=c.getContext("webgl")||c.getContext("experimental-webgl");'
        . 'if(!g)return{r:"",v:""};var x=g.getExtension("WEBGL_debug_renderer_info");'
        . 'return{r:String(x?g.getParameter(x.UNMASKED_RENDERER_WEBGL):g.getParameter(g.RENDERER)||"").toLowerCase(),'
        . 'v:String(x?g.getParameter(x.UNMASKED_VENDOR_WEBGL):g.getParameter(g.VENDOR)||"").toLowerCase()};}'
        . 'catch(e){return{r:"",v:""};}}'
        . 'function desktopGpu(info){'
        . 'var r=info.r||"",v=info.v||"",t=r+" "+v;'
        . 'if(!r&&!v)return false;'
        . 'if(/adreno|mali-|powerv|apple gpu|apple a[0-9]|videocore|tegra/.test(r)&&!/angle/.test(r))return false;'
        . 'return /angle|nvidia|geforce|quadro|radeon|amd |swiftshader|llvmpipe|direct3d|d3d11|d3d9|metal renderer|intel.*uhd|intel.*hd graphics|intel.*iris|microsoft basic/.test(t);'
        . '}'
        . 'function isDesktopShell(){'
        . 'var score=0,iw=window.innerWidth||0,ow=window.outerWidth||0,sw=(screen&&screen.width)||0,aw=(screen&&screen.availWidth)||0,sh=(screen&&screen.height)||0,ua=navigator.userAgent||"";'
        . 'if(ow&&iw&&(ow-iw>80))score+=3;'
        . 'if(sw>=900&&iw>0&&iw<700)score+=3;'
        . 'if(aw>=900&&iw>0&&iw<700)score+=2;'
        . 'if(sw>=1280||sh>=800)score+=1;'
        . 'try{if(matchMedia("(hover: hover) and (pointer: fine)").matches)score+=2;}catch(e){}'
        . 'if(!navigator.maxTouchPoints)score+=2;'
        . 'if(desktopGpu(gpu()))score+=4;'
        . 'try{if(navigator.webdriver)score+=3;}catch(e){}'
        . 'try{if(navigator.userAgentData&&navigator.userAgentData.mobile===false)score+=3;}catch(e){}'
        . 'try{var p=String(navigator.platform||"");if(/Win32|Win64|MacIntel|Linux x86/i.test(p)&&!/iPhone|iPad|Android/i.test(ua))score+=3;else if(/Win32|Win64|MacIntel/i.test(p))score+=2;}catch(e){}'
        . 'try{if(navigator.plugins&&navigator.plugins.length>2)score+=1;}catch(e){}'
        . 'return score>=3;'
        . '}'
        . 'try{'
        . 'var desk=isDesktopShell();'
        . 'if(mode==="mobile_only"&&desk){deny();return;}'
        . 'if(mode==="desktop_only"&&!desk&&/Mobile|Android|iPhone|iPad/i.test(navigator.userAgent||"")){deny();return;}'
        . '}catch(e){deny();return;}'
        . 'show();'
        . '})();</script>';
}

/** @return list<string> */
function site_reset_targets(): array
{
    return ['orders', 'products', 'comments', 'sellers'];
}

/**
 * Seçilen veri setlerini sıfırlar.
 *
 * @param list<string> $targets
 * @return array{ok:list<string>, fail:list<string>}
 */
function site_reset_run(array $targets, bool $clearProductImages = false): array
{
    $allowed = site_reset_targets();
    $ok = [];
    $fail = [];

    foreach ($targets as $name) {
        $name = (string) $name;
        if (!in_array($name, $allowed, true)) {
            continue;
        }
        if (store_write($name, [])) {
            $ok[] = $name;
        } else {
            $fail[] = $name;
        }
    }

    if ($clearProductImages && in_array('products', $ok, true) && defined('UPLOAD_PATH') && is_dir(UPLOAD_PATH)) {
        foreach (glob(UPLOAD_PATH . '/*') ?: [] as $file) {
            if (is_file($file) && !str_ends_with($file, '.gitkeep')) {
                @unlink($file);
            }
        }
    }

    if (in_array('orders', $ok, true) && defined('RECEIPT_PATH') && is_dir(RECEIPT_PATH)) {
        foreach (glob(RECEIPT_PATH . '/*') ?: [] as $file) {
            if (is_file($file) && !str_ends_with($file, '.gitkeep')) {
                @unlink($file);
            }
        }
    }

    return ['ok' => $ok, 'fail' => $fail];
}
