<?php
declare(strict_types=1);

const SEO_BASE_URL = 'https://innovarerenovations.com.au';
const SEO_SITE_NAME = 'Innovare Renovations';
const SEO_GA_ID = 'G-2ME3VP923H';
const SEO_GOOGLE_VERIFICATION = '8uWlS-ckeglRN2hOF29cMxvGEKKAXfxxDfzDwD-Fuas';

function seo_pages(): array
{
    return [
        'home' => [
            'slug' => '',
            'label' => 'Home',
            'title' => 'Home Renovations Brisbane & Gold Coast | Innovare Renovations',
            'description' => 'Innovare Renovations delivers expert home renovations, extensions, bathroom and kitchen upgrades across Brisbane and the Gold Coast. QBCC licensed. Fixed-price contracts. Call today.',
            'keywords' => 'home renovations Brisbane, home renovations Gold Coast, renovation builders Brisbane, renovation builders Gold Coast, Innovare Renovations',
            'image' => 'images/Knockdown-and-Rebuild-in-Brisbane.webp',
            'changefreq' => 'weekly',
            'priority' => '1.0',
        ],
        'about' => [
            'slug' => 'about',
            'label' => 'About',
            'title' => 'About Innovare Renovations | Brisbane & Gold Coast Builders',
            'description' => 'Meet the Innovare Renovations team — QBCC-licensed renovation specialists with hands-on experience across Brisbane and Gold Coast homes. Learn our design-led approach.',
            'keywords' => 'about Innovare Renovations, QBCC licensed builders Brisbane, renovation specialists Gold Coast, Innovare Group',
            'image' => 'images/queenslander-renovation.webp',
            'changefreq' => 'monthly',
            'priority' => '0.8',
        ],
        'projects' => [
            'slug' => 'projects',
            'label' => 'Projects',
            'title' => 'Renovation Projects Gallery | Innovare Renovations Brisbane',
            'description' => 'Browse Innovare Renovations\' project gallery — before-and-after renovation photos from Brisbane and Gold Coast homes. Kitchens, bathrooms, extensions and more.',
            'keywords' => 'renovation projects Brisbane, renovation gallery Gold Coast, before and after renovations, Innovare Renovations projects',
            'image' => 'images/home-renovations.webp',
            'changefreq' => 'monthly',
            'priority' => '0.7',
        ],
        'faq' => [
            'slug' => 'faq',
            'label' => 'FAQ',
            'title' => 'Renovation FAQ | Innovare Renovations Brisbane & Gold Coast',
            'description' => 'Answers to the most common renovation questions for Brisbane and Gold Coast homeowners. Timelines, costs, permits, living on site and more. Call Innovare today.',
            'keywords' => 'renovation FAQ Brisbane, renovation questions Gold Coast, renovation costs, renovation timelines, QBCC home warranty',
            'image' => 'images/home-renovations.webp',
            'changefreq' => 'monthly',
            'priority' => '0.7',
        ],
        'contact' => [
            'slug' => 'contact',
            'label' => 'Contact',
            'title' => 'Contact Innovare Renovations | Brisbane & Gold Coast',
            'description' => 'Get in touch with Innovare Renovations for a free renovation consultation. Serving Brisbane, Gold Coast and South East Queensland. Call or enquire online today.',
            'keywords' => 'contact renovation builder Brisbane, renovation quote Gold Coast, free renovation consultation, Innovare Renovations phone',
            'image' => 'images/Innovare-renovations.png',
            'changefreq' => 'monthly',
            'priority' => '0.8',
        ],
        'laundry-renovation' => [
            'slug' => 'laundry-renovation',
            'label' => 'Laundry Renovation',
            'section' => 'Services',
            'title' => 'Laundry Renovation Brisbane & Gold Coast | Innovare Renovations',
            'description' => 'Functional laundry renovations across Brisbane and Gold Coast. Custom cabinetry, tiling, waterproofing. QBCC licensed builders. Get your free quote today.',
            'keywords' => 'laundry renovation Brisbane, laundry renovation Gold Coast, custom laundry cabinetry, laundry waterproofing',
            'image' => 'images/laundry-renovation.webp',
            'changefreq' => 'monthly',
            'priority' => '0.7',
        ],
        'knockdown-rebuilds' => [
            'slug' => 'knockdown-rebuilds',
            'label' => 'Knockdown Rebuilds',
            'section' => 'Services',
            'title' => 'Knockdown Rebuild Brisbane & Gold Coast | Innovare Renovations',
            'description' => 'Complete knockdown rebuild service across Brisbane and Gold Coast. Council approvals, demolition, new construction. QBCC licensed. Fixed-price. Call Innovare today.',
            'keywords' => 'knockdown rebuild Brisbane, knockdown rebuild Gold Coast, demolition and rebuild, new home builder Brisbane',
            'image' => 'images/Knockdown-and-Rebuild-in-Brisbane.webp',
            'changefreq' => 'monthly',
            'priority' => '0.7',
        ],
        'queenslander-renovation' => [
            'slug' => 'queenslander-renovation',
            'label' => 'Queenslander Renovation',
            'section' => 'Services',
            'title' => 'Queenslander Renovation Brisbane & SEQ | Innovare Renovations',
            'description' => 'Expert Queenslander home renovation, raising and restoration across Brisbane and SEQ. Character overlay compliance, sensitive modern updates. QBCC licensed. Call today.',
            'keywords' => 'Queenslander renovation Brisbane, Queenslander raise, character home renovation, Queenslander restoration SEQ',
            'image' => 'images/queenslander-renovation.webp',
            'changefreq' => 'monthly',
            'priority' => '0.7',
        ],
        'heritage-home-renovation' => [
            'slug' => 'heritage-home-renovation',
            'label' => 'Heritage Home Renovation',
            'section' => 'Services',
            'title' => 'Heritage Home Renovation Brisbane & SEQ | Innovare Renovations',
            'description' => 'Sensitive heritage and character home renovation across Brisbane and SEQ. Council-compliant design, period materials, expert trades. QBCC licensed. Call today.',
            'keywords' => 'heritage home renovation Brisbane, character home renovation SEQ, heritage builders Brisbane, council compliant renovation',
            'image' => 'images/heritage-home-renovation-img.webp',
            'changefreq' => 'monthly',
            'priority' => '0.7',
        ],
    ];
}

