<?php
$settingsJsonld = settings('jsonld')->getAll();
$schemaGraph = [];

// 1. Organization
$organizationSchema = [
    "@type" => "Organization",
    "@id" => $currentUrl . "#organization",
    "name" => $settingsJsonld['organization_name'] ?? ($seo['title'] ?? $pageContent['title']),
    "url" => $settingsJsonld['organization_url'] ?? $currentDomain,
    "logo" => !empty($settingsContent['header-logo']) ? $currentDomain . '/' . json_decode($settingsContent['header-logo'], true)['src'] : ''
];

// Add sameAs if organization_same_as is filled
if (!empty($settingsJsonld['organization_same_as'])) {
    $sameAsUrls = array_filter(array_map('trim', explode("\n", $settingsJsonld['organization_same_as'])));
    if (!empty($sameAsUrls)) {
        $organizationSchema["sameAs"] = $sameAsUrls;
    }
}

// Add license if filled
if (!empty($settingsJsonld['license_url'])) {
    $organizationSchema["license"] = $settingsJsonld['license_url'];
}

$schemaGraph[] = $organizationSchema;

// 2. Casino Brand
$casinoBrand = [
    "@type" => ["Casino", "Brand"],
    "@id" => $currentUrl . "#brand-casino-entity",
    "name" => $seo['title'],
    "url" => $seo['canonical'] ?? $currentUrl,
    "image" => !empty($settingsContent['header-logo']) ? $currentDomain . '/' . json_decode($settingsContent['header-logo'], true)['src'] : '',
    "aggregateRating" => [
        "@type" => "AggregateRating",
        "ratingValue" => $settingsJsonld['rating_value'] ?? "5",
        "ratingCount" => $settingsJsonld['review_count'] ?? "150",
        "worstRating" => $settingsJsonld['worst_rating'] ?? "1",
        "bestRating" => $settingsJsonld['best_rating'] ?? "5"
    ],
    "priceRange" => "$",
    "openingHoursSpecification" => [
        [
            "@type" => "OpeningHoursSpecification",
            "dayOfWeek" => ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
            "opens" => "00:00",
            "closes" => "23:59"
        ]
    ],
    "parentOrganization" => [
        "@id" => $currentUrl . "#organization"
    ]
];

// Add address if any field is filled
if (!empty($settingsContent['address-street']) || !empty($settingsContent['address-city']) || 
    !empty($settingsContent['address-region']) || !empty($settingsContent['address-postal']) || 
    !empty($settingsContent['address-country'])) {
    $casinoBrand["address"] = [
        "@type" => "PostalAddress",
        "streetAddress" => $settingsContent['address-street'] ?? '',
        "addressLocality" => $settingsContent['address-city'] ?? '',
        "addressRegion" => $settingsContent['address-region'] ?? '',
        "postalCode" => $settingsContent['address-postal'] ?? '',
        "addressCountry" => $settingsContent['address-country'] ?? ''
    ];
}

$schemaGraph[] = $casinoBrand;

// 3. WebSite
$schemaGraph[] = [
    "@type" => "WebSite",
    "url" => $currentDomain,
    "name" => $seo['title'] ?? $pageData['title'],
    "publisher" => [
        "@id" => $currentUrl . "#organization"
    ]
];

// 4. WebPage
$schemaGraph[] = [
    "@type" => "WebPage",
    "@id" => $currentUrl . "#webpage",
    "name" => $seo['title'],
    "description" => $seo['description'],
    "inLanguage" => $seo['extra_fields']['locale'] ?? 'en',
    "url" => $currentUrl,
    "dateModified" => $settingsContent['modified-date'] ?? date('Y-m-d'),
    "author" => [
        "@type" => "Person",
        "name" => $settingsContent['author-name'] ?? '',
        "image" => !empty($settingsContent['author-img']) ? $currentDomain . '/' . $settingsContent['author-img'] : '',
        "jobTitle" => "Casino Expert"
    ],
    "publisher" => [
        "@id" => $currentUrl . "#organization"
    ]
];

// 5. Review
$schemaGraph[] = [
    "@type" => "Review",
    "itemReviewed" => [
        "@id" => $currentUrl . "#brand-casino-entity"
    ],
    "reviewRating" => [
        "@type" => "Rating",
        "ratingValue" => "5",
        "bestRating" => "5"
    ],
    "author" => [
        "@id" => $currentUrl . "#organization"
    ],
    "name" => $seo['title'],
    "reviewBody" => $seo['description'],
    "datePublished" => $settingsContent['published-date'] ?? date('Y-m-d')
];

