<?php

namespace App\Http\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Models\Page;
use App\Models\Menu;
use App\Models\HomepageSection;
use App\Models\BlogPost;
use App\Models\GalleryAlbum;
use App\Models\Event;
use App\Services\Mailer;

class PageController extends Controller
{
    /**
     * Render the homepage.
     */
    public function home(Request $request, array $params = []): void
    {
        $sections = HomepageSection::active();

        // Determine blog_preview count from active section config (falls back to 3)
        $blogPreviewCount = 3;
        foreach ($sections as $s) {
            if ($s['section_key'] === 'blog_preview') {
                $d = json_decode($s['content'] ?? '{}', true) ?: [];
                $blogPreviewCount = max(1, min(12, (int) ($d['count'] ?? 3)));
                break;
            }
        }
        $latestPosts = BlogPost::published($blogPreviewCount);

        // Determine gallery_preview albums from active section config (falls back to 6)
        $galleryPreviewAlbums = [];
        foreach ($sections as $s) {
            if ($s['section_key'] === 'gallery_preview') {
                $d = json_decode($s['content'] ?? '{}', true) ?: [];
                $count = max(1, min(12, (int) ($d['count'] ?? 6)));
                $galleryPreviewAlbums = array_slice(GalleryAlbum::visibleWithImageCount(), 0, $count);
                break;
            }
        }

        // Determine events_preview count from active section config (falls back to 3)
        $upcomingEvents = [];
        foreach ($sections as $s) {
            if ($s['section_key'] === 'events_preview' && $s['is_active']) {
                $d     = json_decode($s['content'] ?? '{}', true) ?: [];
                $count = max(1, min(12, (int) ($d['count'] ?? 3)));
                $upcomingEvents = Event::publishedUpcoming($count);
                break;
            }
        }

        $this->renderFrontend('home', [
            'page_title'             => setting('site_name'),
            'seo_title'              => setting('seo_title', setting('site_name')),
            'seo_description'        => setting('seo_description'),
            'canonical_url'          => base_url('/'),
            'sections'               => $sections,
            'latest_posts'           => $latestPosts,
            'gallery_preview_albums' => $galleryPreviewAlbums,
            'upcoming_events'        => $upcomingEvents,
            'current_uri'            => '/',
        ]);
    }

    /**
     * Render a dynamic page by slug.
     */
    public function show(Request $request, array $params = []): void
    {
        $slug = $params['slug'] ?? '';
        $page = Page::findBySlug($slug);

        if (!$page || $page['status'] !== 'published') {
            http_response_code(404);
            $this->renderFrontend('404', ['current_uri' => $request->uri()]);
            return;
        }

        // Normalize legacy template name 'default' → 'page' (no template file named 'default' exists)
        $template = $page['template'] ?: 'page';
        if ($template === 'default') {
            $template = 'page';
        }

        $this->renderFrontend($template, [
            'page'            => $page,
            'page_title'      => $page['title'],
            'seo_title'       => $page['seo_title'] ?: $page['title'] . ' – ' . setting('site_name'),
            'seo_description' => $page['seo_description'] ?? '',
            'canonical_url'   => base_url('/' . $slug),
            'breadcrumbs'     => [
                ['label' => 'Home', 'url' => '/'],
                ['label' => $page['title'], 'url' => null],
            ],
            'current_uri'     => '/' . $slug,
        ]);
    }

    /**
     * Contact page.
     */
    public function contact(Request $request, array $params = []): void
    {
        $page = Page::findBySlug('contact');

        $this->renderFrontend('contact', [
            'page'          => $page ?: ['title' => 'Contact', 'content' => ''],
            'page_title'    => 'Contact',
            'seo_title'     => 'Contact – ' . setting('site_name'),
            'canonical_url' => base_url('/contact'),
            'breadcrumbs'   => [
                ['label' => 'Home',    'url' => '/'],
                ['label' => 'Contact', 'url' => null],
            ],
            'current_uri'   => '/contact',
        ]);
    }