function seo_company(): array
{
    return [
        'name' => SEO_SITE_NAME,
        'url' => SEO_BASE_URL . '/',
        'logo' => SEO_BASE_URL . '/images/Innovare-renovations.png',
        'description' => 'QBCC-licensed renovation specialists delivering complete home renovations, extensions, pools and knockdown rebuilds across Brisbane, the Gold Coast and South East Queensland under a single fixed-price contract.',
        'telephone' => '+61488773232',
        'email' => 'info@innovarebuilders.com.au',
        'address' => [
            '@type' => 'PostalAddress',
            'streetAddress' => '29/97 Creek St',
            'addressLocality' => 'Brisbane City',
            'addressRegion' => 'QLD',
            'postalCode' => '4000',
            'addressCountry' => 'AU',
        ],
        'areaServed' => ['Brisbane', 'Gold Coast', 'South East Queensland'],
        'identifier' => [
            [
                '@type' => 'PropertyValue',
                'name' => 'QBCC Licence',
                'value' => '15514239',
            ],
            [
                '@type' => 'PropertyValue',
                'name' => 'NSW Builder Licence',
                'value' => '474965C',
            ],
        ],
    ];
}

function seo_page(?string $pageKey = null, ?string $sourceFile = null): array
{
    $pages = seo_pages();
    $key = $pageKey ?: seo_key_from_file($sourceFile);

    if ($key && isset($pages[$key])) {
        return $pages[$key] + ['key' => $key, 'robots' => 'index, follow'];
    }

    $slug = $key ?: 'page';
    $label = seo_label_from_slug($slug);

    return [
        'key' => $slug,
        'slug' => $slug === 'home' ? '' : $slug,
        'label' => $label,
        'title' => $label . ' | ' . SEO_SITE_NAME,
        'description' => SEO_SITE_NAME . ' provides renovation and building services across Brisbane, the Gold Coast and South East Queensland.',
        'keywords' => strtolower($label) . ', renovation builders Brisbane, renovation builders Gold Coast, ' . SEO_SITE_NAME,
        'image' => 'images/Innovare-renovations.png',
        'changefreq' => 'monthly',
        'priority' => '0.5',
        'robots' => 'index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1',
    ];
}

function seo_key_from_file(?string $sourceFile): ?string
{
    if (!$sourceFile) {
        return null;
    }

    $base = pathinfo($sourceFile, PATHINFO_FILENAME);
    return $base === 'index' ? 'home' : $base;
}

