<?php
declare(strict_types=1);

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

function app_url(string $path = ''): string
{
    global $config;
    return rtrim((string)$config['app_url'], '/') . ($path === '' ? '' : '/' . ltrim($path, '/'));
}

function request_path(): string
{
    global $config;
    $request = rawurldecode(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/');
    $base = parse_url((string)$config['app_url'], PHP_URL_PATH) ?: '';
    if ($base !== '' && str_starts_with($request, rtrim($base, '/'))) {
        $request = substr($request, strlen(rtrim($base, '/')));
    }
    return trim($request, '/');
}

function setting(string $key, mixed $default = ''): mixed
{
    static $settings = null;
    if ($settings === null) {
        $settings = [];
        try {
            foreach (DB::connection()->query('SELECT setting_key, setting_value FROM settings') as $row) {
                $settings[$row['setting_key']] = $row['setting_value'];
            }
        } catch (Throwable) {
        }
    }
    return array_key_exists($key, $settings) ? $settings[$key] : $default;
}

function save_setting(string $key, string $value): void
{
    $stmt = DB::connection()->prepare(
        'INSERT INTO settings (setting_key, setting_value, updated_at) VALUES (?, ?, NOW())
         ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), updated_at = NOW()'
    );
    $stmt->execute([$key, $value]);
}

function slugify(string $text): string
{
    $text = trim($text);
    if (function_exists('transliterator_transliterate')) {
        $text = transliterator_transliterate('Any-Latin; Latin-ASCII; Lower()', $text);
    } else {
        $text = strtolower($text);
    }
    $text = preg_replace('/[^a-z0-9]+/i', '-', $text) ?: '';
    return trim(strtolower($text), '-') ?: 'game';
}

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

function csrf_field(): string
{
    return '<input type="hidden" name="_csrf" value="' . e(csrf_token()) . '">';
}

function verify_csrf(): void
{
    $sent = (string)($_POST['_csrf'] ?? '');
    if ($sent === '' || !hash_equals((string)($_SESSION['_csrf'] ?? ''), $sent)) {
        http_response_code(419);
        exit('Session expired. Go back, reload the page and try again.');
    }
}

function is_admin(): bool
{
    return !empty($_SESSION['admin_id']);
}

function require_admin(): void
{
    if (!is_admin()) {
        header('Location: ' . app_url('admin/'));
        exit;
    }
}

function admin_activity(string $action, string $details = ''): void
{
    if (!is_admin()) {
        return;
    }
    $stmt = DB::connection()->prepare(
        'INSERT INTO admin_activity_log (admin_id, action, details, ip_hash, created_at) VALUES (?, ?, ?, ?, NOW())'
    );
    $stmt->execute([
        (int)$_SESSION['admin_id'],
        $action,
        mb_substr($details, 0, 1000),
        hash('sha256', ($_SERVER['REMOTE_ADDR'] ?? '') . setting('privacy_salt', 'gamesji')),
    ]);
}

function log_message(string $level, string $message): void
{
    $dir = APP_ROOT . '/storage/logs';
    if (!is_dir($dir)) {
        @mkdir($dir, 0755, true);
    }
    @file_put_contents(
        $dir . '/app-' . date('Y-m-d') . '.log',
        '[' . date('c') . '] ' . $level . ' ' . str_replace(["\r", "\0"], '', $message) . PHP_EOL,
        FILE_APPEND | LOCK_EX
    );
}

function fetch_url(string $url, int $timeout = 18): array
{
    if (!filter_var($url, FILTER_VALIDATE_URL) || !in_array(parse_url($url, PHP_URL_SCHEME), ['http', 'https'], true)) {
        return ['ok' => false, 'status' => 0, 'body' => '', 'error' => 'Invalid URL'];
    }
    $headers = [
        'Accept: text/html,application/xhtml+xml,application/json;q=0.9,*/*;q=0.8',
        'Accept-Language: en-IN,en;q=0.8',
        'Cache-Control: no-cache',
        'User-Agent: GamesJiDiscoveryBot/1.0 (+https://gamesji.com/app/about)',
    ];
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS => 3,
            CURLOPT_CONNECTTIMEOUT => 8,
            CURLOPT_TIMEOUT => $timeout,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_ENCODING => '',
            CURLOPT_SSL_VERIFYPEER => true,
        ]);
        $body = curl_exec($ch);
        $status = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        return ['ok' => is_string($body) && $status >= 200 && $status < 300, 'status' => $status, 'body' => is_string($body) ? $body : '', 'error' => $error];
    }
    $context = stream_context_create(['http' => ['timeout' => $timeout, 'follow_location' => 1, 'header' => implode("\r\n", $headers)]]);
    $body = @file_get_contents($url, false, $context);
    return ['ok' => is_string($body), 'status' => is_string($body) ? 200 : 0, 'body' => is_string($body) ? $body : '', 'error' => is_string($body) ? '' : 'HTTP fetch failed'];
}

function flash(string $type, string $message): void
{
    $_SESSION['_flash'][] = ['type' => $type, 'message' => $message];
}

function render_flashes(): void
{
    foreach ($_SESSION['_flash'] ?? [] as $item) {
        echo '<div class="alert ' . e($item['type']) . '">' . e($item['message']) . '</div>';
    }
    unset($_SESSION['_flash']);
}