    /**
     * Contact form submission.
     */
    public function contactSubmit(Request $request, array $params = []): void
    {
        // ── CSRF is validated by base Controller ───────────────────────────
        $this->validateCsrf();

        // ── Honeypot spam check ────────────────────────────────────────────
        if (trim($request->input('website', '')) !== '') {
            // Silent redirect for bots
            Response::redirect('/contact');
            return;
        }

        // ── Collect & sanitise input ───────────────────────────────────────
        $name    = trim($request->input('name', ''));
        $email   = trim($request->input('email', ''));
        $subject = trim($request->input('subject', ''));
        $message = trim($request->input('message', ''));

        // ── Validation ────────────────────────────────────────────────────
        $errors = [];

        if ($name === '') {
            $errors['name'] = 'Bitte geben Sie Ihren Namen an.';
        } elseif (mb_strlen($name) > 120) {
            $errors['name'] = 'Name darf maximal 120 Zeichen lang sein.';
        }

        if ($email === '') {
            $errors['email'] = 'Bitte geben Sie Ihre E-Mail-Adresse an.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors['email'] = 'Bitte geben Sie eine gültige E-Mail-Adresse an.';
        }

        if ($subject === '') {
            $errors['subject'] = 'Bitte geben Sie einen Betreff an.';
        } elseif (mb_strlen($subject) > 200) {
            $errors['subject'] = 'Betreff darf maximal 200 Zeichen lang sein.';
        }

        if ($message === '') {
            $errors['message'] = 'Bitte geben Sie Ihre Nachricht ein.';
        } elseif (mb_strlen($message) > 5000) {
            $errors['message'] = 'Nachricht darf maximal 5.000 Zeichen lang sein.';
        }

        if (!empty($errors)) {
            set_flash('contact_errors', $errors);
            set_flash('contact_old', [
                'name'    => $name,
                'email'   => $email,
                'subject' => $subject,
                'message' => $message,
            ]);
            set_flash('contact_error', 'Bitte korrigieren Sie die markierten Felder.');
            Response::redirect('/contact');
            return;
        }

        // ── Send mail ──────────────────────────────────────────────────────
        $recipient = setting('contact_email', '');
        if (empty($recipient)) {
            // Fallback: log only, do not expose missing config to user
            error_log('ITSWEBER Contact: contact_email setting is empty – message not sent.');
            set_flash('contact_success', 'Vielen Dank für Ihre Nachricht! Wir melden uns so bald wie möglich.');
            Response::redirect('/contact');
            return;
        }

        $siteName = setting('site_name', 'ITSWEBER CMS');

        $mailConfig = config('mail') ?? [];
        // Set reply-to to the sender so we can reply directly
        $mailConfig['reply_to'] = $email;

        $mailer = new Mailer($mailConfig);

        $mailSubject = '[' . $siteName . '] Kontaktanfrage: ' . $subject;

        $htmlBody = '<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body style="font-family:sans-serif;color:#2b2b2b;line-height:1.6;">'
            . '<h2 style="color:#15779b;">Neue Kontaktanfrage</h2>'
            . '<table style="border-collapse:collapse;width:100%;max-width:600px;">'
            . '<tr><td style="padding:.5rem 0;font-weight:600;width:100px;">Name:</td><td style="padding:.5rem 0;">' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '</td></tr>'
            . '<tr><td style="padding:.5rem 0;font-weight:600;">E-Mail:</td><td style="padding:.5rem 0;"><a href="mailto:' . htmlspecialchars($email, ENT_QUOTES, 'UTF-8') . '">' . htmlspecialchars($email, ENT_QUOTES, 'UTF-8') . '</a></td></tr>'
            . '<tr><td style="padding:.5rem 0;font-weight:600;">Betreff:</td><td style="padding:.5rem 0;">' . htmlspecialchars($subject, ENT_QUOTES, 'UTF-8') . '</td></tr>'
            . '</table>'
            . '<hr style="margin:1.5rem 0;border:none;border-top:1px solid #efefef;">'
            . '<h3 style="color:#666;font-size:.875rem;text-transform:uppercase;letter-spacing:.06em;">Nachricht</h3>'
            . '<div style="background:#f9f9f9;border-left:3px solid #15779b;padding:1rem 1.25rem;border-radius:0 6px 6px 0;">'
            . nl2br(htmlspecialchars($message, ENT_QUOTES, 'UTF-8'))
            . '</div>'
            . '<p style="margin-top:2rem;font-size:.8125rem;color:#999;">Diese Nachricht wurde über das Kontaktformular auf ' . htmlspecialchars($siteName, ENT_QUOTES, 'UTF-8') . ' gesendet.</p>'
            . '</body></html>';

        $plainBody = "Neue Kontaktanfrage\n\n"
            . "Name:    {$name}\n"
            . "E-Mail:  {$email}\n"
            . "Betreff: {$subject}\n\n"
            . "Nachricht:\n{$message}\n\n"
            . "-- Gesendet über {$siteName}";

        $sent = $mailer->sendHtml($recipient, $mailSubject, $htmlBody, $plainBody);

        if ($sent) {
            set_flash('contact_success', 'Vielen Dank für Ihre Nachricht! Wir melden uns so bald wie möglich.');
        } else {
            error_log('ITSWEBER Contact: mail send failed for ' . $email);
            set_flash('contact_error', 'Ihre Nachricht konnte leider nicht gesendet werden. Bitte versuchen Sie es erneut oder schreiben Sie uns direkt per E-Mail.');
        }

        Response::redirect('/contact');
    }

    /**
     * Render a frontend template with shared layout data.
     */
    private function renderFrontend(string $template, array $data = []): void
    {
        // Load menu data for all pages
        $data['main_menu'] = Menu::getItems('main');
        $data['footer_menu'] = Menu::getItems('footer');

        $view = $this->app->service('view');
        $html = $view->render($template, $data);
        Response::html($html);
    }
}