function seo_label_from_slug(string $slug): string
{
    return ucwords(str_replace('-', ' ', $slug));
}

function seo_path_for_slug(string $slug): string
{
    return $slug === '' ? '/' : '/' . trim($slug, '/');
}

function seo_canonical_url(array $page): string
{
    return rtrim(SEO_BASE_URL, '/') . seo_path_for_slug((string) $page['slug']);
}

function seo_asset_url(string $path): string
{
    if (preg_match('#^https?://#i', $path)) {
        return $path;
    }

    return rtrim(SEO_BASE_URL, '/') . '/' . ltrim($path, '/');
}

function seo_json(array $data): string
{
    return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
}

function seo_text(string $html): string
{
    $text = preg_replace('/<script\b[^>]*>.*?<\/script>/is', ' ', $html);
    $text = preg_replace('/<style\b[^>]*>.*?<\/style>/is', ' ', (string) $text);
    $text = html_entity_decode(strip_tags((string) $text), ENT_QUOTES | ENT_HTML5, 'UTF-8');
    $text = preg_replace('/\s+/u', ' ', $text);
    return trim((string) $text);
}

function seo_extract_faqs(?string $sourceFile): array
{
    if (!$sourceFile || !is_readable($sourceFile)) {
        return [];
    }

    $html = (string) file_get_contents($sourceFile);
    preg_match_all('/<div\s+class="acc-item">\s*<button\s+class="acc-q">(.*?)<span\s+class="acc-icon"><\/span><\/button>\s*<div\s+class="acc-body">\s*<div\s+class="acc-body-inner">(.*?)<\/div>\s*<\/div>\s*<\/div>/is', $html, $matches, PREG_SET_ORDER);

    $faqs = [];
    foreach ($matches as $match) {
        $question = seo_text($match[1]);
        $answer = seo_text($match[2]);

        if ($question !== '' && $answer !== '') {
            $faqs[] = [
                '@type' => 'Question',
                'name' => $question,
                'acceptedAnswer' => [
                    '@type' => 'Answer',
                    'text' => $answer,
                ],
            ];
        }
    }

    return $faqs;
}

function seo_organization_schema(): array
{
    $company = seo_company();

    return [
        '@context' => 'https://schema.org',
        '@type' => 'Organization',
        '@id' => SEO_BASE_URL . '/#organization',
        'name' => $company['name'],
        'url' => $company['url'],
        'logo' => [
            '@type' => 'ImageObject',
            'url' => $company['logo'],
        ],
        'description' => $company['description'],
        'telephone' => $company['telephone'],
        'email' => $company['email'],
        'address' => $company['address'],
        'areaServed' => $company['areaServed'],
        'identifier' => $company['identifier'],
        'contactPoint' => [
            '@type' => 'ContactPoint',
            'telephone' => $company['telephone'],
            'contactType' => 'customer service',
            'areaServed' => 'AU',
            'availableLanguage' => 'English',
        ],
    ];
}

function seo_breadcrumb_schema(array $page): ?array
{
    if (($page['slug'] ?? '') === '') {
        return null;
    }

    $items = [
        [
            '@type' => 'ListItem',
            'position' => 1,
            'name' => 'Home',
            'item' => SEO_BASE_URL . '/',
        ],
    ];

    if (!empty($page['section'])) {
        $items[] = [
            '@type' => 'ListItem',
            'position' => count($items) + 1,
            'name' => (string) $page['section'],
            'item' => SEO_BASE_URL . '/#services',
        ];
    }

    $items[] = [
        '@type' => 'ListItem',
        'position' => count($items) + 1,
        'name' => (string) $page['label'],
        'item' => seo_canonical_url($page),
    ];

    return [
        '@context' => 'https://schema.org',
        '@type' => 'BreadcrumbList',
        'itemListElement' => $items,
    ];
}

function seo_schema_graph(array $page, ?string $sourceFile): array
{
    $schemas = [seo_organization_schema()];
    $breadcrumb = seo_breadcrumb_schema($page);

    if ($breadcrumb) {
        $schemas[] = $breadcrumb;
    }

    $faqs = seo_extract_faqs($sourceFile);
    if ($faqs) {
        $schemas[] = [
            '@context' => 'https://schema.org',
            '@type' => 'FAQPage',
            'mainEntity' => $faqs,
        ];
    }

    return $schemas;
}

