<?php

// Sayfanın <head> içindeki SEO etiketleri: açıklama, canonical, Open Graph, doğrulama ve takip kodları.
function seo_head($title, $meta)
{
    $description = $meta['description'] ?? setting('seo_description', setting('store_tagline', ''));
    $description = mb_substr(trim(preg_replace('/\s+/', ' ', strip_tags((string) $description))), 0, 160);
    $image = !empty($meta['image']) ? upload_url($meta['image']) : (setting('seo_image') ? upload_url(setting('seo_image')) : '');
    $canonical = preg_replace('#^(https?://[^/]+).*$#', '$1', URL) . current_path();

    $tags = [
        '<meta name="description" content="' . e($description) . '">',
        '<link rel="canonical" href="' . e($canonical) . '">',
        '<meta property="og:site_name" content="' . e(store_name()) . '">',
        '<meta property="og:type" content="' . e($meta['type'] ?? 'website') . '">',
        '<meta property="og:title" content="' . e(page_title($title)) . '">',
        '<meta property="og:description" content="' . e($description) . '">',
        '<meta property="og:url" content="' . e($canonical) . '">',
        '<meta name="twitter:card" content="summary_large_image">',
    ];
    if ($image) {
        $tags[] = '<meta property="og:image" content="' . e($image) . '">';
    }
    if (!empty($meta['noindex']) || setting('seo_noindex') === '1') {
        $tags[] = '<meta name="robots" content="noindex, nofollow">';
    }
    if (setting('google_verification')) {
        $tags[] = '<meta name="google-site-verification" content="' . e(setting('google_verification')) . '">';
    }
    if (!empty($meta['jsonld'])) {
        $tags[] = '<script type="application/ld+json">' . json_encode($meta['jsonld'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . '</script>';
    }
    if ($id = setting('ga_id')) {
        $tags[] = '<script async src="https://www.googletagmanager.com/gtag/js?id=' . e($id) . '"></script>';
        $tags[] = "<script>window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments)}gtag('js',new Date());gtag('config'," . json_encode($id) . ");</script>";
    }
    if ($id = setting('pixel_id')) {
        $tags[] = "<script>!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','https://connect.facebook.net/en_US/fbevents.js');fbq('init'," . json_encode($id) . ");fbq('track','PageView');</script>";
    }
    if (setting('head_code')) {
        $tags[] = setting('head_code');
    }
    return implode("\n    ", $tags);
}

function seo_title($row, $fallback)
{
    return !empty($row['meta_title']) ? $row['meta_title'] : $fallback;
}

// Ürün sayfası için Google yapılandırılmış verisi.
function product_jsonld($product, $images)
{
    $data = [
        '@context'    => 'https://schema.org',
        '@type'       => 'Product',
        'name'        => $product['name'],
        'description' => mb_substr(strip_tags((string) $product['description']), 0, 500),
        'image'       => array_map('upload_url', $images),
        'sku'         => (string) $product['id'],
        'offers'      => [
            '@type'         => 'Offer',
            'price'         => number_format($product['price'], 2, '.', ''),
            'priceCurrency' => 'TRY',
            'availability'  => $product['stock'] > 0 ? 'https://schema.org/InStock' : 'https://schema.org/OutOfStock',
            'url'           => product_url($product),
        ],
    ];
    if ($product['review_count'] > 0) {
        $data['aggregateRating'] = ['@type' => 'AggregateRating', 'ratingValue' => (float) $product['rating'], 'reviewCount' => (int) $product['review_count']];
    }
    return $data;
}

function seo_fields($row)
{
    include PARTS . '/seo-fields.php';
}

function seo_input()
{
    return [
        'meta_title'       => mb_substr(post('meta_title', ''), 0, 200) ?: null,
        'meta_description' => mb_substr(post('meta_description', ''), 0, 300) ?: null,
    ];
}
