<?php
$site_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]/";
$base_url = rtrim($site_url, '/') . '/';
$current_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

$firma_adi = 'İstanbul Ajans';
$firma_kisa = 'İstanbul Ajans';
$slogan = 'Manken, Hostes & Etkinlik Personeli Ajansı';
$telefon_raw = '+905325810330';
$telefon_display = '0532 581 03 30';
$whatsapp = '905325810330';
$adres = 'Şişli / İstanbul';
$instagram_url = 'https://www.instagram.com/kdraydin34';

function buildWhatsappUrl($whatsapp, $hizmet_slug, $hizmetler, $il_slug, $ilce_slug, $mahalle_slug, $turkey_data) {
    if (!$hizmet_slug || !isset($hizmetler[$hizmet_slug])) {
        $mesaj = 'Merhaba, manken ve hostes hizmetleriniz hakkında bilgi ve teklif almak istiyorum.';
    } else {
        $hizmet_name = $hizmetler[$hizmet_slug]['name'];
        list($il_name, $ilce_name, $mahalle_name) = getLocationNames($il_slug, $ilce_slug, $mahalle_slug, $turkey_data);

        if ($mahalle_name && $ilce_name && $il_name) {
            $lokasyon = $mahalle_name . ', ' . $ilce_name . ', ' . $il_name;
        } elseif ($ilce_name && $il_name) {
            $lokasyon = $ilce_name . ', ' . $il_name;
        } elseif ($il_name) {
            $lokasyon = $il_name;
        } else {
            $lokasyon = null;
        }

        if ($lokasyon) {
            $mesaj = 'Merhaba, ' . $lokasyon . ' bölgesindeki etkinliğimiz için ' . $hizmet_name . ' hizmeti hakkında teklif almak istiyorum.';
        } else {
            $mesaj = 'Merhaba, ' . $hizmet_name . ' hizmetiniz hakkında bilgi ve fiyat teklifi almak istiyorum.';
        }
    }
    return 'https://wa.me/' . $whatsapp . '?text=' . urlencode($mesaj);
}

$email = 'info@istanbulajans.com.tr';

$izinli_iller = ['adana', 'adiyaman', 'afyonkarahisar', 'agri', 'amasya', 'ankara', 'antalya', 'artvin', 'aydin', 'balikesir', 'bilecik', 'bingol', 'bitlis', 'bolu', 'burdur', 'bursa', 'canakkale', 'cankiri', 'corum', 'denizli', 'diyarbakir', 'edirne', 'elazig', 'erzincan', 'erzurum', 'eskisehir', 'gaziantep', 'giresun', 'gumushane', 'hakkari', 'hatay', 'isparta', 'mersin', 'istanbul', 'izmir', 'kars', 'kastamonu', 'kayseri', 'kirklareli', 'kirsehir', 'kocaeli', 'konya', 'kutahya', 'malatya', 'manisa', 'kahramanmaras', 'mardin', 'mugla', 'mus', 'nevsehir', 'nigde', 'ordu', 'rize', 'sakarya', 'samsun', 'siirt', 'sinop', 'sivas', 'tekirdag', 'tokat', 'trabzon', 'tunceli', 'sanliurfa', 'usak', 'van', 'yozgat', 'zonguldak', 'aksaray', 'bayburt', 'karaman', 'kirikkale', 'batman', 'sirnak', 'bartin', 'ardahan', 'igdir', 'yalova', 'karabuk', 'kilis', 'osmaniye', 'duzce'];

require_once __DIR__ . '/hizmetler-data.php';
require_once __DIR__ . '/includes/branding.php';
require_once __DIR__ . '/includes/article-generator.php';
require_once __DIR__ . '/includes/seo.php';

$brand_assets = resolveBrandAssets($base_url);
$hizmetler = buildHizmetlerArray();

$menu_hizmet_slugs = array_rand($hizmetler, min(6, count($hizmetler)));
if (!is_array($menu_hizmet_slugs)) { $menu_hizmet_slugs = [$menu_hizmet_slugs]; }
$menu_hizmetler = array_intersect_key($hizmetler, array_flip($menu_hizmet_slugs));

require_once 'turkey.php';

$request_uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$request_uri = trim($request_uri, '/');
$url_parts = !empty($request_uri) ? explode('/', $request_uri) : [];

$hizmet_slug = null;
$il_slug = null;
$ilce_slug = null;
$mahalle_slug = null;
$page_type = 'homepage';

if (count($url_parts) >= 1 && isset($hizmetler[$url_parts[0]])) {
    $hizmet_slug = $url_parts[0];
    $page_type = 'hizmet';
    if (count($url_parts) >= 2 && isset($turkey_data[$url_parts[1]]) && in_array($url_parts[1], $izinli_iller)) {
        $il_slug = $url_parts[1];
        $page_type = 'hizmet-il';
        if (count($url_parts) >= 3 && isset($turkey_data[$il_slug]['ilceler'][$url_parts[2]])) {
            $ilce_slug = $url_parts[2];
            $page_type = 'hizmet-il-ilce';
            if (count($url_parts) >= 4 && isset($turkey_data[$il_slug]['ilceler'][$ilce_slug]['mahalleler'][$url_parts[3]])) {
                $mahalle_slug = $url_parts[3];
                $page_type = 'hizmet-il-ilce-mahalle';
            }
        }
    }
}

