<?php
declare(strict_types=1);

function seo_defaults(): array
{
    $defaults = site_default_settings();
    return [
        'title' => (string) setting('site_title', $defaults['site_title']),
        'description' => (string) setting('meta_description', $defaults['meta_description']),
        'canonical' => current_url(),
        'robots' => 'index,follow,max-image-preview:large,max-snippet:-1,max-video-preview:-1',
        'image' => url((string) setting('og_image', $defaults['og_image'])),
        'type' => 'website',
        'breadcrumbs' => [],
        'schema' => [],
        'amp' => null,
    ];
}

function schema_address(): array
{
    return schema_clean([
        '@type' => 'PostalAddress',
        'streetAddress' => (string) setting('address', 'Nekrut Hotel, İstanbul, Türkiye'),
        'addressLocality' => (string) setting('address_locality', 'İstanbul'),
        'addressRegion' => (string) setting('address_region', 'İstanbul'),
        'postalCode' => (string) setting('postal_code', ''),
        'addressCountry' => 'TR',
    ]);
}

function schema_logo_url(): string
{
    $customLogo = (string) setting('logo_dark', '/assets/img/logo.svg');
    if ($customLogo === '/assets/img/logo.svg') {
        return url('/assets/img/logo-schema.png');
    }
    return url($customLogo);
}

function corporate_organization_schema(): array
{
    $sameAs = array_values(array_filter(array_map(
        static fn($value): string => trim((string) $value),
        [setting('instagram_url'), setting('facebook_url'), setting('linkedin_url'), setting('youtube_url')]
    ), static fn(string $value): bool => filter_var($value, FILTER_VALIDATE_URL) !== false));

    $customLogo = (string) setting('logo_dark', '/assets/img/logo.svg');
    $logo = [
        '@type' => 'ImageObject',
        '@id' => base_url() . '/#logo',
        'url' => schema_logo_url(),
        'contentUrl' => schema_logo_url(),
    ];
    // Yalnız ölçülerini bildiğimiz kurulum logosunda kesin genişlik/yükseklik yayımla.
    if ($customLogo === '/assets/img/logo.svg') {
        $logo['width'] = 512;
        $logo['height'] = 512;
    }

    return schema_clean([
        '@type' => 'Organization',
        '@id' => base_url() . '/#organization',
        'name' => (string) setting('hotel_name', 'Nekrut Hotel'),
        'url' => (string) setting('hotel_url', 'https://nekruthotel.com'),
        'logo' => $logo,
        'sameAs' => $sameAs,
    ]);
}

function hotel_schema(): array
{
    return schema_clean([
        '@type' => 'Hotel',
        '@id' => base_url() . '/#hotel',
        'name' => (string) setting('hotel_name', 'Nekrut Hotel'),
        'url' => (string) setting('hotel_url', 'https://nekruthotel.com'),
        'image' => url((string) setting('og_image', '/assets/img/og-cover.png')),
        'address' => schema_address(),
        'starRating' => ['@type' => 'Rating', 'ratingValue' => 5, 'bestRating' => 5],
        'parentOrganization' => ['@id' => base_url() . '/#organization'],
    ]);
}

function reserve_action_schema(?string $target = null): array
{
    $target ??= url('/rezervasyon');
    return [
        '@type' => 'ReserveAction',
        'target' => [
            '@type' => 'EntryPoint',
            'urlTemplate' => $target,
            'actionPlatform' => [
                'https://schema.org/DesktopWebPlatform',
                'https://schema.org/MobileWebPlatform',
            ],
        ],
        'result' => [
            '@type' => 'Reservation',
            'name' => 'Wellness ve spa rezervasyonu',
        ],
    ];
}

