<?php

/**
 * ITSWEBER CMS – Default Seed Data
 *
 * Inserts default settings, pages, menus, and homepage sections
 * during installation.
 */

use App\Core\Database;

function seedDefaultData(Database $db, array $siteConfig = [], string $language = 'de'): void
{
    $siteName = $siteConfig['site_name'] ?? ($language === 'en' ? 'My Website' : 'Meine Website');
    $siteTagline = $siteConfig['site_tagline'] ?? '';
    $contactEmail = $siteConfig['contact_email'] ?? '';

    $copyrightSuffix = $language === 'en' ? '. All rights reserved.' : '. Alle Rechte vorbehalten.';

    // Default settings
    $settings = [
        ['site_name', $siteName, 'general'],
        ['site_tagline', $siteTagline, 'general'],
        ['contact_email', $contactEmail, 'general'],
        ['contact_phone', '', 'general'],
        ['footer_text', '', 'general'],
        ['copyright', '© ' . date('Y') . ' ' . $siteName . $copyrightSuffix, 'general'],
        ['active_theme', $siteConfig['theme'] ?? 'default', 'branding'],
        ['logo', '', 'branding'],
        ['favicon', '', 'branding'],
        ['seo_title', $siteName, 'seo'],
        ['seo_description', '', 'seo'],
        ['social_facebook', '', 'social'],
        ['social_instagram', '', 'social'],
        ['social_linkedin', '', 'social'],
        ['social_x', '', 'social'],
        ['social_youtube', '', 'social'],
    ];

    foreach ($settings as [$key, $value, $group]) {
        $db->insert('iw_settings', [
            'setting_key'   => $key,
            'setting_value' => $value,
            'setting_group' => $group,
        ]);
    }

    // Language-dependent labels
    $isEn = ($language === 'en');

    // Default pages
    $now = date('Y-m-d H:i:s');

    $db->insert('iw_pages', [
        'title'           => 'Home',
        'slug'            => 'home',
        'content'         => '',
        'template'        => 'home',
        'status'          => 'published',
        'sort_order'      => 0,
        'is_homepage'     => 1,
        'show_title'      => 1,
        'page_type'       => 'home',
        'seo_title'       => '',
        'seo_description' => '',
        'created_at'      => $now,
        'updated_at'      => $now,
    ]);

    $db->insert('iw_pages', [
        'title'           => $isEn ? 'About' : 'Über uns',
        'slug'            => $isEn ? 'about' : 'ueber-uns',
        'content'         => '',
        'template'        => 'page',
        'status'          => 'published',
        'sort_order'      => 1,
        'is_homepage'     => 0,
        'show_title'      => 1,
        'page_type'       => 'page',
        'seo_title'       => '',
        'seo_description' => '',
        'created_at'      => $now,
        'updated_at'      => $now,
    ]);

    $db->insert('iw_pages', [
        'title'           => $isEn ? 'Contact' : 'Kontakt',
        'slug'            => 'contact',
        'content'         => '',
        'template'        => 'contact',
        'status'          => 'published',
        'sort_order'      => 2,
        'is_homepage'     => 0,
        'show_title'      => 1,
        'page_type'       => 'contact',
        'seo_title'       => '',
        'seo_description' => '',
        'created_at'      => $now,
        'updated_at'      => $now,
    ]);

    // System/module pages – editable intro content + SEO via /admin/pages
    // These may already exist from migration 021, so check before inserting
    // and update the language-aware title if the page was pre-created.
    $systemPages = [
        [
            'title'      => $isEn ? 'Gallery' : 'Galerie',
            'slug'       => 'gallery',
            'template'   => 'gallery',
            'page_type'  => 'gallery',
            'sort_order' => 20,
        ],
        [
            'title'      => 'Blog',
            'slug'       => 'blog',
            'template'   => 'blog',
            'page_type'  => 'blog',
            'sort_order' => 21,
        ],
        [
            'title'      => $isEn ? 'Events' : 'Veranstaltungen',
            'slug'       => 'events',
            'template'   => 'events',
            'page_type'  => 'events',
            'sort_order' => 22,
        ],
        [
            'title'      => 'Downloads',
            'slug'       => 'download',
            'template'   => 'downloads',
            'page_type'  => 'downloads',
            'sort_order' => 23,
        ],
    ];

    foreach ($systemPages as $sp) {
        $existing = $db->fetch("SELECT id FROM iw_pages WHERE slug = :slug LIMIT 1", ['slug' => $sp['slug']]);
        if (!$existing) {
            $db->insert('iw_pages', [
                'title'           => $sp['title'],
                'slug'            => $sp['slug'],
                'content'         => '',
                'template'        => $sp['template'],
                'status'          => 'published',
                'sort_order'      => $sp['sort_order'],
                'is_homepage'     => 0,
                'show_title'      => 1,
                'page_type'       => $sp['page_type'],
                'seo_title'       => '',
                'seo_description' => '',
                'created_at'      => $now,
                'updated_at'      => $now,
            ]);
        } else {
            // Update language-aware title and ensure correct page_type
            $db->query(
                "UPDATE iw_pages SET title = :title, page_type = :ptype, updated_at = :now WHERE id = :id",
                ['title' => $sp['title'], 'ptype' => $sp['page_type'], 'now' => $now, 'id' => $existing['id']]
            );
        }
    }

    // Default menus
    $mainMenuId = $db->insert('iw_menus', [
        'location' => 'main',
        'name'     => $isEn ? 'Main Navigation' : 'Hauptnavigation',
    ]);

    $footerMenuId = $db->insert('iw_menus', [
        'location' => 'footer',
        'name'     => $isEn ? 'Footer Navigation' : 'Footer-Navigation',
    ]);

    // Main menu items
    $aboutUrl = $isEn ? '/about' : '/ueber-uns';
    $db->insert('iw_menu_items', ['menu_id' => $mainMenuId, 'label' => $isEn ? 'Home' : 'Startseite', 'url' => '/', 'sort_order' => 0, 'is_visible' => 1, 'target' => '_self']);
    $db->insert('iw_menu_items', ['menu_id' => $mainMenuId, 'label' => $isEn ? 'About' : 'Über uns', 'url' => $aboutUrl, 'sort_order' => 1, 'is_visible' => 1, 'target' => '_self']);
    $db->insert('iw_menu_items', ['menu_id' => $mainMenuId, 'label' => 'Blog', 'url' => '/blog', 'sort_order' => 2, 'is_visible' => 1, 'target' => '_self']);
    $db->insert('iw_menu_items', ['menu_id' => $mainMenuId, 'label' => $isEn ? 'Gallery' : 'Galerie', 'url' => '/gallery', 'sort_order' => 3, 'is_visible' => 1, 'target' => '_self']);
    $db->insert('iw_menu_items', ['menu_id' => $mainMenuId, 'label' => $isEn ? 'Contact' : 'Kontakt', 'url' => '/contact', 'sort_order' => 4, 'is_visible' => 1, 'target' => '_self']);

    // Footer menu items
    $privacyUrl = $isEn ? '/privacy' : '/datenschutz';
    $imprintUrl = $isEn ? '/imprint' : '/impressum';
    $db->insert('iw_menu_items', ['menu_id' => $footerMenuId, 'label' => $isEn ? 'Privacy Policy' : 'Datenschutz', 'url' => $privacyUrl, 'sort_order' => 0, 'is_visible' => 1, 'target' => '_self']);
    $db->insert('iw_menu_items', ['menu_id' => $footerMenuId, 'label' => $isEn ? 'Imprint' : 'Impressum', 'url' => $imprintUrl, 'sort_order' => 1, 'is_visible' => 1, 'target' => '_self']);

    // Default homepage sections (language-aware)
    $sections = [
        ['hero', 'Hero', json_encode([
            'title'    => $siteName,
            'subtitle' => $siteTagline,
            'image'    => '',
            'cta_text' => $isEn ? 'Learn More' : 'Mehr erfahren',
            'cta_url'  => $aboutUrl,
        ]), 1, 0],
        ['intro', $isEn ? 'Introduction' : 'Einleitung', json_encode([
            'title' => $isEn ? 'Welcome' : 'Willkommen',
            'text'  => '',
        ]), 1, 1],
        ['features', $isEn ? 'Features' : 'Leistungen', json_encode([
            'title' => $isEn ? 'What We Offer' : 'Unsere Leistungen',
            'items' => [],
        ]), 1, 2],
        ['gallery_preview', $isEn ? 'Gallery Preview' : 'Galerie-Vorschau', json_encode([
            'title' => $isEn ? 'Our Work' : 'Unsere Arbeiten',
            'count' => 6,
        ]), 0, 3],
        ['blog_preview', $isEn ? 'Blog Preview' : 'Blog-Vorschau', json_encode([
            'title' => $isEn ? 'Latest News' : 'Aktuelle Beiträge',
            'count' => 3,
        ]), 0, 4],
        ['events_preview', $isEn ? 'Upcoming Events' : 'Kommende Veranstaltungen', json_encode([
            'title'    => $isEn ? 'Upcoming Events' : 'Kommende Veranstaltungen',
            'count'    => 2,
            'cta_text' => $isEn ? 'View all events' : 'Alle Events ansehen',
            'cta_url'  => '/events',
        ]), 0, 5],
        ['cta', 'Call to Action', json_encode([
            'title'    => $isEn ? 'Get in Touch' : 'Kontakt aufnehmen',
            'text'     => '',
            'cta_text' => $isEn ? 'Contact Us' : 'Kontakt',
            'cta_url'  => '/contact',
        ]), 1, 6],
        // topic_cards and highlight_grid are inserted by migration
        // 012_add_new_homepage_sections (INSERT IGNORE) – omitted here to
        // prevent a duplicate-key error on fresh installs where the migration
        // always runs before the seed.
    ];

    foreach ($sections as [$key, $title, $content, $active, $order]) {
        // Write to new iw_page_sections table (v3.2.0+)
        $db->insert('iw_page_sections', [
            'page_context'  => 'homepage',
            'section_type'  => $key,
            'instance_label' => $title,
            'content'       => $content,
            'is_active'     => $active,
            'sort_order'    => $order,
        ]);
    }
}