function getLocationNames($il_slug, $ilce_slug, $mahalle_slug, $turkey_data) {
    $il_name = $il_slug ? $turkey_data[$il_slug]['name'] : null;
    $ilce_name = ($il_slug && $ilce_slug) ? $turkey_data[$il_slug]['ilceler'][$ilce_slug]['name'] : null;
    $mahalle_name = ($il_slug && $ilce_slug && $mahalle_slug) ? $turkey_data[$il_slug]['ilceler'][$ilce_slug]['mahalleler'][$mahalle_slug] : null;
    return [$il_name, $ilce_name, $mahalle_name];
}

function buildSeoTitle($hizmet_name, $il_slug, $ilce_slug, $mahalle_slug, $turkey_data, $telefon_display) {
    list($il_name, $ilce_name, $mahalle_name) = getLocationNames($il_slug, $ilce_slug, $mahalle_slug, $turkey_data);
    if ($mahalle_name) {
        $lokasyon = $mahalle_name;
    } elseif ($ilce_name) {
        $lokasyon = $ilce_name;
    } elseif ($il_name) {
        $lokasyon = $il_name;
    } else {
        return $hizmet_name . ' | İstanbul Ajans | Manken & Hostes Ajansı | ☎️ ' . $telefon_display;
    }
    return $lokasyon . ' ' . $hizmet_name . ' | İstanbul Ajans | Manken & Hostes Ajansı | ☎️ ' . $telefon_display;
}

function buildMetaDescription($hizmet_name, $il_slug, $ilce_slug, $mahalle_slug, $turkey_data) {
    list($il_name, $ilce_name, $mahalle_name) = getLocationNames($il_slug, $ilce_slug, $mahalle_slug, $turkey_data);
    if ($mahalle_name && $ilce_name) {
        return $mahalle_name . ' ve ' . $ilce_name . ' bölgesinde ' . $hizmet_name . ' hizmeti. Profesyonel hostes, manken ve event personeli için İstanbul Ajans ile iletişime geçin.';
    } elseif ($ilce_name && $il_name) {
        return $ilce_name . ', ' . $il_name . ' bölgesinde ' . $hizmet_name . ' hizmeti. Fuar, kongre, lansman ve organizasyonlarınız için deneyimli kadro.';
    } elseif ($il_name) {
        return $il_name . ' genelinde ' . $hizmet_name . ' hizmeti. İstanbul Ajans ile güvenilir manken, hostes ve etkinlik personeli temini.';
    }
    return 'Profesyonel ' . $hizmet_name . ' hizmeti. Manken, hostes, fuar ve etkinlik personeli kiralama. İstanbul Ajans ile hemen teklif alın.';
}

function buildMetaKeywords($hizmet_name, $il_slug, $ilce_slug, $mahalle_slug, $turkey_data) {
    list($il_name, $ilce_name, $mahalle_name) = getLocationNames($il_slug, $ilce_slug, $mahalle_slug, $turkey_data);
    $base_keywords = ['Manken Ajansı', 'Hostes Ajansı', 'Fuar Hostesi', 'Etkinlik Personeli', 'Model Ajansı', 'Tanıtım Hostesi', 'Organizasyon Ajansı', 'Cast Ajansı', 'VIP Hostes', 'Fotomodel'];
    if ($mahalle_name) {
        $lokasyon = $mahalle_name;
    } elseif ($ilce_name) {
        $lokasyon = $ilce_name;
    } elseif ($il_name) {
        $lokasyon = $il_name;
    } else {
        return $hizmet_name . ', İstanbul Ajans ' . $hizmet_name . ', manken ajansı, hostes ajansı, ' . implode(', ', $base_keywords);
    }
    $prefixed = array_map(fn($k) => $lokasyon . ' ' . $k, $base_keywords);
    return $lokasyon . ' ' . $hizmet_name . ', ' . $hizmet_name . ' ' . $lokasyon . ', ' . $lokasyon . ' manken hostes, ' . implode(', ', $prefixed);
}

function buildH1($hizmet_name, $il_slug, $ilce_slug, $mahalle_slug, $turkey_data) {
    list($il_name, $ilce_name, $mahalle_name) = getLocationNames($il_slug, $ilce_slug, $mahalle_slug, $turkey_data);
    if ($mahalle_name && $ilce_name) {
        return trim($mahalle_name . ' ' . $hizmet_name);
    } elseif ($ilce_name && $il_name) {
        return trim($ilce_name . ' ' . $hizmet_name);
    } elseif ($il_name) {
        return trim($il_name . ' ' . $hizmet_name);
    }
    return trim($hizmet_name);
}



$dynamic_content = null;
$aktif_hizmet = null;
if ($hizmet_slug) {
    $aktif_hizmet = $hizmetler[$hizmet_slug];
    $dynamic_content = generateDynamicContent(
        $aktif_hizmet, $il_slug, $ilce_slug, $mahalle_slug, $turkey_data, $telefon_display, $hizmet_slug, $base_url, $hizmetler
    );
}

