<?php

namespace App\Http\Controllers\Admin;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Models\HomepageSection;

class HomepageController extends Controller
{
    /**
     * Show all homepage sections with edit forms.
     * GET /admin/homepage
     */
    public function index(Request $request, array $params = []): void
    {
        $sections = HomepageSection::all('sort_order', 'ASC');

        // Decode each section's JSON content for the view
        foreach ($sections as &$section) {
            $section['data'] = json_decode($section['content'] ?? '{}', true) ?: [];
        }
        unset($section);

        $this->renderAdmin('homepage/index', [
            'pageTitle' => 'Homepage Sections',
            'sections'  => $sections,
            'auth'      => $this->auth(),
            'csrf'      => $this->csrf(),
        ]);
    }

    /**
     * Save/update a single homepage section's content.
     * POST /admin/homepage/section/{id}/save
     */
    public function updateSection(Request $request, array $params = []): void
    {
        $this->validateCsrf();

        $id      = (int) ($params['id'] ?? 0);
        $section = HomepageSection::find($id);

        if (!$section) {
            set_flash('error', 'Section not found.');
            Response::redirect('/admin/homepage');
            return;
        }

        $key  = $section['section_key'];
        $data = $this->buildSectionData($key, $request);

        HomepageSection::updateById($id, [
            'title'      => trim($request->input('section_title', $section['title'])),
            'content'    => json_encode($data, JSON_UNESCAPED_UNICODE),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);

        set_flash('success', 'Section "' . $section['title'] . '" saved.');
        Response::redirect('/admin/homepage#section-' . $id);
    }

    /**
     * Toggle the is_active flag of a section.
     * POST /admin/homepage/section/{id}/toggle
     */
    public function toggleSection(Request $request, array $params = []): void
    {
        $this->validateCsrf();

        $id      = (int) ($params['id'] ?? 0);
        $section = HomepageSection::find($id);

        if (!$section) {
            set_flash('error', 'Section not found.');
            Response::redirect('/admin/homepage');
            return;
        }

        $newState = $section['is_active'] ? 0 : 1;
        HomepageSection::updateById($id, [
            'is_active'  => $newState,
            'updated_at' => date('Y-m-d H:i:s'),
        ]);

        $label = $newState ? 'activated' : 'deactivated';
        set_flash('success', 'Section "' . $section['title'] . '" ' . $label . '.');
        Response::redirect('/admin/homepage#section-' . $id);
    }

    /**
     * Move a section up or down in the sort order.
     * POST /admin/homepage/section/{id}/move
     *
     * Expects POST parameter 'direction' = 'up' or 'down'.
     * Swaps sort_order with the adjacent section in that direction.
     */
    public function moveSection(Request $request, array $params = []): void
    {
        $this->validateCsrf();

        $id        = (int) ($params['id'] ?? 0);
        $direction = trim($request->input('direction', ''));

        if (!in_array($direction, ['up', 'down'], true)) {
            set_flash('error', 'Invalid direction.');
            Response::redirect('/admin/homepage');
            return;
        }

        $section = HomepageSection::find($id);
        if (!$section) {
            set_flash('error', 'Section not found.');
            Response::redirect('/admin/homepage');
            return;
        }

        // Load all sections in current order
        $all = HomepageSection::all('sort_order', 'ASC');

        // Find the index of the current section in the ordered list
        $currentIdx = null;
        foreach ($all as $idx => $s) {
            if ((int) $s['id'] === $id) {
                $currentIdx = $idx;
                break;
            }
        }

        if ($currentIdx === null) {
            Response::redirect('/admin/homepage');
            return;
        }

        // Determine swap target
        $swapIdx = ($direction === 'up') ? $currentIdx - 1 : $currentIdx + 1;

        if ($swapIdx < 0 || $swapIdx >= count($all)) {
            // Already at top/bottom – nothing to do
            Response::redirect('/admin/homepage#section-' . $id);
            return;
        }

        // Swap sort_order values
        $currentSortOrder = (int) $all[$currentIdx]['sort_order'];
        $swapSortOrder    = (int) $all[$swapIdx]['sort_order'];

        // If they happen to have the same sort_order, force distinct values
        if ($currentSortOrder === $swapSortOrder) {
            $swapSortOrder = ($direction === 'up') ? $currentSortOrder - 1 : $currentSortOrder + 1;
        }

        HomepageSection::updateById((int) $all[$currentIdx]['id'], ['sort_order' => $swapSortOrder]);
        HomepageSection::updateById((int) $all[$swapIdx]['id'], ['sort_order' => $currentSortOrder]);

        Response::redirect('/admin/homepage#section-' . $id);
    }

    /**
     * Legacy stub redirect – kept for route compatibility.
     * POST /admin/homepage/save
     */
    public function save(Request $request, array $params = []): void
    {
        Response::redirect('/admin/homepage');
    }

    // -------------------------------------------------------------------------
    // Private helpers
    // -------------------------------------------------------------------------

    /**
     * Build the JSON content array from POST data for a given section key.
     * Each section type has its own set of fields.
     *
     * After building the core fields, theme_section_extra_data() is called
     * to allow premium themes to contribute additional validated fields.
     * Extra fields are merged AFTER core fields, so themes cannot override
     * core field validation – only add new keys.
     */
    private function buildSectionData(string $key, Request $request): array
    {
        // ── Shared presentation token helpers (Phase 21) ───────────────────
        // empty string = theme default (no modifier class applied)
        $sanitizeToken       = static function (string $value, array $allowed): string {
            return in_array($value, $allowed, true) ? $value : '';
        };
        $allowedColorScheme    = ['', 'alt', 'primary', 'dark', 'none'];
        $allowedSectionAlign   = ['', 'left'];
        $allowedCardStyle      = ['', 'bordered', 'flat'];
        $allowedSectionTextColor = ['', 'black', 'white', 'theme'];
        $allowedColumns      = ['', '2', '3', '4'];
        $allowedOverlay      = ['', 'light', 'medium', 'heavy'];
        $allowedMaxWidth     = ['', 'sm', 'md', 'lg'];

        switch ($key) {
            case 'hero':
                // Presentation token whitelists – empty string = theme default (no class applied)
                $allowedTextColor       = ['', 'auto', 'white', 'black', 'red', 'green', 'blue', 'light', 'dark']; // light/dark = legacy 1.0.9
                $allowedHeadingSize     = ['', 'sm', 'md', 'lg', 'xl'];
                $allowedHeadingWeight   = ['', 'normal', 'medium', 'bold', 'black'];
                $allowedBodySize        = ['', 'sm', 'md', 'lg'];
                $allowedLayoutMode      = ['', 'full', 'boxed', 'split']; // full/boxed added 1.0.10
                $allowedTextAlign       = ['', 'left', 'right'];
                $allowedOverlayStrength = ['', 'light', 'medium', 'heavy'];
                $allowedHeroHeight      = ['', 'tall'];
                $allowedPortraitStyle   = ['', 'elevated', 'flat'];
                $allowedPortraitShape   = ['', 'circle', 'rounded', 'square'];
                $allowedCtaLayout       = ['', 'stacked'];

                $data = [
                    // Content fields
                    'title'          => trim($request->input('title', '')),
                    'eyebrow'        => trim($request->input('eyebrow', '')),
                    'subtitle'       => trim($request->input('subtitle', '')),
                    'image'          => trim($request->input('image', '')),
                    'portrait_image' => trim($request->input('portrait_image', '')),
                    'portrait_alt'   => trim($request->input('portrait_alt', '')),
                    'cta_text'       => trim($request->input('cta_text', '')),
                    'cta_url'        => trim($request->input('cta_url', '')),
                    'cta2_text'      => trim($request->input('cta2_text', '')),
                    'cta2_url'       => trim($request->input('cta2_url', '')),
                    // Presentation tokens (Phase 12a) – validated against whitelist
                    'text_color'       => $sanitizeToken(trim($request->input('text_color', '')),       $allowedTextColor),
                    'heading_size'     => $sanitizeToken(trim($request->input('heading_size', '')),     $allowedHeadingSize),
                    'heading_weight'   => $sanitizeToken(trim($request->input('heading_weight', '')),   $allowedHeadingWeight),
                    'body_size'        => $sanitizeToken(trim($request->input('body_size', '')),        $allowedBodySize),
                    'layout_mode'      => $sanitizeToken(trim($request->input('layout_mode', '')),      $allowedLayoutMode),
                    'text_align'       => $sanitizeToken(trim($request->input('text_align', '')),       $allowedTextAlign),
                    'overlay_strength' => $sanitizeToken(trim($request->input('overlay_strength', '')), $allowedOverlayStrength),
                    'hero_height'      => $sanitizeToken(trim($request->input('hero_height', '')),      $allowedHeroHeight),
                    'portrait_style'   => $sanitizeToken(trim($request->input('portrait_style', '')),   $allowedPortraitStyle),
                    'portrait_shape'   => $sanitizeToken(trim($request->input('portrait_shape', '')),   $allowedPortraitShape),
                    'cta_layout'       => $sanitizeToken(trim($request->input('cta_layout', '')),       $allowedCtaLayout),
                ];
                break;

            case 'intro':
                $data = [
                    'title'        => trim($request->input('title', '')),
                    'subtitle'     => trim($request->input('subtitle', '')),
                    'text'         => trim($request->input('text', '')),
                    'cta_text'     => trim($request->input('cta_text', '')),
                    'cta_url'      => trim($request->input('cta_url', '')),
                    // Presentation tokens
                    'color_scheme'       => $sanitizeToken(trim($request->input('color_scheme', '')), $allowedColorScheme),
                    'text_align'         => $sanitizeToken(trim($request->input('text_align', '')),   $allowedSectionAlign),
                    'max_width'          => $sanitizeToken(trim($request->input('max_width', '')),     $allowedMaxWidth),
                    'section_text_color' => $sanitizeToken(trim($request->input('section_text_color', '')), $allowedSectionTextColor),
                ];
                break;

            case 'features':
                $itemIcons  = $request->input('item_icon', []);
                $itemTitles = $request->input('item_title', []);
                $itemTexts  = $request->input('item_text', []);
                $itemUrls   = $request->input('item_url', []);
                $items = [];
                if (is_array($itemTitles)) {
                    foreach ($itemTitles as $i => $itemTitle) {
                        $t = trim($itemTitle);
                        if ($t !== '') {
                            $items[] = [
                                'icon'  => trim($itemIcons[$i] ?? ''),
                                'title' => $t,
                                'text'  => trim($itemTexts[$i] ?? ''),
                                'url'   => trim($itemUrls[$i] ?? ''),
                            ];
                        }
                    }
                }
                $data = [
                    'title'        => trim($request->input('title', '')),
                    'subtitle'     => trim($request->input('subtitle', '')),
                    'items'        => $items,
                    // Presentation tokens
                    'color_scheme'       => $sanitizeToken(trim($request->input('color_scheme', '')), $allowedColorScheme),
                    'text_align'         => $sanitizeToken(trim($request->input('text_align', '')),   $allowedSectionAlign),
                    'card_style'         => $sanitizeToken(trim($request->input('card_style', '')),   $allowedCardStyle),
                    'columns'            => $sanitizeToken(trim($request->input('columns', '')),       $allowedColumns),
                    'section_text_color' => $sanitizeToken(trim($request->input('section_text_color', '')), $allowedSectionTextColor),
                ];
                break;

            case 'gallery_preview':
                $data = [
                    'title'            => trim($request->input('title', '')),
                    'subtitle'         => trim($request->input('subtitle', '')),
                    'count'            => max(1, min(24, (int) $request->input('count', 6))),
                    'cta_text'         => trim($request->input('cta_text', '')),
                    'cta_url'          => trim($request->input('cta_url', '')),
                    'show_image_count'   => $request->input('show_image_count') ? 1 : 0,
                    // Presentation tokens
                    'color_scheme'       => $sanitizeToken(trim($request->input('color_scheme', '')), $allowedColorScheme),
                    'text_align'         => $sanitizeToken(trim($request->input('text_align', '')),   $allowedSectionAlign),
                    'section_text_color' => $sanitizeToken(trim($request->input('section_text_color', '')), $allowedSectionTextColor),
                ];
                break;

            case 'blog_preview':
                $data = [
                    'title'         => trim($request->input('title', '')),
                    'subtitle'      => trim($request->input('subtitle', '')),
                    'count'         => max(1, min(12, (int) $request->input('count', 3))),
                    'cta_text'      => trim($request->input('cta_text', '')),
                    'cta_url'       => trim($request->input('cta_url', '')),
                    'show_date'     => $request->input('show_date') ? 1 : 0,
                    'show_category'      => $request->input('show_category') ? 1 : 0,
                    // Presentation tokens
                    'color_scheme'       => $sanitizeToken(trim($request->input('color_scheme', '')), $allowedColorScheme),
                    'text_align'         => $sanitizeToken(trim($request->input('text_align', '')),   $allowedSectionAlign),
                    'section_text_color' => $sanitizeToken(trim($request->input('section_text_color', '')), $allowedSectionTextColor),
                ];
                break;

            case 'events_preview':
                $data = [
                    'title'        => trim($request->input('title', '')),
                    'subtitle'     => trim($request->input('subtitle', '')),
                    'count'        => max(1, min(12, (int) $request->input('count', 3))),
                    'cta_text'     => trim($request->input('cta_text', '')),
                    'cta_url'      => trim($request->input('cta_url', '')),
                    'show_image'         => $request->input('show_image') ? 1 : 0,
                    // Presentation tokens
                    'color_scheme'       => $sanitizeToken(trim($request->input('color_scheme', '')), $allowedColorScheme),
                    'text_align'         => $sanitizeToken(trim($request->input('text_align', '')),   $allowedSectionAlign),
                    'section_text_color' => $sanitizeToken(trim($request->input('section_text_color', '')), $allowedSectionTextColor),
                ];
                break;

            case 'cta':
                $data = [
                    'title'           => trim($request->input('title', '')),
                    'eyebrow'         => trim($request->input('eyebrow', '')),
                    'text'            => trim($request->input('text', '')),
                    'cta_text'        => trim($request->input('cta_text', '')),
                    'cta_url'         => trim($request->input('cta_url', '')),
                    'cta2_text'       => trim($request->input('cta2_text', '')),
                    'cta2_url'        => trim($request->input('cta2_url', '')),
                    'image'           => trim($request->input('image', '')),
                    // Presentation tokens
                    'color_scheme'    => $sanitizeToken(trim($request->input('color_scheme', '')),    $allowedColorScheme),
                    'text_align'      => $sanitizeToken(trim($request->input('text_align', '')),      $allowedSectionAlign),
                    'overlay_strength'   => $sanitizeToken(trim($request->input('overlay_strength', '')), $allowedOverlay),
                    'section_text_color' => $sanitizeToken(trim($request->input('section_text_color', '')), $allowedSectionTextColor),
                ];
                break;

            case 'topic_cards':
                $tcTitles = $request->input('tc_title', []);
                $tcIcons  = $request->input('tc_icon', []);
                $tcTexts  = $request->input('tc_text', []);
                $tcUrls   = $request->input('tc_url', []);
                $tcItems  = [];
                if (is_array($tcTitles)) {
                    foreach ($tcTitles as $i => $tcTitle) {
                        $t = trim($tcTitle);
                        if ($t !== '') {
                            $tcItems[] = [
                                'icon'  => trim($tcIcons[$i] ?? ''),
                                'title' => $t,
                                'text'  => trim($tcTexts[$i] ?? ''),
                                'url'   => trim($tcUrls[$i] ?? ''),
                            ];
                        }
                    }
                }
                $data = [
                    'title'        => trim($request->input('title', '')),
                    'subtitle'     => trim($request->input('subtitle', '')),
                    'items'        => $tcItems,
                    // Presentation tokens
                    'color_scheme'       => $sanitizeToken(trim($request->input('color_scheme', '')), $allowedColorScheme),
                    'text_align'         => $sanitizeToken(trim($request->input('text_align', '')),   $allowedSectionAlign),
                    'card_style'         => $sanitizeToken(trim($request->input('card_style', '')),   $allowedCardStyle),
                    'columns'            => $sanitizeToken(trim($request->input('columns', '')),       $allowedColumns),
                    'section_text_color' => $sanitizeToken(trim($request->input('section_text_color', '')), $allowedSectionTextColor),
                ];
                break;

            case 'highlight_grid':
                $hgTitles  = $request->input('hg_title', []);
                $hgIcons   = $request->input('hg_icon', []);
                $hgTexts   = $request->input('hg_text', []);
                $hgSources = $request->input('hg_source', []);
                $hgUrls    = $request->input('hg_url', []);
                $hgItems   = [];
                if (is_array($hgTitles)) {
                    foreach ($hgTitles as $i => $hgTitle) {
                        $t = trim($hgTitle);
                        if ($t !== '') {
                            $hgItems[] = [
                                'icon'   => trim($hgIcons[$i] ?? ''),
                                'title'  => $t,
                                'text'   => trim($hgTexts[$i] ?? ''),
                                'source' => trim($hgSources[$i] ?? ''),
                                'url'    => trim($hgUrls[$i] ?? ''),
                            ];
                        }
                    }
                }
                $data = [
                    'title'        => trim($request->input('title', '')),
                    'subtitle'     => trim($request->input('subtitle', '')),
                    'items'        => $hgItems,
                    // Presentation tokens
                    'color_scheme'       => $sanitizeToken(trim($request->input('color_scheme', '')), $allowedColorScheme),
                    'text_align'         => $sanitizeToken(trim($request->input('text_align', '')),   $allowedSectionAlign),
                    'card_style'         => $sanitizeToken(trim($request->input('card_style', '')),   $allowedCardStyle),
                    'columns'            => $sanitizeToken(trim($request->input('columns', '')),       $allowedColumns),
                    'section_text_color' => $sanitizeToken(trim($request->input('section_text_color', '')), $allowedSectionTextColor),
                ];
                break;

            default:
                // Let plugins handle their own section types via hook
                $pluginData = apply_hook('homepage.build_section_data', null, $key, $request);
                if (is_array($pluginData)) {
                    $data = $pluginData;
                } else {
                    // Fallback: preserve raw JSON input
                    $raw = trim($request->input('content_raw', ''));
                    $data = $raw !== '' ? (json_decode($raw, true) ?: []) : [];
                }
                break;
        }

        // ── Theme-specific extra fields (premium themes) ───────────────────
        // Merge additional validated fields from the active theme, if provided.
        // Extra fields can only ADD new keys – they cannot override core fields.
        $extra = theme_section_extra_data($key, $request);
        if ($extra) {
            // Only add keys that don't already exist in core data
            foreach ($extra as $extraKey => $extraValue) {
                if (!array_key_exists($extraKey, $data)) {
                    $data[$extraKey] = $extraValue;
                }
            }
        }

        return $data;
    }
}