function organization_schema(): array
{
    $site = base_url();
    return schema_clean([
        '@type' => 'DaySpa',
        '@id' => $site . '/#wellness',
        'name' => (string) setting('brand_name', 'Nekrut Wellness & Spa'),
        'url' => $site . '/',
        'logo' => ['@id' => $site . '/#logo'],
        'image' => url((string) setting('og_image', '/assets/img/og-cover.png')),
        'description' => (string) setting('brand_description', site_default_settings()['brand_description']),
        'telephone' => (string) setting('phone', ''),
        'email' => (string) setting('email', 'wellness@nekrut.com'),
        'priceRange' => (string) setting('price_range', '₺₺₺'),
        'address' => schema_address(),
        'geo' => setting('latitude') && setting('longitude') ? [
            '@type' => 'GeoCoordinates',
            'latitude' => (float) setting('latitude'),
            'longitude' => (float) setting('longitude'),
        ] : null,
        'parentOrganization' => ['@id' => $site . '/#organization'],
        'containedInPlace' => ['@id' => $site . '/#hotel'],
        'areaServed' => ['@type' => 'City', 'name' => 'İstanbul'],
        'openingHoursSpecification' => opening_hours_schema(),
        'potentialAction' => reserve_action_schema(),
    ]);
}

function opening_hours_schema(): array
{
    if (!db_table_exists('business_hours')) return [];
    $days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
    $rows = db()->query('SELECT weekday,open_time,close_time,is_closed FROM business_hours ORDER BY weekday')->fetchAll();
    $out = [];
    foreach ($rows as $row) {
        $weekday = (int) $row['weekday'];
        if ((int) $row['is_closed'] || $weekday < 1 || $weekday > 7) continue;
        $out[] = [
            '@type' => 'OpeningHoursSpecification',
            'dayOfWeek' => 'https://schema.org/' . $days[$weekday - 1],
            'opens' => substr((string) $row['open_time'], 0, 5),
            'closes' => substr((string) $row['close_time'], 0, 5),
        ];
    }
    return $out;
}

function website_schema(): array
{
    return [
        '@type' => 'WebSite',
        '@id' => base_url() . '/#website',
        'url' => base_url() . '/',
        'name' => (string) setting('brand_name', 'Nekrut Wellness & Spa'),
        'alternateName' => (string) setting('hotel_name', 'Nekrut Hotel') . ' Wellness & Spa',
        'inLanguage' => 'tr-TR',
        'publisher' => ['@id' => base_url() . '/#wellness'],
    ];
}

function breadcrumb_schema(array $items): ?array
{
    if (!$items) return null;
    $elements = [];
    foreach ($items as $i => $item) {
        $elements[] = [
            '@type' => 'ListItem',
            'position' => $i + 1,
            'name' => (string) $item['name'],
            'item' => (string) $item['url'],
        ];
    }
    return [
        '@type' => 'BreadcrumbList',
        '@id' => current_url() . '#breadcrumb',
        'itemListElement' => $elements,
    ];
}

function schema_clean(mixed $value): mixed
{
    if (!is_array($value)) return $value;
    $isList = array_is_list($value);
    $clean = [];
    foreach ($value as $key => $item) {
        $item = schema_clean($item);
        if ($item === null || $item === '' || $item === []) continue;
        $clean[$key] = $item;
    }
    return $isList ? array_values($clean) : $clean;
}

function schema_datetime(?string $value): ?string
{
    if (!$value) return null;
    $ts = strtotime($value);
    return $ts === false ? null : date(DATE_ATOM, $ts);
}

function seo_graph(array $seo): array
{
    $page = schema_clean([
        '@type' => 'WebPage',
        '@id' => $seo['canonical'] . '#webpage',
        'url' => $seo['canonical'],
        'name' => $seo['title'],
        'description' => $seo['description'],
        'inLanguage' => 'tr-TR',
        'isPartOf' => ['@id' => base_url() . '/#website'],
        'about' => ['@id' => base_url() . '/#wellness'],
        'primaryImageOfPage' => !empty($seo['image']) ? [
            '@type' => 'ImageObject',
            '@id' => $seo['canonical'] . '#primaryimage',
            'url' => $seo['image'],
            'contentUrl' => $seo['image'],
        ] : null,
        'breadcrumb' => !empty($seo['breadcrumbs']) ? ['@id' => current_url() . '#breadcrumb'] : null,
    ]);

    $graph = [
        corporate_organization_schema(),
        hotel_schema(),
        organization_schema(),
        website_schema(),
        $page,
    ];
    if ($crumb = breadcrumb_schema($seo['breadcrumbs'] ?? [])) $graph[] = $crumb;
    foreach (($seo['schema'] ?? []) as $schema) {
        if (is_array($schema)) $graph[] = $schema;
    }

    return schema_clean([
        '@context' => 'https://schema.org',
        '@graph' => array_values(array_filter($graph)),
    ]);
}
