<?php

/**
 * Theme-specific seed: Estate (Real Estate / Immobilien)
 *
 * Creates real estate demo content with property listings, open house events,
 * and neighbourhood galleries. Used during installation when the Estate theme
 * is selected.
 */
function seedEstateTheme(\App\Core\Database $db, string $language = 'de'): void
{
    $isDE = $language === 'de';

    // Pages
    $pages = [
        ['title' => $isDE ? 'Immobilien' : 'Properties', 'slug' => $isDE ? 'immobilien' : 'properties', 'template' => 'page', 'content' => $isDE ? '<p>Entdecken Sie unsere aktuellen Immobilienangebote.</p>' : '<p>Discover our current property listings.</p>', 'sort_order' => 3],
        ['title' => $isDE ? 'Verkaufen' : 'Sell', 'slug' => $isDE ? 'verkaufen' : 'sell', 'template' => 'page', 'content' => $isDE ? '<p>Sie moechten Ihre Immobilie verkaufen? Wir begleiten Sie durch den gesamten Prozess.</p>' : '<p>Want to sell your property? We guide you through the entire process.</p>', 'sort_order' => 4],
        ['title' => $isDE ? 'Bewertung' : 'Valuation', 'slug' => $isDE ? 'bewertung' : 'valuation', 'template' => 'page', 'content' => $isDE ? '<p>Erhalten Sie eine kostenlose Erstbewertung Ihrer Immobilie.</p>' : '<p>Get a free initial valuation of your property.</p>', 'sort_order' => 5],
    ];

    foreach ($pages as $page) {
        $exists = $db->fetch("SELECT id FROM iw_pages WHERE slug = :slug LIMIT 1", ['slug' => $page['slug']]);
        if (!$exists) {
            $page['status']     = 'published';
            $page['page_type']  = 'page';
            $page['created_at'] = date('Y-m-d H:i:s');
            $page['updated_at'] = date('Y-m-d H:i:s');
            $db->insert('iw_pages', $page);
        }
    }

    // Blog posts (market insights)
    $adminUser = $db->fetch("SELECT id FROM iw_users LIMIT 1");
    $authorId  = $adminUser['id'] ?? 1;
    $newsCat   = $db->fetch("SELECT id FROM iw_blog_categories WHERE slug IN ('news', 'neuigkeiten') LIMIT 1");
    $catId     = $newsCat['id'] ?? null;

    $posts = [
        [
            'title'       => $isDE ? 'Immobilienmarkt 2026: Trends und Prognosen' : 'Real Estate Market 2026: Trends and Forecasts',
            'slug'        => $isDE ? 'immobilienmarkt-2026' : 'real-estate-market-2026',
            'excerpt'     => $isDE ? 'Ein Ueberblick ueber die aktuelle Marktlage.' : 'An overview of the current market situation.',
            'content'     => $isDE ? '<p>Der Immobilienmarkt zeigt sich trotz wirtschaftlicher Herausforderungen stabil. Besonders gefragte Lagen verzeichnen weiterhin steigende Preise.</p>' : '<p>The real estate market remains stable despite economic challenges. Particularly sought-after locations continue to see rising prices.</p>',
            'status'      => 'published',
            'is_featured' => 1,
            'category_id' => $catId,
            'author_id'   => $authorId,
            'published_at' => date('Y-m-d H:i:s'),
            'created_at'  => date('Y-m-d H:i:s'),
            'updated_at'  => date('Y-m-d H:i:s'),
        ],
    ];

    foreach ($posts as $post) {
        $exists = $db->fetch("SELECT id FROM iw_blog_posts WHERE slug = :slug LIMIT 1", ['slug' => $post['slug']]);
        if (!$exists) {
            $db->insert('iw_blog_posts', $post);
        }
    }

    // Events (open house / viewings)
    $events = [
        [
            'title'          => $isDE ? 'Tag der offenen Tuer: Neubauprojekt Am Park' : 'Open House: New Build Project Park View',
            'slug'           => $isDE ? 'tag-der-offenen-tuer-am-park' : 'open-house-park-view',
            'content'        => $isDE ? '<p>Besichtigen Sie unser neuestes Bauprojekt mit modernen Eigentumswohnungen.</p>' : '<p>Visit our latest building project with modern condominiums.</p>',
            'location'       => $isDE ? 'Parkstrasse 15, 50667 Koeln' : '15 Park Street, Cologne',
            'start_date'     => date('Y-m-d', strtotime('+14 days')),
            'start_time'     => '14:00:00',
            'end_time'       => '18:00:00',
            'publish_status' => 'published',
            'event_status'   => 'scheduled',
            'created_at'     => date('Y-m-d H:i:s'),
        ],
    ];

    foreach ($events as $event) {
        $exists = $db->fetch("SELECT id FROM iw_events WHERE slug = :slug LIMIT 1", ['slug' => $event['slug']]);
        if (!$exists) {
            $db->insert('iw_events', $event);
        }
    }

    // Gallery albums
    $albums = [
        ['title' => $isDE ? 'Aktuelle Objekte' : 'Current Properties', 'slug' => $isDE ? 'aktuelle-objekte' : 'current-properties', 'description' => $isDE ? 'Fotos unserer verfuegbaren Immobilien' : 'Photos of our available properties', 'is_visible' => 1, 'created_at' => date('Y-m-d H:i:s')],
        ['title' => $isDE ? 'Referenzen' : 'References', 'slug' => $isDE ? 'referenzen' : 'references', 'description' => $isDE ? 'Erfolgreich vermittelte Objekte' : 'Successfully brokered properties', 'is_visible' => 1, 'created_at' => date('Y-m-d H:i:s')],
    ];

    foreach ($albums as $album) {
        $exists = $db->fetch("SELECT id FROM iw_gallery_albums WHERE slug = :slug LIMIT 1", ['slug' => $album['slug']]);
        if (!$exists) {
            $db->insert('iw_gallery_albums', $album);
        }
    }

    // ── Homepage Sections: Override starter content with Estate-themed data ──

    // Hero: Premium real estate, teal background feel
    $heroContent = json_encode([
        'title'          => $isDE ? 'Finden Sie Ihr Traumhaus' : 'Find Your Dream Home',
        'highlight_word' => $isDE ? 'Traumhaus' : 'Dream Home',
        'eyebrow'        => $isDE ? 'Ihr Immobilienexperte seit 2005' : 'Your Real Estate Expert Since 2005',
        'subtitle'       => $isDE
            ? 'Entdecken Sie exklusive Immobilien in bester Lage. Persoenliche Beratung, transparente Prozesse und ein Netzwerk, das Ihnen Tueren oeffnet.'
            : 'Discover exclusive properties in prime locations. Personal consulting, transparent processes, and a network that opens doors for you.',
        'image'          => '',
        'portrait_image' => '',
        'portrait_alt'   => '',
        'text_color'     => 'white',
        'heading_size'   => 'lg',
        'heading_weight' => 'bold',
        'cta_text'       => $isDE ? 'Objekte entdecken' : 'Explore Properties',
        'cta_url'        => $isDE ? '/immobilien' : '/properties',
        'cta2_text'      => $isDE ? 'Kostenlose Bewertung' : 'Free Valuation',
        'cta2_url'       => $isDE ? '/bewertung' : '/valuation',
        'show_search'    => true,
        'search_placeholder' => $isDE ? 'Stadt, Stadtteil oder PLZ...' : 'City, district or zip...',
        'search_select_label' => $isDE ? 'Art' : 'Type',
        'search_options' => $isDE ? ['Kaufen', 'Mieten', 'Bewerten'] : ['Buy', 'Rent', 'Appraise'],
        'search_url'     => $isDE ? '/immobilien' : '/properties',
        'search_button_text' => $isDE ? 'Suchen' : 'Search',
        'hero_stats'     => [
            ['value' => '850+', 'label' => $isDE ? 'Vermittelte Objekte' : 'Properties Sold'],
            ['value' => '98%',  'label' => $isDE ? 'Zufriedene Kunden'   : 'Satisfied Clients'],
            ['value' => '20+',  'label' => $isDE ? 'Jahre Erfahrung'     : 'Years Experience'],
        ],
    ], JSON_UNESCAPED_UNICODE);

    $db->query(
        "UPDATE iw_page_sections SET content = :c, is_active = 1 WHERE section_type = 'hero' AND page_context = 'homepage'",
        ['c' => $heroContent]
    );

    // Intro: Trust and expertise
    $introContent = json_encode([
        'title'        => $isDE ? 'Vertrauen durch Erfahrung' : 'Trust Through Experience',
        'text'         => $isDE
            ? 'Seit ueber einem Jahrzehnt begleiten wir unsere Kunden bei den wichtigsten Entscheidungen rund um Immobilien. Ob Kauf, Verkauf oder Bewertung – wir stehen Ihnen mit Expertise und Marktkenntnis zur Seite.'
            : 'For over a decade, we have guided our clients through the most important decisions around real estate. Whether buying, selling, or valuation, we stand by you with expertise and market knowledge.',
        'color_scheme' => 'alt',
    ], JSON_UNESCAPED_UNICODE);

    $db->query(
        "UPDATE iw_page_sections SET content = :c, is_active = 1 WHERE section_type = 'intro' AND page_context = 'homepage'",
        ['c' => $introContent]
    );

    // Topic Cards: Core services
    $topicContent = json_encode([
        'title' => $isDE ? 'Unsere Leistungen' : 'Our Services',
        'items' => $isDE ? [
            ['icon' => 'home', 'title' => 'Immobilienvermittlung', 'text' => 'Vom Erstkontakt bis zum Notartermin – wir begleiten Sie durch den gesamten Verkaufsprozess.', 'url' => $isDE ? '/immobilien' : '/properties'],
            ['icon' => 'bar-chart', 'title' => 'Marktbewertung', 'text' => 'Fundierte Bewertungen basierend auf aktuellen Marktdaten und lokaler Expertise.', 'url' => $isDE ? '/bewertung' : '/valuation'],
            ['icon' => 'users', 'title' => 'Persoenliche Beratung', 'text' => 'Individuelle Betreuung fuer Kaeufer und Verkaeufer – diskret und professionell.', 'url' => '/contact'],
        ] : [
            ['icon' => 'home', 'title' => 'Property Brokerage', 'text' => 'From first contact to notary appointment, we guide you through the entire sales process.', 'url' => '/properties'],
            ['icon' => 'bar-chart', 'title' => 'Market Valuation', 'text' => 'Thorough valuations based on current market data and local expertise.', 'url' => '/valuation'],
            ['icon' => 'users', 'title' => 'Personal Consulting', 'text' => 'Individual support for buyers and sellers – discreet and professional.', 'url' => '/contact'],
        ],
        'color_scheme' => 'none',
        'card_style'   => 'bordered',
    ], JSON_UNESCAPED_UNICODE);

    $db->query(
        "UPDATE iw_page_sections SET content = :c, is_active = 1 WHERE section_type = 'topic_cards' AND page_context = 'homepage'",
        ['c' => $topicContent]
    );

    // Features: Why choose us
    $featuresContent = json_encode([
        'title' => $isDE ? 'Warum wir?' : 'Why Choose Us?',
        'items' => $isDE ? [
            ['title' => 'Regionale Marktkenntnis', 'text' => 'Wir kennen jede Nachbarschaft, jeden Trend und jede Entwicklung in unserer Region.'],
            ['title' => 'Diskrete Abwicklung', 'text' => 'Vertraulichkeit und professionelle Abwicklung stehen bei jedem Auftrag an erster Stelle.'],
            ['title' => 'Starkes Netzwerk', 'text' => 'Zugang zu exklusiven Off-Market-Objekten durch unser gewachsenes Kontaktnetzwerk.'],
        ] : [
            ['title' => 'Regional Market Expertise', 'text' => 'We know every neighborhood, every trend, and every development in our region.'],
            ['title' => 'Discreet Transactions', 'text' => 'Confidentiality and professional handling are our top priority for every mandate.'],
            ['title' => 'Strong Network', 'text' => 'Access to exclusive off-market properties through our established contact network.'],
        ],
        'color_scheme' => 'alt',
        'card_style'   => 'flat',
    ], JSON_UNESCAPED_UNICODE);

    $db->query(
        "UPDATE iw_page_sections SET content = :c, is_active = 1 WHERE section_type = 'features' AND page_context = 'homepage'",
        ['c' => $featuresContent]
    );

    // Blog Preview: Market insights
    $blogContent = json_encode([
        'title'    => $isDE ? 'Marktberichte & Insights' : 'Market Reports & Insights',
        'count'    => 3,
        'cta_text' => $isDE ? 'Alle Berichte' : 'All Reports',
        'cta_url'  => '/blog',
    ], JSON_UNESCAPED_UNICODE);

    $db->query(
        "UPDATE iw_page_sections SET content = :c, is_active = 1 WHERE section_type = 'blog_preview' AND page_context = 'homepage'",
        ['c' => $blogContent]
    );

    // Events Preview: Open houses
    $eventsContent = json_encode([
        'title'    => $isDE ? 'Besichtigungstermine' : 'Open Houses',
        'count'    => 3,
        'cta_text' => $isDE ? 'Alle Termine' : 'All Dates',
        'cta_url'  => '/events',
    ], JSON_UNESCAPED_UNICODE);

    $db->query(
        "UPDATE iw_page_sections SET content = :c, is_active = 1 WHERE section_type = 'events_preview' AND page_context = 'homepage'",
        ['c' => $eventsContent]
    );

    // CTA: Contact / Valuation
    $ctaContent = json_encode([
        'title'              => $isDE ? 'Lassen Sie Ihre Immobilie bewerten' : 'Get Your Property Valued',
        'text'               => $isDE
            ? 'Erfahren Sie den aktuellen Marktwert Ihrer Immobilie – kostenlos und unverbindlich. Unsere Experten beraten Sie gerne persoenlich.'
            : 'Find out the current market value of your property – free and without obligation. Our experts are happy to advise you personally.',
        'cta_text'           => $isDE ? 'Kostenlose Bewertung anfragen' : 'Request Free Valuation',
        'cta_url'            => '/contact',
        'color_scheme'       => '',
        'section_text_color' => '',
    ], JSON_UNESCAPED_UNICODE);

    $db->query(
        "UPDATE iw_page_sections SET content = :c, is_active = 1 WHERE section_type = 'cta' AND page_context = 'homepage'",
        ['c' => $ctaContent]
    );

    // ── Stats: Key figures (placed right after Hero) ──

    $statsContent = json_encode([
        'title'              => '',
        'subtitle'           => '',
        'color_scheme'       => '',
        'section_text_color' => '',
        'section_surface'    => '',
        'text_align'         => '',
        'columns'            => '3',
        'items'              => [
            ['value' => '850+', 'label' => $isDE ? 'Vermittelte Objekte' : 'Properties Sold', 'icon' => '', 'prefix' => '', 'suffix' => ''],
            ['value' => '98%',  'label' => $isDE ? 'Zufriedene Kunden'   : 'Satisfied Clients', 'icon' => '', 'prefix' => '', 'suffix' => ''],
            ['value' => '20+',  'label' => $isDE ? 'Jahre Erfahrung'     : 'Years Experience',  'icon' => '', 'prefix' => '', 'suffix' => ''],
        ],
    ], JSON_UNESCAPED_UNICODE);

    // Insert or update stats section
    $statsExists = $db->fetch("SELECT id FROM iw_page_sections WHERE section_type = 'stats' AND page_context = 'homepage' LIMIT 1");
    if ($statsExists) {
        $db->query(
            "UPDATE iw_page_sections SET content = :c, is_active = 1 WHERE section_type = 'stats' AND page_context = 'homepage'",
            ['c' => $statsContent]
        );
    } else {
        $db->insert('iw_page_sections', [
            'page_context'   => 'homepage',
            'section_type'   => 'stats',
            'instance_label' => $isDE ? 'Kennzahlen' : 'Key Figures',
            'content'        => $statsContent,
            'is_active'      => 1,
            'sort_order'     => 1,
            'created_at'     => date('Y-m-d H:i:s'),
            'updated_at'     => date('Y-m-d H:i:s'),
        ]);
    }

    // ── Testimonials: Customer voices (before CTA) ──

    $testimonialsContent = json_encode([
        'title'              => $isDE ? 'Das sagen unsere Kunden' : 'What Our Clients Say',
        'subtitle'           => '',
        'color_scheme'       => 'primary',
        'section_text_color' => '',
        'section_surface'    => '',
        'text_align'         => '',
        'columns'            => '2',
        'layout'             => 'staggered',
        'items'              => $isDE ? [
            [
                'quote'  => 'Die Zusammenarbeit mit Estate war herausragend. Innerhalb von drei Wochen hatten wir eine Traumwohnung gefunden. Die persoenliche Beratung und die Marktkenntnis haben den gesamten Prozess unglaublich einfach gemacht.',
                'author' => 'Michael und Sandra Hoffmann',
                'role'   => 'Kaeufer, Koeln-Lindenthal',
                'avatar' => '',
                'rating' => 5,
            ],
            [
                'quote'  => 'Professionell, diskret und extrem zuverlaessig. Unser Haus wurde zum bestmoeglichen Preis verkauft – schneller als erwartet.',
                'author' => 'Dr. Thomas Richter',
                'role'   => 'Verkaeufer, Bonn-Beuel',
                'avatar' => '',
                'rating' => 5,
            ],
        ] : [
            [
                'quote'  => 'Working with Estate was outstanding. Within three weeks, we found our dream apartment. The personal consultation and market knowledge made the entire process incredibly easy.',
                'author' => 'Michael and Sandra Hoffmann',
                'role'   => 'Buyers, Cologne',
                'avatar' => '',
                'rating' => 5,
            ],
            [
                'quote'  => 'Professional, discreet, and extremely reliable. Our house was sold at the best possible price – faster than expected.',
                'author' => 'Dr. Thomas Richter',
                'role'   => 'Seller, Bonn',
                'avatar' => '',
                'rating' => 5,
            ],
        ],
    ], JSON_UNESCAPED_UNICODE);

    $testimonialsExists = $db->fetch("SELECT id FROM iw_page_sections WHERE section_type = 'testimonials' AND page_context = 'homepage' LIMIT 1");
    if ($testimonialsExists) {
        $db->query(
            "UPDATE iw_page_sections SET content = :c, is_active = 1 WHERE section_type = 'testimonials' AND page_context = 'homepage'",
            ['c' => $testimonialsContent]
        );
    } else {
        $db->insert('iw_page_sections', [
            'page_context'   => 'homepage',
            'section_type'   => 'testimonials',
            'instance_label' => $isDE ? 'Kundenstimmen' : 'Testimonials',
            'content'        => $testimonialsContent,
            'is_active'      => 1,
            'sort_order'     => 8,
            'created_at'     => date('Y-m-d H:i:s'),
            'updated_at'     => date('Y-m-d H:i:s'),
        ]);
    }

    // ── Stats section: deactivate (stats live inside hero via hero_stats) ──
    $db->query(
        "UPDATE iw_page_sections SET is_active = 0 WHERE section_type = 'stats' AND page_context = 'homepage'"
    );

    // ── Property Cards: Estate-exclusive section ──

    $propertyContent = json_encode([
        'title'              => $isDE ? 'Ausgewaehlte Immobilien' : 'Featured Properties',
        'subtitle'           => $isDE
            ? 'Entdecken Sie unsere aktuellen Top-Objekte in erstklassigen Lagen.'
            : 'Discover our current top properties in prime locations.',
        'color_scheme'       => '',
        'section_text_color' => '',
        'cta_text'           => $isDE ? 'Alle Objekte' : 'All Properties',
        'cta_url'            => $isDE ? '/immobilien' : '/properties',
        'items'              => $isDE ? [
            ['title' => 'Stilvolle Altbauwohnung mit Rheinblick', 'price' => '485.000 EUR', 'image' => '', 'url' => '/immobilien', 'badge' => 'Neu', 'features' => '4 Zimmer, 120 m2, Balkon, Parkett'],
            ['title' => 'Familienfreundliches Einfamilienhaus',   'price' => '725.000 EUR', 'image' => '', 'url' => '/immobilien', 'badge' => 'Top-Lage', 'features' => '5 Zimmer, 180 m2, Garten, Garage'],
            ['title' => 'Modernes Penthouse mit Dachterrasse',    'price' => '1.250.000 EUR', 'image' => '', 'url' => '/immobilien', 'badge' => 'Exklusiv', 'features' => '3 Zimmer, 145 m2, Terrasse, Aufzug'],
        ] : [
            ['title' => 'Stylish Old-Town Apartment with River View', 'price' => '485,000 EUR', 'image' => '', 'url' => '/properties', 'badge' => 'New', 'features' => '4 rooms, 120 sqm, Balcony, Parquet'],
            ['title' => 'Family-Friendly Detached House',             'price' => '725,000 EUR', 'image' => '', 'url' => '/properties', 'badge' => 'Prime', 'features' => '5 rooms, 180 sqm, Garden, Garage'],
            ['title' => 'Modern Penthouse with Roof Terrace',         'price' => '1,250,000 EUR', 'image' => '', 'url' => '/properties', 'badge' => 'Exclusive', 'features' => '3 rooms, 145 sqm, Terrace, Elevator'],
        ],
    ], JSON_UNESCAPED_UNICODE);

    $propertyExists = $db->fetch("SELECT id FROM iw_page_sections WHERE section_type = 'property_cards' AND page_context = 'homepage' LIMIT 1");
    if ($propertyExists) {
        $db->query(
            "UPDATE iw_page_sections SET content = :c, is_active = 1 WHERE section_type = 'property_cards' AND page_context = 'homepage'",
            ['c' => $propertyContent]
        );
    } else {
        $db->insert('iw_page_sections', [
            'page_context'   => 'homepage',
            'section_type'   => 'property_cards',
            'instance_label' => $isDE ? 'Ausgewaehlte Immobilien' : 'Featured Properties',
            'content'        => $propertyContent,
            'is_active'      => 1,
            'sort_order'     => 2,
            'created_at'     => date('Y-m-d H:i:s'),
            'updated_at'     => date('Y-m-d H:i:s'),
        ]);
    }
}