// 6. Offer (if bonus fields are filled)
if (!empty($settingsContent['bonus-name']) || !empty($settingsContent['bonus-description'])) {
    $schemaGraph[] = [
        "@type" => "Offer",
        "@id" => $currentUrl . "#offer",
        "name" => $settingsContent['bonus-name'] ?? '',
        "description" => $settingsContent['bonus-description'] ?? '',
        "url" => $settingsContent['bonus-url'] ?? $currentUrl,
        "price" => $settingsContent['bonus-price'] ?? '',
        "priceCurrency" => $settingsContent['bonus-currency'] ?? 'EUR',
        "availability" => "https://schema.org/InStock",
        "eligibleCustomerType" => "https://schema.org/NewCustomer",
        "offeredBy" => [
            "@id" => $currentUrl . "#organization"
        ]
    ];
}

// 7. BreadcrumbList
$schemaGraph[] = [
    "@type" => "BreadcrumbList",
    "itemListElement" => [
        [
            "@type" => "ListItem",
            "position" => 1,
            "name" => $settingsJsonld['breadcrumb_home_name'] ?? ($seo['title'] ?? $pageData['title']),
            "item" => $currentUrl
        ]
    ]
];

// 8. FAQPage
if (!empty($faqItems)) {
    $faqQuestions = [];
    foreach ($faqItems as $item) {
        // Support both formats: content FAQ (question/answer) and pages FAQ (extra_fields)
        if (isset($item['question']) && isset($item['answer'])) {
            // Content FAQ format
            $faqQuestions[] = [
                "@type" => "Question",
                "name" => htmlspecialchars($item['question']),
                "acceptedAnswer" => [
                    "@type" => "Answer",
                    "text" => htmlspecialchars($item['answer'])
                ]
            ];
        } elseif (isset($item['extra_fields']) && is_array($item['extra_fields'])) {
            // Pages FAQ format - check extra_fields
            foreach ($item['extra_fields'] as $faqItem) {
                if (isset($faqItem['question']) && isset($faqItem['answer'])) {
                    $faqQuestions[] = [
                        "@type" => "Question",
                        "name" => htmlspecialchars($faqItem['question']),
                        "acceptedAnswer" => [
                            "@type" => "Answer",
                            "text" => htmlspecialchars($faqItem['answer'])
                        ]
                    ];
                }
            }
        }
    }
    
    if (!empty($faqQuestions)) {
        $schemaGraph[] = [
            "@type" => "FAQPage",
            "mainEntityOfPage" => [
                "@id" => $currentUrl . "#webpage"
            ],
            "mainEntity" => $faqQuestions
        ];
    }
}

// 9. SoftwareApplication (if app fields are filled)
if (!empty($settingsJsonld['download_url']) || !empty($settingsJsonld['app_name'])) {
    $schemaGraph[] = [
        "@type" => "SoftwareApplication",
        "@id" => $currentUrl . "#app",
        "name" => $settingsJsonld['app_name'] ?? (($seo['title'] ?? $pageData['title']) . " App"),
        "operatingSystem" => $settingsJsonld['operating_system'] ?? "Android, iOS",
        "applicationCategory" => $settingsJsonld['application_category'] ?? "GameApplication",
        "provider" => [
            "@id" => $currentUrl . "#organization"
        ],
        "offers" => [
            "@type" => "Offer",
            "price" => "0",
            "priceCurrency" => "EUR",
            "availability" => "https://schema.org/InStock"
        ],
        "downloadUrl" => $settingsJsonld['download_url'] ?? '',
        "aggregateRating" => [
            "@type" => "AggregateRating",
            "ratingValue" => $settingsJsonld['rating_value'] ?? "5",
            "ratingCount" => $settingsJsonld['review_count'] ?? "99",
            "worstRating" => $settingsJsonld['worst_rating'] ?? "1",
            "bestRating" => $settingsJsonld['best_rating'] ?? "5"
        ],
        "author" => [
            "@id" => $currentUrl . "#organization"
        ]
    ];
}

// Generate final JSON-LD
$schemaMarkup = [
    "@context" => "https://schema.org",
    "@graph" => array_filter($schemaGraph) // Remove null entries
];

echo json_encode($schemaMarkup, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
?>