function generateStructuredData($firma_adi, $telefon_display, $email, $hizmet, $hizmet_slug, $il_slug, $ilce_slug, $mahalle_slug, $turkey_data, $dynamic_content, $base_url, $current_url, $page_type) {
    global $slogan, $hizmetler, $telefon_raw, $brand_assets, $instagram_url, $adres;

    $homepage_seo = ($page_type === 'homepage') ? buildHomepageSeo($firma_adi, $slogan, $telefon_display, $adres) : null;

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

    $org_id    = $base_url . '#organization';
    $site_id   = $base_url . '#website';
    $page_id   = $current_url . '#webpage';
    $bc_id     = $current_url . '#breadcrumb';
    $svc_id    = $current_url . '#service';
    $brand_id  = $base_url . '#brand';

    $logo_url = !empty($brand_assets['logo_url']) ? $brand_assets['logo_url'] : $base_url . 'images/logo.png';
    $logo_obj = [
        '@type' => 'ImageObject',
        '@id' => $base_url . '#logo',
        'url' => $logo_url,
        'contentUrl' => $logo_url,
        'width' => 250,
        'height' => 80,
        'caption' => $firma_adi
    ];

    $brand = [
        '@type' => 'Brand',
        '@id' => $brand_id,
        'name' => $firma_adi,
        'logo' => $logo_obj
    ];

    $contact_point_cs = [
        '@type' => 'ContactPoint',
        'telephone' => $telefon_display,
        'contactType' => 'customer service',
        'availableLanguage' => ['Turkish'],
        'areaServed' => 'TR',
        'hoursAvailable' => [
            '@type' => 'OpeningHoursSpecification',
            'dayOfWeek' => ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
            'opens' => '08:00',
            'closes' => '18:00'
        ]
    ];

    $contact_point_sales = [
        '@type' => 'ContactPoint',
        'telephone' => $telefon_display,
        'contactType' => 'sales',
        'availableLanguage' => ['Turkish'],
        'areaServed' => 'TR'
    ];

    $knows_about = [
        'Manken Ajansı', 'Hostes Ajansı', 'Fuar Hostesi', 'Etkinlik Personeli',
        'Model Ajansı', 'Tanıtım Hostesi', 'Organizasyon Ajansı', 'Cast Ajansı',
        'VIP Hostes', 'Fotomodel Ajansı', 'Tercüman Hostes', 'Brand Ambassador',
        'Fuar Mankeni', 'Etkinlik Hostesi'
    ];

    // Hizmet listesi — fiyat bilgisi içermez (ItemList + Service)
    $itemlist_elements = [];
    if (!empty($hizmetler) && is_array($hizmetler)) {
        $pos_i = 1;
        foreach ($hizmetler as $h_slug => $h_data) {
            $h_url = $base_url . $h_slug . '/';
            $itemlist_elements[] = [
                '@type' => 'ListItem',
                'position' => $pos_i++,
                'name' => $h_data['name'],
                'url' => $h_url,
                'item' => [
                    '@type' => 'Service',
                    'name' => $h_data['name'],
                    'serviceType' => $h_data['name'],
                    'url' => $h_url,
                    'provider' => ['@id' => $org_id],
                    'areaServed' => ['@type' => 'Country', 'name' => 'Turkey'],
                ],
            ];
        }
    }

    $organization = [
        '@type' => ['LocalBusiness', 'EmploymentAgency', 'ProfessionalService'],
        '@id' => $org_id,
        'name' => $firma_adi,
        'alternateName' => ['İstanbul Ajans', 'istanbulajans'],
        'legalName' => $firma_adi,
        'description' => $slogan . ' Manken, hostes, fuar personeli, etkinlik ekibi ve casting hizmetleri. Şişli / İstanbul merkezli, Türkiye geneli hizmet.',
        'slogan' => $slogan,
        'url' => $base_url,
        'logo' => $logo_obj,
        'image' => $logo_obj,
        'brand' => $brand,
        'telephone' => $telefon_display,
        'email' => $email,
        'foundingDate' => '2010',
        'address' => [
            '@type' => 'PostalAddress',
            'streetAddress' => 'Şişli',
            'addressLocality' => 'Şişli',
            'addressRegion' => 'İstanbul',
            'postalCode' => '34360',
            'addressCountry' => 'TR'
        ],
        'geo' => [
            '@type' => 'GeoCoordinates',
            'latitude' => SEO_GEO_LAT,
            'longitude' => SEO_GEO_LNG,
        ],
        'contactPoint' => [$contact_point_cs, $contact_point_sales],
        'openingHoursSpecification' => $contact_point_cs['hoursAvailable'],
        'areaServed' => [
            ['@type' => 'Country', 'name' => 'Turkey'],
            ['@type' => 'City', 'name' => 'İstanbul'],
        ],
        'knowsAbout' => $knows_about,
        'knowsLanguage' => ['tr-TR'],
        'hasCredential' => [
            '@type' => 'EducationalOccupationalCredential',
            'credentialCategory' => 'certification',
            'name' => 'Profesyonel Personel Yönetimi ve Ajans Hizmetleri'
        ],
        'sameAs' => [
            $instagram_url
        ],
        'mainEntityOfPage' => $base_url
    ];
    $schema['@graph'][] = $organization;

    // Sektörel terimler sözlüğü (DefinedTermSet)
    $glossary_terms = [
        ['Hostes', 'Etkinlik, fuar ve organizasyonlarda karşılama, yönlendirme ve tanıtım yapan profesyonel personel.'],
        ['Manken', 'Defile, çekim, katalog ve tanıtım faaliyetlerinde ürün veya markayı temsil eden model.'],
        ['Casting', 'Etkinlik veya çekim için uygun manken, hostes veya oyuncu seçim süreci.'],
        ['Fuar Hostesi', 'Fuar ve expo standlarında ziyaretçi karşılama ve ürün tanıtımı yapan personel.'],
        ['VIP Hostes', 'Protokol ve özel davetlerde üst düzey misafirleri karşılayan deneyimli hostes.'],
        ['Brand Ambassador', 'Markayı temsil eden, tanıtım ve etkileşim sağlayan marka elçisi.'],
        ['Event Personeli', 'Etkinliklerde operasyonel destek sağlayan organizasyon personeli.'],
        ['Fotomodel', 'Fotoğraf ve video çekimlerinde profesyonel poz veren model.'],
        ['Tercüman Hostes', 'Yabancı dil bilen, çeviri desteği sağlayan hostes personeli.'],
        ['Roadshow Ekibi', 'Saha tanıtım ve ürün sampling aktivitelerinde görev alan mobil ekip.']
    ];
    $defined_terms = [];
    $term_set_id = $base_url . '#ajans-sozlugu';
    foreach ($glossary_terms as $ti => $term) {
        $defined_terms[] = [
            '@type' => 'DefinedTerm',
            '@id' => $base_url . '#terim-' . ($ti + 1),
            'name' => $term[0],
            'description' => $term[1],
            'inDefinedTermSet' => ['@id' => $term_set_id]
        ];
    }
    $schema['@graph'][] = [
        '@type' => 'DefinedTermSet',
        '@id' => $term_set_id,
        'name' => 'Manken ve Hostes Terimleri Sözlüğü',
        'description' => 'Manken, hostes ve etkinlik sektöründe sık kullanılan terimler ve açıklamaları.',
        'inLanguage' => 'tr-TR',
        'hasDefinedTerm' => $defined_terms
    ];

    // Tüm ajans hizmetlerinin listesi (ItemList)
    if (!empty($itemlist_elements)) {
        $schema['@graph'][] = [
            '@type' => 'ItemList',
            '@id' => $base_url . '#hizmet-listesi',
            'name' => $firma_adi . ' Hizmetleri',
            'itemListElement' => $itemlist_elements
        ];
    }

    $website = [
        '@type' => 'WebSite',
        '@id' => $site_id,
        'url' => $base_url,
        'name' => $firma_adi,
        'description' => $slogan,
        'publisher' => ['@id' => $org_id],
        'inLanguage' => 'tr-TR',
    ];
    $schema['@graph'][] = $website;

    if ($page_type === 'homepage') {
        $hp_title = $homepage_seo['title'];
        $hp_desc = $homepage_seo['description'];

        $schema['@graph'][] = [
            '@type' => ['WebPage', 'CollectionPage'],
            '@id' => $page_id,
            'url' => $current_url,
            'name' => $hp_title,
            'description' => $hp_desc,
            'isPartOf' => ['@id' => $site_id],
            'about' => ['@id' => $org_id],
            'mainEntity' => ['@id' => $org_id],
            'inLanguage' => 'tr-TR',
            'datePublished' => '2018-06-01',
            'dateModified' => date('Y-m-d'),
            'speakable' => [
                '@type' => 'SpeakableSpecification',
                'cssSelector' => ['.home-seo-h1', '.home-seo-intro'],
            ],
        ];

        $hero_video = resolveHeroVideo($base_url);
        if ($hero_video['exists']) {
            $schema['@graph'][] = [
                '@type' => 'VideoObject',
                '@id' => $base_url . '#hero-video',
                'name' => $firma_adi . ' Tanıtım Videosu',
                'description' => $hp_desc,
                'thumbnailUrl' => $hero_video['poster'],
                'contentUrl' => $hero_video['url'],
                'uploadDate' => date('Y-m-d'),
                'inLanguage' => 'tr-TR',
                'isPartOf' => ['@id' => $page_id],
            ];
        }

        $schema['@graph'][] = [
            '@type' => 'SiteNavigationElement',
            '@id' => $base_url . '#siteNav',
            'name' => $firma_adi . ' Site Navigasyonu',
            'hasPart' => [
                ['@type' => 'SiteNavigationElement', 'name' => 'Ana Sayfa', 'url' => $base_url],
                ['@type' => 'SiteNavigationElement', 'name' => 'Kurumsal', 'url' => $base_url . '#kurumsal'],
                ['@type' => 'SiteNavigationElement', 'name' => 'Hizmetlerimiz', 'url' => $base_url . '#hizmetlerimiz'],
                ['@type' => 'SiteNavigationElement', 'name' => 'Galeri', 'url' => $base_url . '#galeri'],
                ['@type' => 'SiteNavigationElement', 'name' => 'Referanslar', 'url' => $base_url . '#referanslar'],
                ['@type' => 'SiteNavigationElement', 'name' => 'İletişim', 'url' => $base_url . '#iletisim'],
            ],
        ];
    }

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

        $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' => $bc_id, 'itemListElement' => $breadcrumb_items];

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

        $service_img_url = $base_url . 'og-image.php?mode=og&title=' . urlencode(mb_substr($dynamic_content['h1'], 0, 80, 'UTF-8'));

        $service_schema = [
            '@type' => 'Service',
            '@id' => $svc_id,
            'name' => $dynamic_content['h1'],
            'alternateName' => $hizmet['name'],
            'description' => $dynamic_content['meta_description'],
            'provider' => ['@id' => $org_id],
            'brand' => ['@id' => $brand_id],
            'image' => ['@type' => 'ImageObject', 'url' => $service_img_url, 'name' => $hizmet['name']],
            'serviceType' => $hizmet['name'],
            'category' => 'Manken ve Hostes Ajansı Hizmetleri',
            'availableChannel' => [
                '@type' => 'ServiceChannel',
                'serviceUrl' => $current_url,
                'servicePhone' => $contact_point_cs
            ],
            'mainEntityOfPage' => ['@id' => $page_id]
        ];
        if ($loc_place) {
            $service_schema['areaServed'] = $loc_place;
        } else {
            $service_schema['areaServed'] = ['@type' => 'Country', 'name' => 'Turkey'];
        }
        if (!empty($hizmet['benefits'])) {
            $service_schema['additionalProperty'] = array_map(function ($b) {
                return ['@type' => 'PropertyValue', 'name' => 'Avantaj', 'value' => $b];
            }, $hizmet['benefits']);
        }
        $schema['@graph'][] = $service_schema;

        $webpage_type = in_array($page_type, ['hizmet', 'hizmet-il', 'hizmet-il-ilce']) ? 'CollectionPage' : 'WebPage';

        $webpage_node = [
            '@type' => $webpage_type,
            '@id' => $page_id,
            'url' => $current_url,
            'name' => $dynamic_content['title'],
            'description' => $dynamic_content['meta_description'],
            'isPartOf' => ['@id' => $site_id],
            'breadcrumb' => ['@id' => $bc_id],
            'mainEntity' => ['@id' => $svc_id],
            'about' => ['@id' => $org_id],
            'inLanguage' => 'tr-TR',
            'primaryImageOfPage' => ['@type' => 'ImageObject', 'url' => $service_img_url],
            'datePublished' => schemaDatePublished($hizmet_slug . ($il_slug ?? '') . ($ilce_slug ?? '') . ($mahalle_slug ?? '')),
            'dateModified' => date('Y-m-d'),
            'speakable' => [
                '@type' => 'SpeakableSpecification',
                'cssSelector' => ['h1', '.article-body h2'],
            ],
        ];
        if ($loc_place) {
            $webpage_node['mentions'] = ['@id' => $org_id];
        }
        $schema['@graph'][] = $webpage_node;

        $article_plain = trim(preg_replace('/\s+/', ' ', strip_tags($dynamic_content['article'] ?? '')));
        $word_count = $article_plain ? count(preg_split('/\s+/', $article_plain)) : 0;
        $headline = mb_substr($dynamic_content['h1'], 0, 108, 'UTF-8');
        $article_node = [
            '@type' => 'Article',
            '@id' => $current_url . '#article',
            'headline' => $headline,
            'name' => $dynamic_content['h1'],
            'description' => $dynamic_content['meta_description'],
            'articleSection' => $hizmet['name'],
            'inLanguage' => 'tr-TR',
            'image' => ['@type' => 'ImageObject', 'url' => $service_img_url, 'width' => 1200, 'height' => 630],
            'author' => ['@id' => $org_id],
            'publisher' => ['@id' => $org_id],
            'isPartOf' => ['@id' => $page_id],
            'mainEntityOfPage' => ['@id' => $page_id],
            'about' => ['@id' => $svc_id],
            'datePublished' => schemaDatePublished($hizmet_slug . ($il_slug ?? '') . ($ilce_slug ?? '') . ($mahalle_slug ?? '')),
            'dateModified' => date('Y-m-d'),
            'keywords' => $dynamic_content['meta_keywords'] ?? $hizmet['name']
        ];
        if ($word_count > 0) {
            $article_node['wordCount'] = $word_count;
        }
        $schema['@graph'][] = $article_node;

        if ($loc_place) {
            $loc_place['geo'] = [
                '@type' => 'GeoCoordinates',
                'latitude' => SEO_GEO_LAT,
                'longitude' => SEO_GEO_LNG,
            ];
            $schema['@graph'][] = $loc_place + ['@id' => $current_url . '#place'];
        }

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

        if (in_array($page_type, ['hizmet', 'hizmet-il', 'hizmet-il-ilce', 'hizmet-il-ilce-mahalle'])) {
            $how_to_steps = [
                ['name' => 'Talebinizi İletin', 'text' => 'Telefon veya WhatsApp üzerinden etkinlik detaylarınızı ve personel ihtiyacınızı bize iletin.'],
                ['name' => 'İhtiyaç Analizi ve Teklif', 'text' => 'Etkinlik türü, süre ve dil gereksinimleriniz analiz edilerek size özel teklif hazırlanır.'],
                ['name' => 'Personel Seçimi', 'text' => 'Profil ve deneyime göre en uygun hostes, manken veya personel önerilir.'],
                ['name' => 'Ön Hazırlık', 'text' => 'Seçilen ekip etkinlik öncesi bilgilendirilir ve sahaya hazırlanır.'],
                ['name' => 'Sahada Uygulama', 'text' => 'Etkinlik günü profesyonel personel ekibiniz görev alır.']
            ];
            $how_to_step_objs = [];
            foreach ($how_to_steps as $i => $step) {
                $how_to_step_objs[] = [
                    '@type' => 'HowToStep',
                    'position' => $i + 1,
                    'name' => $step['name'],
                    'text' => $step['text']
                ];
            }
            $schema['@graph'][] = [
                '@type' => 'HowTo',
                '@id' => $current_url . '#howto',
                'name' => $dynamic_content['h1'] . ' Süreci Nasıl İşler?',
                'description' => $dynamic_content['meta_description'],
                'step' => $how_to_step_objs,
                'isPartOf' => ['@id' => $page_id]
            ];
        }
    }

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

