<?php

function generateStructuredData($config, $hizmet, $hizmet_slug, $il_slug, $ilce_slug, $mahalle_slug, $turkey_data, $dynamic_content, $base_url, $current_url, $page_type) {
    $firma_adi = $config['firma_adi'];
    $telefon_display = $config['telefon_display'];
    $telefon_raw = $config['telefon_raw'];
    $email = $config['email'];
    $domain = $config['domain'];
    $slogan = $config['slogan'];

    $schema = [
        '@context' => 'https://schema.org',
        '@graph' => []
    ];

    $schema['@graph'][] = [
        '@type' => 'Organization',
        '@id' => $base_url . '#organization',
        'name' => $firma_adi,
        'url' => $base_url,
        'logo' => ['@type' => 'ImageObject', '@id' => $base_url . '#logo', 'url' => $base_url . 'logo.png', 'width' => 200, 'height' => 60, 'caption' => $firma_adi],
        'telephone' => $telefon_display,
        'email' => $email,
        'description' => $slogan,
        'foundingLocation' => ['@type' => 'Country', 'name' => 'Turkey'],
        'areaServed' => ['@type' => 'Country', 'name' => 'Turkey'],
        'brand' => ['@type' => 'Brand', 'name' => $firma_adi, 'logo' => $base_url . 'logo.png'],
    ];

    $schema['@graph'][] = [
        '@type' => ['LocalBusiness', 'PrintShop', 'Store'],
        '@id' => $base_url . '#localbusiness',
        'name' => $firma_adi,
        'url' => $base_url,
        'telephone' => $telefon_display,
        'email' => $email,
        'image' => $base_url . 'logo.png',
        'priceRange' => '₺₺',
        'currenciesAccepted' => 'TRY',
        'paymentAccepted' => 'Cash, Credit Card, Bank Transfer',
        'address' => ['@type' => 'PostalAddress', 'addressCountry' => 'TR', 'addressLocality' => 'Türkiye'],
        'geo' => ['@type' => 'GeoCoordinates', 'latitude' => '39.9334', 'longitude' => '32.8597'],
        'openingHoursSpecification' => [
            ['@type' => 'OpeningHoursSpecification', 'dayOfWeek' => ['Monday','Tuesday','Wednesday','Thursday','Friday'], 'opens' => '09:00', 'closes' => '18:00'],
            ['@type' => 'OpeningHoursSpecification', 'dayOfWeek' => 'Saturday', 'opens' => '09:00', 'closes' => '14:00'],
        ],
        'contactPoint' => [
            ['@type' => 'ContactPoint', 'telephone' => $telefon_display, 'contactType' => 'customer service', 'availableLanguage' => ['Turkish'], 'areaServed' => 'TR'],
            ['@type' => 'ContactPoint', 'telephone' => $telefon_display, 'contactType' => 'sales', 'availableLanguage' => ['Turkish']],
        ],
        'areaServed' => ['@type' => 'Country', 'name' => 'Turkey'],
        'hasOfferCatalog' => ['@id' => $base_url . '#offercatalog'],
    ];

    $schema['@graph'][] = [
        '@type' => 'WebSite',
        '@id' => $base_url . '#website',
        'url' => $base_url,
        'name' => $firma_adi,
        'description' => $slogan,
        'publisher' => ['@id' => $base_url . '#organization'],
        'inLanguage' => 'tr-TR',
        'potentialAction' => [
            '@type' => 'SearchAction',
            'target' => ['@type' => 'EntryPoint', 'urlTemplate' => $base_url . '?q={search_term_string}'],
            'query-input' => 'required name=search_term_string',
        ],
    ];

    $service_list_items = [];
    $pos = 1;
    foreach ($config['hizmetler'] as $slug => $h) {
        $service_list_items[] = ['@type' => 'ListItem', 'position' => $pos++, 'name' => $h['name'], 'url' => $base_url . $slug . '/'];
    }
    $schema['@graph'][] = [
        '@type' => 'ItemList',
        '@id' => $base_url . '#servicelist',
        'name' => 'Kartvizit Baskı Hizmetleri',
        'numberOfItems' => count($service_list_items),
        'itemListElement' => $service_list_items,
    ];

    $schema['@graph'][] = [
        '@type' => 'OfferCatalog',
        '@id' => $base_url . '#offercatalog',
        'name' => $firma_adi . ' Kartvizit Kataloğu',
        'itemListElement' => array_map(function($slug, $h) use ($base_url, $config) {
            $product_image = $h['img'];
            if (!empty($config['use_dynamic_images']) && function_exists('resolveHomeServiceCardImageUrl')) {
                $product_image = resolveHomeServiceCardImageUrl($base_url, $h['name']);
            }
            return [
                '@type' => 'Offer',
                'itemOffered' => ['@type' => 'Product', 'name' => $h['name'], 'description' => $h['short_desc'], 'image' => $product_image],
                'url' => $base_url . $slug . '/',
                'priceCurrency' => 'TRY',
                'availability' => 'https://schema.org/InStock',
                'seller' => ['@id' => $base_url . '#organization'],
            ];
        }, array_keys($config['hizmetler']), $config['hizmetler']),
    ];

    $schema['@graph'][] = [
        '@type' => 'HowTo',
        '@id' => $base_url . '#howto',
        'name' => 'Kartvizit Siparişi Nasıl Verilir?',
        'description' => $firma_adi . ' ile kartvizit siparişi verme adımları',
        'step' => [
            ['@type' => 'HowToStep', 'position' => 1, 'name' => 'İletişime Geçin', 'text' => 'WhatsApp veya telefon ile bize ulaşın.'],
            ['@type' => 'HowToStep', 'position' => 2, 'name' => 'Tasarım ve Fiyat', 'text' => 'Tasarımınızı paylaşın veya ücretsiz tasarım desteği alın.'],
            ['@type' => 'HowToStep', 'position' => 3, 'name' => 'Onay ve Ödeme', 'text' => 'Tasarımı onaylayın ve ödemenizi yapın.'],
            ['@type' => 'HowToStep', 'position' => 4, 'name' => 'Üretim', 'text' => 'Kartvizitleriniz modern makinelerde basılır.'],
            ['@type' => 'HowToStep', 'position' => 5, 'name' => 'Teslimat', 'text' => 'Kartvizitleriniz kargo ile adresinize teslim edilir.'],
        ],
    ];

    if ($page_type === 'homepage') {
        $homepage_webpage = [
            '@type' => 'WebPage',
            '@id' => $current_url . '#webpage',
            'url' => $current_url,
            'name' => $firma_adi . ' | ' . $slogan,
            'description' => 'Profesyonel kartvizit baskı hizmeti. Mat selefonlu, parlak selefonlu, laklı, altın varak, gümüş yaldız, kraft, PVC, şeffaf, özel kesimli, metal ve kalın kartvizit.',
            'isPartOf' => ['@id' => $base_url . '#website'],
            'about' => ['@id' => $base_url . '#organization'],
            'inLanguage' => 'tr-TR',
            'speakable' => ['@type' => 'SpeakableSpecification', 'cssSelector' => ['h1', 'h2', '.hero-text']],
        ];
        if (!empty($config['og_image'])) {
            $homepage_webpage['primaryImageOfPage'] = ['@type' => 'ImageObject', 'url' => $config['og_image'], 'width' => 1200, 'height' => 630];
        }
        $schema['@graph'][] = $homepage_webpage;
    }

    if ($hizmet && $dynamic_content) {
        list($il_name, $ilce_name, $mahalle_name) = getLocationNames($il_slug, $ilce_slug, $mahalle_slug, $turkey_data);

        $page_image = !empty($config['og_image']) ? $config['og_image'] : $hizmet['img'];
        $card_image = !empty($config['service_image']) ? $config['service_image'] : $page_image;

        $breadcrumb_items = [
            ['@type' => 'ListItem', 'position' => 1, 'name' => 'Ana Sayfa', 'item' => $base_url],
            ['@type' => 'ListItem', 'position' => 2, 'name' => $hizmet['name'], 'item' => $base_url . $hizmet_slug . '/'],
        ];
        $pos = 3;
        if ($il_name) {
            $breadcrumb_items[] = ['@type' => 'ListItem', 'position' => $pos++, 'name' => $il_name, 'item' => $base_url . $hizmet_slug . '/' . $il_slug . '/'];
        }
        if ($ilce_name) {
            $breadcrumb_items[] = ['@type' => 'ListItem', 'position' => $pos++, 'name' => $ilce_name, 'item' => $base_url . $hizmet_slug . '/' . $il_slug . '/' . $ilce_slug . '/'];
        }
        if ($mahalle_name) {
            $breadcrumb_items[] = ['@type' => 'ListItem', 'position' => $pos, 'name' => $mahalle_name, 'item' => $current_url];
        }
        $schema['@graph'][] = ['@type' => 'BreadcrumbList', '@id' => $current_url . '#breadcrumb', 'itemListElement' => $breadcrumb_items];

        $service_area = null;
        if ($mahalle_name) {
            $service_area = ['@type' => 'Place', 'name' => $mahalle_name . ', ' . ($ilce_name ?? '') . ', ' . ($il_name ?? ''), 'address' => ['@type' => 'PostalAddress', 'addressLocality' => $ilce_name, 'addressRegion' => $il_name, 'addressCountry' => 'TR']];
        } elseif ($ilce_name) {
            $service_area = ['@type' => 'AdministrativeArea', 'name' => $ilce_name . ', ' . $il_name];
        } elseif ($il_name) {
            $service_area = ['@type' => 'City', 'name' => $il_name, 'containedInPlace' => ['@type' => 'Country', 'name' => 'Turkey']];
        }

        $schema['@graph'][] = [
            '@type' => 'Service',
            '@id' => $current_url . '#service',
            'name' => $dynamic_content['h1'],
            'description' => $dynamic_content['meta_description'],
            'provider' => ['@id' => $base_url . '#localbusiness'],
            'image' => $page_image,
            'serviceType' => $hizmet['name'],
            'areaServed' => $service_area ?? ['@type' => 'Country', 'name' => 'Turkey'],
            'availableChannel' => ['@type' => 'ServiceChannel', 'servicePhone' => ['@type' => 'ContactPoint', 'telephone' => $telefon_display], 'serviceUrl' => $current_url],
            'offers' => ['@type' => 'Offer', 'priceCurrency' => 'TRY', 'availability' => 'https://schema.org/InStock', 'url' => $current_url],
        ];

        $schema['@graph'][] = [
            '@type' => 'Product',
            '@id' => $current_url . '#product',
            'name' => $hizmet['name'],
            'description' => $hizmet['long_desc'],
            'image' => $card_image,
            'brand' => ['@type' => 'Brand', 'name' => $firma_adi],
            'manufacturer' => ['@id' => $base_url . '#organization'],
            'offers' => ['@type' => 'Offer', 'priceCurrency' => 'TRY', 'availability' => 'https://schema.org/InStock', 'url' => $current_url, 'seller' => ['@id' => $base_url . '#organization']],
        ];

        $schema['@graph'][] = [
            '@type' => 'WebPage',
            '@id' => $current_url . '#webpage',
            'url' => $current_url,
            'name' => $dynamic_content['title'],
            'description' => $dynamic_content['meta_description'],
            'isPartOf' => ['@id' => $base_url . '#website'],
            'breadcrumb' => ['@id' => $current_url . '#breadcrumb'],
            'inLanguage' => 'tr-TR',
            'primaryImageOfPage' => ['@type' => 'ImageObject', 'url' => $page_image, 'width' => 1200, 'height' => 630],
            'speakable' => ['@type' => 'SpeakableSpecification', 'cssSelector' => ['h1', 'h2', 'article p']],
            'mainEntity' => ['@id' => $current_url . '#service'],
        ];

        if (!empty($dynamic_content['faq'])) {
            $faq_entities = [];
            foreach ($dynamic_content['faq'] as $faq) {
                $faq_entities[] = ['@type' => 'Question', 'name' => $faq['q'], 'acceptedAnswer' => ['@type' => 'Answer', 'text' => $faq['a']]];
            }
            $schema['@graph'][] = ['@type' => 'FAQPage', '@id' => $current_url . '#faq', 'mainEntity' => $faq_entities];
        }

        if (!empty($dynamic_content['reviews'])) {
            $review_list = [];
            foreach ($dynamic_content['reviews'] as $rev) {
                $review_list[] = ['@type' => 'Review', 'author' => ['@type' => 'Person', 'name' => $rev['isim']], 'reviewRating' => ['@type' => 'Rating', 'ratingValue' => $rev['puan'], 'bestRating' => 5], 'reviewBody' => $rev['metin'], 'datePublished' => date('Y-m-d')];
            }
            $schema['@graph'][] = [
                '@type' => 'Product',
                '@id' => $current_url . '#ratedproduct',
                'name' => $dynamic_content['h1'],
                'aggregateRating' => ['@type' => 'AggregateRating', 'ratingValue' => '5.0', 'bestRating' => '5', 'worstRating' => '1', 'reviewCount' => count($dynamic_content['reviews'])],
                'review' => $review_list,
            ];
        }

        if ($il_name) {
            $schema['@graph'][] = [
                '@type' => 'Place',
                '@id' => $current_url . '#place',
                'name' => ($mahalle_name ? $mahalle_name . ', ' : '') . ($ilce_name ? $ilce_name . ', ' : '') . $il_name,
                'address' => ['@type' => 'PostalAddress', 'addressLocality' => $ilce_name ?? $il_name, 'addressRegion' => $il_name, 'addressCountry' => 'TR'],
                'containedInPlace' => ['@type' => 'Country', 'name' => 'Turkey'],
            ];
        }

        if (!empty($config['gizli_hizmetler'])) {
            $other_items = [];
            $other_pos = 1;
            foreach ($config['gizli_hizmetler'] as $g_slug => $g_h) {
                $other_items[] = ['@type' => 'ListItem', 'position' => $other_pos++, 'name' => $g_h['name'], 'url' => $base_url . $g_slug . '/'];
            }
            $schema['@graph'][] = [
                '@type' => 'ItemList',
                '@id' => $current_url . '#other-services',
                'name' => 'Diğer Hizmetlerimiz',
                'numberOfItems' => count($other_items),
                'itemListElement' => array_slice($other_items, 0, 50),
            ];
        }
    }

    return '<script type="application/ld+json">' . json_encode($schema, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . '</script>';
}

function renderMetaTags($config, $dynamic_content, $current_url, $og_image, $robots_content, $il_slug, $ilce_slug, $mahalle_slug, $turkey_data) {
    $firma_adi = $config['firma_adi'];
    $slogan = $config['slogan'];
    $domain = $config['domain'];
    $telefon_display = $config['telefon_display'];

    $title = $dynamic_content ? htmlspecialchars($dynamic_content['title']) : $firma_adi . ' | ' . $slogan;
    $description = $dynamic_content ? htmlspecialchars($dynamic_content['meta_description']) : 'Profesyonel kartvizit baskı hizmeti. Mat selefonlu, parlak selefonlu, laklı, altın varak ve daha fazlası. Türkiye geneli hızlı kargo.';
    $keywords = $dynamic_content ? htmlspecialchars($dynamic_content['meta_keywords']) : 'kartvizit, kartvizit baskı, kartvizit fiyatları, kartvizit yaptırma, matbaa, kartvizit tasarım, online kartvizit';

    list($il_name, $ilce_name, $mahalle_name) = getLocationNames($il_slug, $ilce_slug, $mahalle_slug, $turkey_data ?? []);
    $geo_place = $mahalle_name ?? $ilce_name ?? $il_name ?? 'Türkiye';

    $tags = '';
    $tags .= '<title>' . $title . '</title>' . "\n";
    $tags .= '<meta name="description" content="' . $description . '">' . "\n";
    $tags .= '<meta name="keywords" content="' . $keywords . '">' . "\n";
    $tags .= '<meta name="robots" content="' . $robots_content . '">' . "\n";
    $tags .= '<meta name="author" content="' . htmlspecialchars($firma_adi) . '">' . "\n";
    $tags .= '<meta name="publisher" content="' . htmlspecialchars($firma_adi) . '">' . "\n";
    $tags .= '<meta name="copyright" content="' . htmlspecialchars($firma_adi) . '">' . "\n";
    $tags .= '<meta name="revisit-after" content="3 days">' . "\n";
    $tags .= '<meta name="language" content="Turkish">' . "\n";
    $tags .= '<meta name="content-language" content="tr">' . "\n";
    $tags .= '<meta name="distribution" content="global">' . "\n";
    $tags .= '<meta name="rating" content="general">' . "\n";
    $tags .= '<meta name="referrer" content="no-referrer-when-downgrade">' . "\n";
    $tags .= '<meta name="format-detection" content="telephone=yes">' . "\n";
    $tags .= '<meta name="theme-color" content="#1E40AF">' . "\n";
    $tags .= '<meta name="msapplication-TileColor" content="#1E40AF">' . "\n";
    $tags .= '<meta name="apple-mobile-web-app-capable" content="yes">' . "\n";
    $tags .= '<meta name="apple-mobile-web-app-status-bar-style" content="default">' . "\n";
    $tags .= '<meta name="mobile-web-app-capable" content="yes">' . "\n";
    $tags .= '<meta name="application-name" content="' . htmlspecialchars($firma_adi) . '">' . "\n";
    $tags .= '<meta name="geo.region" content="TR">' . "\n";
    $tags .= '<meta name="geo.placename" content="' . htmlspecialchars($geo_place) . '">' . "\n";
    $tags .= '<meta name="geo.position" content="39.9334;32.8597">' . "\n";
    $tags .= '<meta name="ICBM" content="39.9334, 32.8597">' . "\n";
    $tags .= '<meta property="og:title" content="' . $title . '">' . "\n";
    $tags .= '<meta property="og:description" content="' . $description . '">' . "\n";
    $tags .= '<meta property="og:type" content="website">' . "\n";
    $tags .= '<meta property="og:url" content="' . htmlspecialchars($current_url) . '">' . "\n";
    $tags .= '<meta property="og:image" content="' . htmlspecialchars($og_image) . '">' . "\n";
    $tags .= '<meta property="og:image:width" content="1200">' . "\n";
    $tags .= '<meta property="og:image:height" content="630">' . "\n";
    if (!empty($config['use_dynamic_images'])) {
        $tags .= '<meta property="og:image:type" content="image/png">' . "\n";
    }
    $og_alt = $dynamic_content ? htmlspecialchars($dynamic_content['h1']) : htmlspecialchars($firma_adi);
    $tags .= '<meta property="og:image:alt" content="' . $og_alt . '">' . "\n";
    $tags .= '<meta property="og:site_name" content="' . htmlspecialchars($firma_adi) . '">' . "\n";
    $tags .= '<meta property="og:locale" content="tr_TR">' . "\n";
    $tags .= '<meta property="og:phone_number" content="' . htmlspecialchars($telefon_display) . '">' . "\n";
    $tags .= '<meta name="twitter:card" content="summary_large_image">' . "\n";
    $tags .= '<meta name="twitter:title" content="' . $title . '">' . "\n";
    $tags .= '<meta name="twitter:description" content="' . $description . '">' . "\n";
    $tags .= '<meta name="twitter:image" content="' . htmlspecialchars($og_image) . '">' . "\n";
    $tags .= '<meta name="twitter:image:alt" content="' . $og_alt . '">' . "\n";
    $tags .= '<link rel="canonical" href="' . htmlspecialchars($current_url) . '">' . "\n";
    $tags .= '<link rel="alternate" hreflang="tr" href="' . htmlspecialchars($current_url) . '">' . "\n";
    $tags .= '<link rel="alternate" hreflang="x-default" href="' . htmlspecialchars($current_url) . '">' . "\n";

    return $tags;
}