function render_seo_head(?string $pageKey = null, ?string $sourceFile = null, array $options = []): void
{
    $page = seo_page($pageKey, $sourceFile);
    $canonical = seo_canonical_url($page);
    $image = seo_asset_url((string) $page['image']);
    $robots = (string) ($page['robots'] ?? 'index, follow');
    $inlineCss = trim((string) ($options['inline_css'] ?? ''));
    ?>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title><?= htmlspecialchars((string) $page['title'], ENT_QUOTES, 'UTF-8') ?></title>
<meta name="description" content="<?= htmlspecialchars((string) $page['description'], ENT_QUOTES, 'UTF-8') ?>">
<meta name="keywords" content="<?= htmlspecialchars((string) $page['keywords'], ENT_QUOTES, 'UTF-8') ?>">
<meta name="robots" content="<?= htmlspecialchars($robots, ENT_QUOTES, 'UTF-8') ?>">
<meta name="author" content="<?= SEO_SITE_NAME ?>">
<meta name="referrer" content="strict-origin-when-cross-origin">
<meta name="theme-color" content="#111027">
<meta name="google-site-verification" content="<?= SEO_GOOGLE_VERIFICATION ?>">
<link rel="canonical" href="<?= htmlspecialchars($canonical, ENT_QUOTES, 'UTF-8') ?>">
<link rel="icon" type="image/png" href="/images/favicon.png">
<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=Archivo:wght@500;600;700;800&family=Hanken+Grotesk:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/assets/css/style.css">
<meta property="og:locale" content="en_AU">
<meta property="og:type" content="website">
<meta property="og:site_name" content="<?= SEO_SITE_NAME ?>">
<meta property="og:title" content="<?= htmlspecialchars((string) $page['title'], ENT_QUOTES, 'UTF-8') ?>">
<meta property="og:description" content="<?= htmlspecialchars((string) $page['description'], ENT_QUOTES, 'UTF-8') ?>">
<meta property="og:url" content="<?= htmlspecialchars($canonical, ENT_QUOTES, 'UTF-8') ?>">
<meta property="og:image" content="<?= htmlspecialchars($image, ENT_QUOTES, 'UTF-8') ?>">
<meta property="og:image:alt" content="<?= htmlspecialchars(SEO_SITE_NAME, ENT_QUOTES, 'UTF-8') ?>">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="<?= htmlspecialchars((string) $page['title'], ENT_QUOTES, 'UTF-8') ?>">
<meta name="twitter:description" content="<?= htmlspecialchars((string) $page['description'], ENT_QUOTES, 'UTF-8') ?>">
<meta name="twitter:image" content="<?= htmlspecialchars($image, ENT_QUOTES, 'UTF-8') ?>">
<?php if ($inlineCss !== ''): ?>
<style>
<?= $inlineCss . "\n" ?>
</style>
<?php endif; ?>
<script async src="https://www.googletagmanager.com/gtag/js?id=<?= SEO_GA_ID ?>"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', '<?= SEO_GA_ID ?>');
</script>
<?php foreach (seo_schema_graph($page, $sourceFile) as $schema): ?>
<script type="application/ld+json">
<?= seo_json($schema) . "\n" ?>
</script>
<?php endforeach; ?>
</head>
<?php
}

function seo_public_routes(): array
{
    $root = dirname(__DIR__);
    $files = array_merge(glob($root . '/*.html') ?: [], glob($root . '/*.php') ?: []);
    $excluded = [
        'contact-data.php' => true,
        'sitemap.php' => true,
    ];
    $routes = [];

    foreach ($files as $file) {
        $basename = basename($file);
        if (isset($excluded[$basename])) {
            continue;
        }

        $key = seo_key_from_file($file);
        $page = seo_page($key, $file);
        if (str_starts_with((string) ($page['robots'] ?? ''), 'noindex')) {
            continue;
        }

        $canonical = seo_canonical_url($page);
        $routes[$canonical] = [
            'loc' => $canonical,
            'lastmod' => gmdate('Y-m-d', (int) filemtime($file)),
            'changefreq' => (string) ($page['changefreq'] ?? 'monthly'),
            'priority' => (string) ($page['priority'] ?? '0.5'),
        ];
    }

    ksort($routes);
    return array_values($routes);
}