class InstagramCache {
    private $cache_file = 'instagram_cache.json';
    private $cache_time = 21600; 
    private $username = 'kdraydin34'; 

    public function getPosts() {
        if (file_exists($this->cache_file) && (time() - filemtime($this->cache_file)) < $this->cache_time) {
            $content = file_get_contents($this->cache_file);
            if ($content) {
                $data = json_decode($content, true);
                if (isset($data['posts']) && is_array($data['posts']) && !empty($data['posts'])) {
                    return $data['posts'];
                }
            }
        }

        $posts = $this->fetchFromInstagram();
        if (!empty($posts)) {
            file_put_contents($this->cache_file, json_encode(['time' => time(), 'posts' => $posts]));
            return $posts;
        }

        if (file_exists($this->cache_file)) {
            $content = file_get_contents($this->cache_file);
            if ($content) {
                $data = json_decode($content, true);
                if (isset($data['posts']) && is_array($data['posts'])) {
                    return $data['posts'];
                }
            }
        }
        return [];
    }

    private function downloadImage($url, $filepath) {
        $ch = curl_init($url);
        $fp = fopen($filepath, 'wb');
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)');
        curl_exec($ch);
        curl_close($ch);
        fclose($fp);
        if (filesize($filepath) == 0) {
            @unlink($filepath);
            return false;
        }
        return true;
    }

    private function fetchFromInstagram() {
        $url = "https://www.instagram.com/api/v1/users/web_profile_info/?username=" . $this->username;
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_TIMEOUT => 15,
            CURLOPT_HTTPHEADER => [
                'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
                'Accept: */*',
                'Accept-Language: tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7',
                'X-IG-App-ID: 936619743392459', 
            ],
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => 0
        ]);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode !== 200 || !$response) return [];

        $data = json_decode($response, true);
        $posts = [];
        if (isset($data['data']['user']['edge_owner_to_timeline_media']['edges'])) {
            $edges = $data['data']['user']['edge_owner_to_timeline_media']['edges'];
            
            $site_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]/";
            $base = rtrim($site_url, '/') . '/';

            $img_dir = __DIR__ . '/instagram_images';
            if (!is_dir($img_dir)) {
                @mkdir($img_dir, 0755, true);
            }

            foreach ($edges as $edge) {
                $node = $edge['node'];
                $img_url = $node['display_url'];
                $is_video = $node['is_video'];
                $shortcode = $node['shortcode'];
                $likes = $node['edge_liked_by']['count'] ?? 0;
                $comments = $node['edge_media_to_comment']['count'] ?? 0;

                $local_filename = $shortcode . '.jpg';
                $local_filepath = $img_dir . '/' . $local_filename;
                $public_filepath = $base . 'instagram_images/' . $local_filename;

                if (!file_exists($local_filepath) || filesize($local_filepath) === 0) {
                    $this->downloadImage($img_url, $local_filepath);
                }

                if (file_exists($local_filepath) && filesize($local_filepath) > 0) {
                    $final_img = $public_filepath;
                } else {
                    $final_img = $base . 'instagram_proxy.php?url=' . urlencode($img_url);
                }

                $posts[] = [
                    'image' => $final_img,
                    'link' => 'https://www.instagram.com/p/' . $shortcode . '/',
                    'likes' => $likes,
                    'comments' => $comments,
                    'is_video' => $is_video
                ];
            }
        }
        return $posts;
    }
}

