<?php

/**
 * Theme-specific seed: Terminal (IT / Developer)
 *
 * Creates developer-oriented demo content with web development services,
 * project portfolio, tech stack overview, meetup events, and code-related
 * blog posts. Used during installation when the Terminal theme is selected.
 */
function seedTerminalTheme(\App\Core\Database $db, string $language = 'de'): void
{
    $isDE = $language === 'de';

    // Pages
    $pages = [
        ['title' => $isDE ? 'Leistungen' : 'Services', 'slug' => $isDE ? 'leistungen' : 'services', 'template' => 'page', 'content' => $isDE ? '<p>Professionelle Webentwicklung, Hosting und technische Beratung – alles aus einer Hand.</p>' : '<p>Professional web development, hosting, and technical consulting – all from one source.</p>', 'sort_order' => 3],
        ['title' => $isDE ? 'Projekte' : 'Projects', 'slug' => $isDE ? 'projekte' : 'projects', 'template' => 'page', 'content' => $isDE ? '<p>Ausgewaehlte Projekte aus den Bereichen Webentwicklung, E-Commerce und individuelle Softwareloesungen.</p>' : '<p>Selected projects from web development, e-commerce, and custom software solutions.</p>', 'sort_order' => 4],
        ['title' => $isDE ? 'Tech Stack' : 'Stack', 'slug' => $isDE ? 'tech-stack' : 'stack', 'template' => 'page', 'content' => $isDE ? '<p>Unsere bevorzugten Technologien: PHP, MySQL, modernes CSS, Vanilla JS – performant, sicher, zukunftssicher.</p>' : '<p>Our preferred technologies: PHP, MySQL, modern CSS, Vanilla JS – performant, secure, future-proof.</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
    $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 ? 'Moderne Webentwicklung 2026: Trends und Best Practices' : 'Modern Web Development 2026: Trends and Best Practices',
            'slug'        => $isDE ? 'webentwicklung-2026' : 'web-development-2026',
            'excerpt'     => $isDE ? 'Die wichtigsten Trends und Best Practices fuer moderne Webentwicklung im Jahr 2026.' : 'The most important trends and best practices for modern web development in 2026.',
            'content'     => $isDE ? '<p>Die Webentwicklung entwickelt sich rasant weiter. Server-Side Rendering erlebt ein Comeback, Performance-Budgets werden zum Standard, und die Rueckbesinnung auf natives HTML und CSS zeigt: weniger Abhaengigkeiten bedeuten mehr Kontrolle und bessere Web Vitals.</p><p>In diesem Beitrag beleuchten wir die wichtigsten Trends – von progressiven Enhancement-Strategien ueber Edge Computing bis hin zu modernen Build-Pipelines ohne Node.js-Overhead.</p>' : '<p>Web development continues to evolve rapidly. Server-side rendering is making a comeback, performance budgets are becoming standard, and the return to native HTML and CSS shows that fewer dependencies mean more control and better Web Vitals.</p><p>In this post, we explore the most important trends – from progressive enhancement strategies to edge computing and modern build pipelines without Node.js overhead.</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 (meetups / workshops)
    $events = [
        [
            'title'          => 'Developer Meetup: Clean Code Workshop',
            'slug'           => 'developer-meetup-clean-code-workshop',
            'content'        => $isDE ? '<p>Interaktiver Workshop zu Clean-Code-Prinzipien: SOLID, DRY, KISS und praktische Refactoring-Uebungen. Ideal fuer PHP- und Backend-Entwickler aller Erfahrungsstufen.</p>' : '<p>Interactive workshop on clean code principles: SOLID, DRY, KISS, and practical refactoring exercises. Ideal for PHP and backend developers of all experience levels.</p>',
            'location'       => $isDE ? 'Online / Virtuell' : 'Online / Virtual',
            'start_date'     => date('Y-m-d', strtotime('+14 days')),
            'start_time'     => '19:00:00',
            'end_time'       => '21:30: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 ? 'Projektgalerie' : 'Project Gallery', 'slug' => $isDE ? 'projektgalerie' : 'project-gallery', 'description' => $isDE ? 'Screenshots und Impressionen aus unseren Webprojekten' : 'Screenshots and impressions from our web projects', 'is_visible' => 1, 'created_at' => date('Y-m-d H:i:s')],
        ['title' => 'Team & Office', 'slug' => 'team-office', 'description' => $isDE ? 'Einblicke in unser Team und unsere Arbeitsumgebung' : 'Insights into our team and work environment', '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 Terminal-themed data ──

    // Hero: Terminal-style with typing effect and metadata badges
    $heroContent = json_encode([
        'title'          => $isDE ? 'Die Zukunft bauen, ein Commit nach dem anderen' : 'Building the future, one commit at a time',
        'highlight_word' => 'Commit',
        'eyebrow'        => $isDE ? 'Webentwicklung & IT-Loesungen' : 'Web Development & IT Solutions',
        'subtitle'       => $isDE
            ? 'Performante Webseiten, sichere Infrastruktur und sauberer Code – von der Idee bis zum Deployment.'
            : 'Performant websites, secure infrastructure, and clean code – from idea to deployment.',
        'image'          => '',
        'portrait_image' => '',
        'portrait_alt'   => '',
        'text_color'     => 'white',
        'heading_size'   => 'lg',
        'heading_weight' => 'bold',
        'cta_text'       => $isDE ? 'Projekt starten' : 'Start Project',
        'cta_url'        => '/contact',
        'cta2_text'      => 'Tech Stack',
        'cta2_url'       => $isDE ? '/tech-stack' : '/stack',
        'show_typing'    => true,
        'terminal_commands' => $isDE ? [
            'Webseiten, die Entwickler lieben',
            'Performant, sicher, skalierbar',
            'Von der Idee zum Deployment in Rekordzeit',
        ] : [
            'Websites developers love',
            'Performant, secure, scalable',
            'From idea to deployment in record time',
        ],
        'metadata_badges' => [
            ['label' => 'PHP',     'value' => '8.3+',    'color' => 'amber'],
            ['label' => 'MySQL',   'value' => '8.x',     'color' => 'blue'],
            ['label' => 'Uptime',  'value' => '99.98%',  'color' => 'green'],
            ['label' => 'License', 'value' => 'Premium', 'color' => 'purple'],
        ],
        'hero_stats'     => [
            ['value' => '847+', 'label' => 'Deployments'],
            ['value' => '120+', 'label' => $isDE ? 'Zufriedene Kunden' : 'Happy Clients'],
            ['value' => '99.98%', 'label' => 'Uptime'],
        ],
    ], 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 message about technical expertise
    $introContent = json_encode([
        'title'        => $isDE ? 'Technik, der Sie vertrauen koennen' : 'Technology You Can Trust',
        'text'         => $isDE
            ? 'Wir entwickeln Webloesungen mit Fokus auf Performance, Sicherheit und Wartbarkeit. Kein Framework-Overhead, keine unnoetige Komplexitaet – nur sauberer Code, der laeuft. Jedes Projekt wird mit derselben Sorgfalt behandelt wie unser eigenes.'
            : 'We build web solutions focused on performance, security, and maintainability. No framework overhead, no unnecessary complexity – just clean code that runs. Every project is treated with the same care as our own.',
        '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' => 'code', 'title' => 'Webentwicklung', 'text' => 'Massgeschneiderte Webseiten und Webanwendungen mit PHP, MySQL und modernem Frontend – ohne unnoetige Abhaengigkeiten.', 'url' => '/leistungen'],
            ['icon' => 'server', 'title' => 'Hosting & DevOps', 'text' => 'Zuverlaessiges Managed Hosting, automatische Deployments und Monitoring – Ihre Infrastruktur in sicheren Haenden.', 'url' => '/leistungen'],
            ['icon' => 'message-circle', 'title' => 'Beratung', 'text' => 'Technische Beratung zu Architektur, Performance-Optimierung und Modernisierung bestehender Systeme.', 'url' => '/contact'],
        ] : [
            ['icon' => 'code', 'title' => 'Web Development', 'text' => 'Custom websites and web applications with PHP, MySQL, and modern frontend – without unnecessary dependencies.', 'url' => '/services'],
            ['icon' => 'server', 'title' => 'Hosting & DevOps', 'text' => 'Reliable managed hosting, automated deployments, and monitoring – your infrastructure in safe hands.', 'url' => '/services'],
            ['icon' => 'message-circle', 'title' => 'Consulting', 'text' => 'Technical consulting on architecture, performance optimization, and modernization of existing systems.', '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: Styled as dependencies
    $featuresContent = json_encode([
        'title' => $isDE ? 'Was uns auszeichnet' : 'What Sets Us Apart',
        'items' => $isDE ? [
            ['title' => 'Responsive Design', 'text' => 'Jedes Projekt ist von Anfang an fuer alle Geraete optimiert – Mobile First, keine Kompromisse bei der Nutzererfahrung.'],
            ['title' => 'Security', 'text' => 'CSRF-Schutz, Prepared Statements, Content Security Policy und regelmaessige Audits – Sicherheit ist kein Feature, sondern Standard.'],
            ['title' => 'Performance', 'text' => 'Optimierte Ladezeiten durch schlanken Code, effizientes Caching und minimale Abhaengigkeiten – gruene Core Web Vitals garantiert.'],
        ] : [
            ['title' => 'Responsive Design', 'text' => 'Every project is optimized for all devices from the start – mobile first, no compromises on user experience.'],
            ['title' => 'Security', 'text' => 'CSRF protection, prepared statements, content security policy, and regular audits – security is not a feature, it is standard.'],
            ['title' => 'Performance', 'text' => 'Optimized load times through lean code, efficient caching, and minimal dependencies – green Core Web Vitals guaranteed.'],
        ],
        '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: Dev blog
    $blogContent = json_encode([
        'title'    => $isDE ? 'Aus dem Dev-Blog' : 'From the Dev Blog',
        'count'    => 3,
        'cta_text' => $isDE ? 'Alle Beitraege' : 'All Posts',
        '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: Meetups & Workshops
    $eventsContent = json_encode([
        'title'    => 'Meetups & Workshops',
        'count'    => 3,
        'cta_text' => $isDE ? 'Alle Termine' : 'All Events',
        '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: Developer-themed call to action
    $ctaContent = json_encode([
        'title'              => $isDE ? 'Bereit fuer den naechsten Commit?' : 'Ready for the next commit?',
        'text'               => $isDE
            ? 'Lassen Sie uns gemeinsam Ihr naechstes Webprojekt starten. Sauberer Code, durchdachte Architektur und ein Partner, der Ihre Sprache spricht.'
            : 'Let us start your next web project together. Clean code, thoughtful architecture, and a partner who speaks your language.',
        'cta_text'           => $isDE ? 'Projekt anfragen' : 'Request Project',
        '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: Git-log styled key figures ──

    $statsContent = json_encode([
        'title'              => '',
        'subtitle'           => '',
        'color_scheme'       => '',
        'section_text_color' => '',
        'section_surface'    => '',
        'text_align'         => '',
        'columns'            => '4',
        'items'              => [
            ['value' => '847+',    'label' => 'Deployments',                                           'icon' => '', 'prefix' => '', 'suffix' => ''],
            ['value' => '120+',    'label' => $isDE ? 'Zufriedene Kunden' : 'Happy Clients',           'icon' => '', 'prefix' => '', 'suffix' => ''],
            ['value' => '99.98%',  'label' => 'Uptime',                                                'icon' => '', 'prefix' => '', 'suffix' => ''],
            ['value' => '2340',    'label' => 'Commits',                                               'icon' => '', 'prefix' => '', 'suffix' => ''],
        ],
    ], JSON_UNESCAPED_UNICODE);

    $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: Developer testimonials ──

    $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 war hervorragend. Das Team hat unsere komplexe Webanwendung in Rekordzeit umgesetzt – performant, sicher und exakt nach Spezifikation. Der Code ist sauber dokumentiert und laesst sich problemlos warten.',
                'author' => 'Markus Bauer',
                'role'   => 'CTO, TechVenture GmbH',
                'avatar' => '',
                'rating' => 5,
            ],
            [
                'quote'  => 'Endlich ein Entwickler, der nicht nur Code schreibt, sondern mitdenkt. Die Performance-Optimierung unseres Online-Shops hat die Ladezeit halbiert und die Conversion-Rate deutlich gesteigert.',
                'author' => 'Julia Kessler',
                'role'   => 'Geschaeftsfuehrerin, Kessler Digital',
                'avatar' => '',
                'rating' => 5,
            ],
        ] : [
            [
                'quote'  => 'The collaboration was outstanding. The team delivered our complex web application in record time – performant, secure, and exactly to specification. The code is cleanly documented and easy to maintain.',
                'author' => 'Markus Bauer',
                'role'   => 'CTO, TechVenture GmbH',
                'avatar' => '',
                'rating' => 5,
            ],
            [
                'quote'  => 'Finally a developer who does not just write code but thinks along. The performance optimization of our online shop cut load times in half and significantly increased conversion rates.',
                'author' => 'Julia Kessler',
                'role'   => 'CEO, Kessler Digital',
                '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'),
        ]);
    }

    // ── Code Showcase: Terminal-exclusive section ──

    $codeShowcaseContent = json_encode([
        'title'              => $isDE ? 'Clean Code, Klare Architektur' : 'Clean Code, Clear Architecture',
        'subtitle'           => $isDE
            ? 'So sieht moderner, wartbarer Code aus – kein Framework-Overhead, nur das Wesentliche.'
            : 'This is what modern, maintainable code looks like – no framework overhead, just the essentials.',
        'color_scheme'       => '',
        'section_text_color' => '',
        'tabs'               => [
            [
                'filename' => 'app.php',
                'language' => 'php',
                'code'     => "<?php\n\nnamespace App\\Core;\n\nclass Router\n{\n    private array \$routes = [];\n\n    public function get(string \$path, array \$handler): self\n    {\n        \$this->routes['GET'][\$path] = \$handler;\n        return \$this;\n    }\n\n    public function dispatch(string \$method, string \$uri): mixed\n    {\n        \$route = \$this->match(\$method, \$uri);\n        if (!\$route) {\n            throw new NotFoundException('Route not found');\n        }\n        return call_user_func(\$route['handler'], \$route['params']);\n    }\n}",
            ],
            [
                'filename' => 'style.css',
                'language' => 'css',
                'code'     => "/* Terminal Theme – Design Tokens */\n:root {\n    --color-primary: #10b981;\n    --color-surface: #0f172a;\n    --color-text: #e2e8f0;\n    --font-mono: 'JetBrains Mono', monospace;\n    --radius: 0.5rem;\n    --transition: 200ms ease;\n}\n\n.terminal-card {\n    background: var(--color-surface);\n    border: 1px solid rgba(16, 185, 129, 0.2);\n    border-radius: var(--radius);\n    padding: 1.5rem;\n    transition: border-color var(--transition);\n}\n\n.terminal-card:hover {\n    border-color: var(--color-primary);\n}",
            ],
        ],
    ], JSON_UNESCAPED_UNICODE);

    $codeShowcaseExists = $db->fetch("SELECT id FROM iw_page_sections WHERE section_type = 'code_showcase' AND page_context = 'homepage' LIMIT 1");
    if ($codeShowcaseExists) {
        $db->query(
            "UPDATE iw_page_sections SET content = :c, is_active = 1 WHERE section_type = 'code_showcase' AND page_context = 'homepage'",
            ['c' => $codeShowcaseContent]
        );
    } else {
        $db->insert('iw_page_sections', [
            'page_context'   => 'homepage',
            'section_type'   => 'code_showcase',
            'instance_label' => $isDE ? 'Code-Beispiel' : 'Code Showcase',
            'content'        => $codeShowcaseContent,
            'is_active'      => 1,
            'sort_order'     => 5,
            'created_at'     => date('Y-m-d H:i:s'),
            'updated_at'     => date('Y-m-d H:i:s'),
        ]);
    }
}