function ad_slot(string $slot): string
{
    if (setting('ads_enabled', '0') !== '1') {
        return '';
    }
    $client = trim((string)setting('adsense_client', ''));
    $slotId = trim((string)setting('ad_slot_' . $slot, ''));
    if ($client === '' || $slotId === '') {
        return '';
    }
    return '<div class="ad-wrap" aria-label="Advertisement"><ins class="adsbygoogle" style="display:block" data-ad-client="' .
        e($client) . '" data-ad-slot="' . e($slotId) . '" data-ad-format="auto" data-full-width-responsive="true"></ins></div>';
}

function page_header(string $title, string $description = '', array $options = []): void
{
    $siteName = (string)setting('site_name', 'GamesJi Apps');
    $description = $description !== '' ? $description : (string)setting('site_description', 'Discover Android games and visit verified official listings.');
    $canonical = $options['canonical'] ?? app_url(request_path());
    $image = $options['image'] ?? app_url('assets/icon.svg');
    $robots = $options['robots'] ?? 'index,follow,max-image-preview:large';
    $ads = setting('ads_enabled', '0') === '1' && setting('adsense_client', '') !== '';
    header('Content-Type: text/html; charset=UTF-8');
    header('X-Frame-Options: SAMEORIGIN');
    header('X-Content-Type-Options: nosniff');
    header('Referrer-Policy: strict-origin-when-cross-origin');
    ?><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title><?= e($title) ?> | <?= e($siteName) ?></title>
  <meta name="description" content="<?= e(mb_substr($description, 0, 160)) ?>">
  <meta name="robots" content="<?= e($robots) ?>">
  <link rel="canonical" href="<?= e($canonical) ?>">
  <link rel="manifest" href="<?= e(app_url('manifest.webmanifest')) ?>">
  <link rel="icon" href="<?= e(app_url('assets/icon.svg')) ?>" type="image/svg+xml">
  <link rel="apple-touch-icon" href="<?= e(app_url('assets/icon-192.png')) ?>">
  <meta name="theme-color" content="#111827">
  <meta property="og:type" content="<?= e($options['og_type'] ?? 'website') ?>">
  <meta property="og:site_name" content="<?= e($siteName) ?>">
  <meta property="og:title" content="<?= e($title) ?>">
  <meta property="og:description" content="<?= e($description) ?>">
  <meta property="og:url" content="<?= e($canonical) ?>">
  <meta property="og:image" content="<?= e($image) ?>">
  <meta name="twitter:card" content="summary_large_image">
  <?php if (setting('google_site_verification', '') !== ''): ?><meta name="google-site-verification" content="<?= e(setting('google_site_verification')) ?>"><?php endif; ?>
  <link rel="stylesheet" href="<?= e(app_url('assets/app.css?v=' . APP_VERSION)) ?>">
  <?php if ($ads): ?><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=<?= e(setting('adsense_client')) ?>" crossorigin="anonymous"></script><?php endif; ?>
  <?= (string)setting('head_code', '') ?>
</head>
<body>
<a class="skip-link" href="#main">Skip to content</a>
<header class="site-header">
  <div class="nav-wrap">
    <a class="brand" href="<?= e(app_url()) ?>"><img src="<?= e(app_url('assets/icon.svg')) ?>" alt="" width="38" height="38"><span><?= e($siteName) ?></span></a>
    <form class="site-search" action="<?= e(app_url('search')) ?>" method="get"><label class="sr-only" for="q">Search games</label><input id="q" name="q" maxlength="80" placeholder="Search games or developers" value="<?= e($_GET['q'] ?? '') ?>"><button type="submit">Search</button></form>
    <a class="play-free" href="<?= e(setting('home_url', 'https://gamesji.com/')) ?>">Play Free Game</a>
  </div>
</header>
<main id="main" class="container"><?php
}

function page_footer(): void
{
    ?>
<?= ad_slot('footer') ?>
</main>
<nav class="mobile-nav" aria-label="Mobile navigation">
  <a href="<?= e(app_url()) ?>">Discover</a>
  <a href="<?= e(app_url('categories')) ?>">Categories</a>
  <a href="<?= e(setting('home_url', 'https://gamesji.com/')) ?>">Play Free</a>
</nav>
<footer class="site-footer">
  <div class="container footer-grid">
    <div><strong><?= e(setting('site_name', 'GamesJi Apps')) ?></strong><p><?= e(setting('site_description', 'Discover Android games and visit verified official listings.')) ?></p></div>
    <div><a href="<?= e(app_url('about')) ?>">About</a><a href="<?= e(app_url('contact')) ?>">Contact</a><a href="<?= e(app_url('privacy')) ?>">Privacy</a><a href="<?= e(app_url('terms')) ?>">Terms</a><a href="<?= e(app_url('disclaimer')) ?>">Disclaimer</a></div>
    <div><a href="<?= e(app_url('sitemap.xml')) ?>">Sitemap</a><a href="<?= e(app_url('feed.xml')) ?>">RSS Feed</a><a href="<?= e(setting('home_url', 'https://gamesji.com/')) ?>">GamesJi.com Home</a></div>
  </div>
  <p class="copyright">&copy; <?= date('Y') ?> <?= e(setting('site_name', 'GamesJi Apps')) ?>. Android and Google Play are trademarks of Google LLC. This site is not affiliated with Google.</p>
</footer>
<script src="<?= e(app_url('assets/app.js?v=' . APP_VERSION)) ?>" defer></script>
<?= (string)setting('footer_code', '') ?>
</body></html><?php
}