$igCache = new InstagramCache();
$instagram_posts = $igCache->getPosts();

function getReferansImages($base_url) {
    $dir = __DIR__ . '/images/referans';
    if (!is_dir($dir)) {
        return [];
    }
    $images = [];
    foreach (scandir($dir) as $file) {
        if ($file === '.' || $file === '..' || $file === '.gitkeep') {
            continue;
        }
        $path = $dir . DIRECTORY_SEPARATOR . $file;
        if (!is_file($path)) {
            continue;
        }
        if (@getimagesize($path) === false) {
            continue;
        }
        $images[] = [
            'url' => rtrim($base_url, '/') . '/images/referans/' . rawurlencode($file),
            'name' => pathinfo($file, PATHINFO_FILENAME),
        ];
    }
    usort($images, fn($a, $b) => strnatcasecmp($a['name'], $b['name']));
    return $images;
}

$referans_gorseller = getReferansImages($base_url);
$hero_video = resolveHeroVideo($base_url);
$homepage_seo = ($page_type === 'homepage') ? buildHomepageSeo($firma_adi, $slogan, $telefon_display, $adres) : null;

if ($aktif_hizmet && $dynamic_content) {
    $_og_title = mb_substr($dynamic_content['h1'], 0, 80, 'UTF-8');
    $og_image = $base_url . 'og-image.php?mode=og&title=' . urlencode($_og_title);
} else {
    $og_image = $base_url . 'og-image.php?mode=og&title=' . urlencode($firma_adi . ' | ' . $slogan);
}

