<?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\PageSection;
use App\Models\BlogPost;
use App\Models\GalleryAlbum;
use App\Models\Event;
use App\Models\ContactSubmission;
use App\Services\Mailer;

class PageController extends Controller
{
    /**
     * Render the homepage.
     */
    public function home(Request $request, array $params = []): void
    {
        // Page Builder (3.2.0): read from iw_page_sections
        $sections = PageSection::active('homepage');

        // Determine blog_preview count from active section config (falls back to 3)
        $blogPreviewCount = 3;
        foreach ($sections as $s) {
            if ($s['section_type'] === '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_type'] === '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_type'] === '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;
            }
        }

        // Let plugins provide additional data for their section types
        $pluginSectionData = [];
        if (function_exists('apply_hook')) {
            $pluginSectionData = apply_hook('homepage.section_data', [], $sections);
        }

        $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,
            'plugin_section_data'    => $pluginSectionData,
            '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::isVisible($page)) {
            http_response_code(404);
            $this->renderFrontend('404', ['current_uri' => $request->uri()]);
            return;
        }

        // HTTP cache headers (ETag, Last-Modified, 304 support)
        $this->sendContentCacheHeaders($page['updated_at'] ?? '', $page['slug'] ?? '');

        $template = $page['template'] ?: 'page';

        // Load page builder sections if enabled
        $sections = [];
        if (!empty($page['pagebuilder_enabled'])) {
            $sections = PageSection::active('page:' . $page['id']);
        }

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

    /**
     * Contact page.
     */
    public function contact(Request $request, array $params = []): void
    {
        // Disabled check
        if (!setting('contact_form_enabled', '1')) {
            http_response_code(404);
            $this->renderFrontend('404', ['current_uri' => '/contact']);
            return;
        }

        $page = Page::findByType('contact');
        if (!$page) {
            $page = Page::findBySlug('contact');
        }
        $pageTitle = ($page['title'] ?? '') ?: __('theme.contact_title');

        $systemPage = $page ?: ['title' => __('theme.contact_title'), 'content' => '', 'show_title' => 1];
        $this->renderFrontend('contact', [
            'system_page'     => $systemPage,
            'page'            => $systemPage,
            'page_title'      => $pageTitle,
            'seo_title'       => ($page['seo_title'] ?? '') ?: $pageTitle . ' – ' . setting('site_name'),
            'seo_description' => $page['seo_description'] ?? '',
            'canonical_url'   => base_url('/contact'),
            'breadcrumbs'     => [
                ['label' => 'Home',      'url' => '/'],
                ['label' => $pageTitle,  'url' => null],
            ],
            'current_uri'     => '/contact',
            'contact_fields'  => contact_form_fields(),
        ]);
    }

    /**
     * Contact form submission (dynamic – driven by contact_form_fields config).
     */
    public function contactSubmit(Request $request, array $params = []): void
    {
        // ── CSRF ───────────────────────────────────────────────────────────
        $this->validateCsrf();

        // ── Disabled check ─────────────────────────────────────────────────
        if (!setting('contact_form_enabled', '1')) {
            Response::redirect('/contact');
            return;
        }

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

        // ── Load field config ──────────────────────────────────────────────
        $fields = contact_form_fields();

        // ── Collect, validate & build form_data ───────────────────────────
        $errors   = [];
        $oldData  = [];
        $formData = []; // stored in DB: [['id','label','value','type'], ...]

        foreach ($fields as $field) {
            $id       = $field['id']    ?? '';
            $type     = $field['type']  ?? 'text';
            $label    = $field['label'] ?? $id;
            $required = !empty($field['required']);
            $inputName = 'cf_' . $id;

            if ($type === 'hidden') {
                $value = $field['value'] ?? '';
            } elseif ($type === 'checkbox') {
                $value = $request->input($inputName, '') !== '' ? '1' : '';
            } else {
                $value = trim($request->input($inputName, ''));
            }

            // Validation
            if ($required && $value === '') {
                $errors[$id] = __('messages.contact_field_required', ['label' => $label]);
            } elseif ($type === 'email' && $value !== '' && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
                $errors[$id] = __('messages.contact_field_email_invalid');
            }

            // Length caps
            $maxLen = ($type === 'textarea') ? 5000 : 200;
            if (mb_strlen($value) > $maxLen) {
                if (!isset($errors[$id])) {
                    $errors[$id] = __('messages.contact_field_too_long', ['label' => $label, 'max' => number_format($maxLen)]);
                }
                $value = mb_substr($value, 0, $maxLen);
            }

            $oldData[$id]  = $value;
            $formData[]    = ['id' => $id, 'label' => $label, 'value' => $value, 'type' => $type];
        }

        if (!empty($errors)) {
            set_flash('contact_errors', $errors);
            set_flash('contact_old', $oldData);
            set_flash('contact_error', __('messages.contact_fix_errors'));
            Response::redirect('/contact');
            return;
        }

        // ── Save to DB ─────────────────────────────────────────────────────
        if (setting('contact_form_save_to_db', '1')) {
            $ip = $_SERVER['REMOTE_ADDR'] ?? '';
            $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
            ContactSubmission::create($formData, $ip, $ua);
        }

        // ── Extract key values for mail ────────────────────────────────────
        $extractedEmail   = '';
        $extractedName    = '';
        $extractedSubject = '';
        $extractedMessage = '';

        foreach ($formData as $entry) {
            if ($entry['type'] === 'email' && $extractedEmail === '') {
                $extractedEmail = $entry['value'];
            }
            if (in_array($entry['type'], ['text'], true) && $extractedName === '') {
                $extractedName = $entry['value'];
            }
            if ($entry['type'] === 'textarea' && $extractedMessage === '') {
                $extractedMessage = $entry['value'];
            }
            // Subject: text field whose label contains 'betreff' or 'subject'
            if ($entry['type'] === 'text'
                && $extractedSubject === ''
                && preg_match('/betreff|subject/i', $entry['label'])
            ) {
                $extractedSubject = $entry['value'];
            }
        }
        if ($extractedSubject === '' && $extractedName !== '') {
            $extractedSubject = 'Kontaktanfrage von ' . $extractedName;
        }

        // Build dynamic fields table for mail
        $formFieldsHtml = '<table style="width:100%;border-collapse:collapse;margin:0 0 24px;">';
        foreach ($formData as $entry) {
            if ($entry['type'] === 'hidden') continue;
            $val = ($entry['type'] === 'textarea')
                ? '<span style="white-space:pre-wrap;">' . htmlspecialchars($entry['value'], ENT_QUOTES, 'UTF-8') . '</span>'
                : htmlspecialchars($entry['value'], ENT_QUOTES, 'UTF-8');
            $formFieldsHtml .= '<tr>'
                . '<td style="padding:10px 12px;border:1px solid #e2e8f0;font-size:13px;font-weight:600;color:#475569;background:#f8fafc;width:140px;">'
                . htmlspecialchars($entry['label'], ENT_QUOTES, 'UTF-8') . '</td>'
                . '<td style="padding:10px 12px;border:1px solid #e2e8f0;font-size:14px;color:#334155;">' . $val . '</td>'
                . '</tr>';
        }
        $formFieldsHtml .= '</table>';

        // ── Send mail ──────────────────────────────────────────────────────
        $recipient = setting('contact_email', '');
        if (empty($recipient)) {
            error_log('ITSWEBER Contact: contact_email setting is empty – message not sent.');
            set_flash('contact_success', __('messages.contact_success'));
            Response::redirect('/contact');
            return;
        }

        $siteName   = setting('site_name', 'ITSWEBER CMS');
        $mailConfig = mail_config();
        if ($extractedEmail !== '') {
            $mailConfig['reply_to'] = $extractedEmail;
        }

        $mailer   = new Mailer($mailConfig);
        $rendered = \App\Models\MailTemplate::render('contact_form', [
            'site_name'        => $siteName,
            'contact_name'     => $extractedName,
            'contact_email'    => $extractedEmail,
            'subject'          => $extractedSubject,
            'message'          => nl2br(htmlspecialchars($extractedMessage, ENT_QUOTES, 'UTF-8')),
            'form_fields_html' => $formFieldsHtml,
        ]);

        if ($rendered) {
            $mailSubject = $rendered['subject'];
            $htmlBody    = $rendered['body'];
            $plainBody   = strip_tags(str_replace(['</p>', '<br>', '</tr>'], ["\n\n", "\n", "\n"], $htmlBody));
        } else {
            // Fallback when mail template not yet seeded
            $mailSubject = '[' . $siteName . '] ' . $extractedSubject;
            $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>'
                . $formFieldsHtml
                . '<p style="margin-top:2rem;font-size:.8125rem;color:#999;">Gesendet über ' . htmlspecialchars($siteName, ENT_QUOTES, 'UTF-8') . '</p>'
                . '</body></html>';
            $plainBody = $mailSubject . "\n\n";
            foreach ($formData as $entry) {
                if ($entry['type'] !== 'hidden') {
                    $plainBody .= $entry['label'] . ': ' . $entry['value'] . "\n";
                }
            }
        }

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

        if ($sent) {
            set_flash('contact_success', __('messages.contact_success'));
        } else {
            error_log('ITSWEBER Contact: mail send failed – recipient=' . $recipient);
            set_flash('contact_error', __('messages.contact_send_failed'));
        }

        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['main_menu_tree'] = Menu::getItemsTree('main');
        $data['footer_menu']    = Menu::getItems('footer');

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