$robots_content = 'index, follow';
if ($page_type !== 'homepage' && !$hizmet_slug) {
    $robots_content = 'noindex, follow';
}

$_meta_title = $dynamic_content
    ? htmlspecialchars($dynamic_content['title'])
    : htmlspecialchars($homepage_seo['title'] ?? ('Manken & Hostes Ajansı | Fuar, Etkinlik Personeli | ' . $firma_adi));
$_meta_desc = $dynamic_content
    ? htmlspecialchars($dynamic_content['meta_description'])
    : htmlspecialchars($homepage_seo['description'] ?? ('İstanbul Ajans - Profesyonel manken, hostes, fuar ve etkinlik personeli hizmetleri. Şişli / İstanbul merkezli, 81 ilde hizmet.'));
$_meta_keywords = $dynamic_content
    ? htmlspecialchars($dynamic_content['meta_keywords'])
    : htmlspecialchars($homepage_seo['keywords'] ?? 'manken ajansı, hostes ajansı, fuar hostesi, etkinlik personeli, model ajansı, tanıtım hostesi, istanbul ajans');
$_meta_url = htmlspecialchars($current_url);
$_meta_og_image = htmlspecialchars($og_image);
$_meta_og_type = ($page_type !== 'homepage' && $aktif_hizmet) ? 'article' : 'website';
list($_il_n, $_ilce_n, $_mah_n) = getLocationNames($il_slug, $ilce_slug, $mahalle_slug, $turkey_data);
$_geo = buildGeoMeta($_il_n, $_ilce_n, $_mah_n, $adres);
?>
<!DOCTYPE html>
<html lang="tr" class="scroll-smooth">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta http-equiv="content-language" content="tr-TR">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, viewport-fit=cover">
    <meta name="HandheldFriendly" content="True">
    <meta name="MobileOptimized" content="320">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <meta name="apple-mobile-web-app-title" content="<?php echo htmlspecialchars($firma_kisa); ?>">
    <meta name="format-detection" content="telephone=no">
    <meta name="theme-color" content="#E91E63">
    <title><?php echo $_meta_title; ?></title>
    <meta name="description" content="<?php echo $_meta_desc; ?>">
    <meta name="keywords" content="<?php echo $_meta_keywords; ?>">
    <meta name="robots" content="<?php echo $robots_content; ?>, max-snippet:-1, max-image-preview:large, max-video-preview:-1">
    <meta name="googlebot" content="<?php echo $robots_content; ?>, max-snippet:-1, max-image-preview:large, max-video-preview:-1">
    <meta name="bingbot" content="<?php echo $robots_content; ?>, max-snippet:-1, max-image-preview:large">
    
    <meta name="author" content="<?php echo htmlspecialchars($firma_adi); ?>">
    <meta name="publisher" content="<?php echo htmlspecialchars($firma_adi); ?>">
    <meta name="copyright" content="<?php echo '© ' . date('Y') . ' ' . htmlspecialchars($firma_adi); ?>">
    <meta name="application-name" content="<?php echo htmlspecialchars($firma_adi); ?>">
    <meta name="revisit-after" content="3 days">
    <meta name="language" content="Turkish">
    <meta name="rating" content="general">
    <meta name="distribution" content="global">
    <meta name="referrer" content="strict-origin-when-cross-origin">
    <meta name="geo.region" content="<?php echo htmlspecialchars($_geo['region']); ?>">
    <meta name="geo.placename" content="<?php echo htmlspecialchars($_geo['placename']); ?>">
    <meta name="geo.position" content="<?php echo htmlspecialchars($_geo['position']); ?>">
    <meta name="ICBM" content="<?php echo htmlspecialchars($_geo['icbm']); ?>">
    <meta property="business:contact_data:street_address" content="Şişli">
    <meta property="business:contact_data:locality" content="İstanbul">
    <meta property="business:contact_data:country_name" content="Türkiye">
    <meta property="business:contact_data:phone_number" content="<?php echo htmlspecialchars($telefon_display); ?>">
    <meta property="business:contact_data:website" content="<?php echo htmlspecialchars($base_url); ?>">
    <meta property="business:contact_data:email" content="<?php echo htmlspecialchars($email); ?>">

    <?php if ($page_type === 'homepage' && $homepage_seo && $hero_video['exists']): ?>
    <meta property="og:video" content="<?php echo htmlspecialchars($hero_video['url']); ?>">
    <meta property="og:video:type" content="video/mp4">
    <meta property="og:video:width" content="1920">
    <meta property="og:video:height" content="1080">
    <?php endif; ?>

    <meta property="og:type" content="<?php echo $_meta_og_type; ?>">
    <meta property="og:title" content="<?php echo $_meta_title; ?>">
    <meta property="og:description" content="<?php echo $_meta_desc; ?>">
    <meta property="og:url" content="<?php echo $_meta_url; ?>">
    <meta property="og:site_name" content="<?php echo htmlspecialchars($firma_adi); ?>">
    <meta property="og:locale" content="tr_TR">
    <meta property="og:image" content="<?php echo $_meta_og_image; ?>">
    <meta property="og:image:width" content="1200">
    <meta property="og:image:height" content="630">
    <meta property="og:image:type" content="image/png">
    <meta property="og:image:alt" content="<?php echo $_meta_title; ?>">
    
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:title" content="<?php echo $_meta_title; ?>">
    <meta name="twitter:description" content="<?php echo $_meta_desc; ?>">
    <meta name="twitter:image" content="<?php echo $_meta_og_image; ?>">
    <meta name="twitter:image:alt" content="<?php echo $_meta_title; ?>">
    <meta name="twitter:label1" content="Hizmet">
    <meta name="twitter:data1" content="<?php echo $aktif_hizmet ? htmlspecialchars($aktif_hizmet['name']) : 'Manken & Hostes Hizmeti'; ?>">
    <meta name="twitter:label2" content="Telefon">
    <meta name="twitter:data2" content="<?php echo htmlspecialchars($telefon_display); ?>">
    <link rel="canonical" href="<?php echo $_meta_url; ?>">
    <link rel="alternate" hreflang="tr-TR" href="<?php echo $_meta_url; ?>">
    <link rel="alternate" hreflang="x-default" href="<?php echo htmlspecialchars($base_url); ?>">

    <?php if ($page_type === 'hizmet-il-ilce' && $il_slug): ?>
    <link rel="up" href="<?php echo htmlspecialchars($base_url . $hizmet_slug . '/' . $il_slug . '/'); ?>">
    <?php endif; ?>
    <?php if ($page_type === 'hizmet-il-ilce-mahalle' && $ilce_slug): ?>
    <link rel="up" href="<?php echo htmlspecialchars($base_url . $hizmet_slug . '/' . $il_slug . '/' . $ilce_slug . '/'); ?>">
    <?php endif; ?>
    <?php if (!empty($brand_assets['has_favicon'])): ?>
    <link rel="icon" type="<?php echo faviconMimeType($brand_assets['favicon_file']); ?>" href="<?php echo htmlspecialchars($brand_assets['favicon_url']); ?>">
    <link rel="shortcut icon" type="<?php echo faviconMimeType($brand_assets['favicon_file']); ?>" href="<?php echo htmlspecialchars($brand_assets['favicon_url']); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($brand_assets['favicon_url']); ?>">
    <?php else: ?>
    <link rel="icon" type="image/png" href="<?php echo $base_url; ?>images/fav.png">
    <link rel="shortcut icon" type="image/png" href="<?php echo $base_url; ?>images/fav.png">
    <link rel="apple-touch-icon" href="<?php echo $base_url; ?>images/fav.png">
    <?php endif; ?>

    <?php if ($page_type === 'homepage' && $hero_video['exists']): ?>
    <link rel="preload" as="video" href="<?php echo htmlspecialchars($hero_video['url']); ?>" type="video/mp4">
    <?php endif; ?>
    <?php if ($dynamic_content): ?>
    <meta property="article:published_time" content="<?php echo schemaDatePublished($hizmet_slug . ($il_slug ?? '') . ($ilce_slug ?? '') . ($mahalle_slug ?? '')); ?>">
    <meta property="article:modified_time" content="<?php echo date('c'); ?>">
    <meta property="article:section" content="<?php echo htmlspecialchars($aktif_hizmet['name'] ?? ''); ?>">
    <meta property="article:tag" content="<?php echo $_meta_keywords; ?>">
    <?php endif; ?>
    <link rel="dns-prefetch" href="//fonts.googleapis.com">
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link rel="dns-prefetch" href="//cdnjs.cloudflare.com">
    <link rel="dns-prefetch" href="//wa.me">
    <?php
    echo generateStructuredData(
        $firma_adi, $telefon_display, $email,
        $aktif_hizmet, $hizmet_slug,
        $il_slug, $ilce_slug, $mahalle_slug,
        $turkey_data, $dynamic_content,
        $base_url, $current_url, $page_type
    );
    ?>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Playfair+Display:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                        serif: ['Playfair Display', 'Georgia', 'serif']
                    },
                    colors: {
                        brand: {
                            primary: '#E91E63',
                            secondary: '#C2185B',
                            dark: '#1a1a1a',
                            light: '#f9fafb',
                            accent: '#E91E63',
                            softgreen: '#FCE4EC',
                            slate: '#6b7280',
                            pure: '#FFFFFF'
                        }
                    }
                }
            }
        }
    </script>
    <style>
        body { background-color: #fff; }
        .custom-scrollbar::-webkit-scrollbar { width: 5px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: #f9fafb; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: #d1d5db; border-radius: 5px; }
        html { scroll-behavior: smooth; }
    </style>
</head>
<body class="antialiased font-sans flex flex-col min-h-screen text-gray-800 selection:bg-pink-100">
<?php include __DIR__ . '/partials/header.php'; ?>
    <?php if ($page_type === 'homepage'): ?>
    <?php include __DIR__ . '/partials/homepage.php'; ?>
    <?php else: ?>
    <?php include __DIR__ . '/partials/hizmet-detay.php'; ?>
    <?php endif; ?>
<?php include __DIR__ . '/partials/footer.php'; ?>
</body>
</html>
