<?php

namespace Modules\LandingPage\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\LandingPage\Entities\LpPage;
use Modules\LandingPage\Entities\LpPageSection;

class PageSectionController extends Controller
{
    /**
     * Get the available layouts for sections.
     * Optionally filter by section type.
     *
     * @param string|null $sectionType
     * @return array
     */
    protected function getAvailableLayouts($sectionType = null): array
    {
        // Define your layouts here. Keys are stored in DB, values are for display.
        $layouts = [
            'default' => 'Default Layout',
            'image_left_text_right' => 'Image Left, Text Right',
            'text_left_image_right' => 'Text Left, Image Right',
            'two_column_text' => 'Two Column Text',
            'three_column_features' => 'Three Column Features',
            'full_width_image' => 'Full Width Image',
            'full_width_text_centered' => 'Full Width Text (Centered)',
            'hero_background_image' => 'Hero (Background Image)',
            'card_grid' => 'Card Grid (Features, Items, etc.)',
            'callout_box' => 'Callout Box / Inline Promo',
            // Add more layouts as you create their corresponding Blade files
            // e.g., 'hero_banner_video' => 'Hero Banner with Video Background'
        ];

        // Example: If you want to restrict layouts based on section type
        // if ($sectionType === 'hero') {
        //     return [
        //         'default' => 'Default Hero Layout',
        //         'hero_banner_video' => 'Hero with Video',
        //     ];
        // }

        return $layouts;
    }

    /**
     * Get available section types.
     *
     * @return array
     */
    protected function getSectionTypes(): array
    {
        // These should correspond to the fields your section content forms will generate
        // and what your layout partials expect.
        return [
            'general_content' => 'General Content (Text, Image, Button)',
            'hero' => 'Hero Section',
            'feature_list' => 'Feature List',
            'call_to_action' => 'Call to Action',
            'testimonial_slider' => 'Testimonial Slider',
            'gallery' => 'Image Gallery',
            // Add more types as needed
        ];
    }

    /**
     * Show the form for creating a new section for a page.
     *
     * @param  \Modules\LandingPage\Entities\LpPage  $page
     * @return \Illuminate\Contracts\View\View
     */
    public function create(LpPage $page)
    {
        $section = new LpPageSection();
        $sectionTypes = $this->getSectionTypes();
        $availableLayouts = $this->getAvailableLayouts(); // Get all layouts for new section

        return view('landingpage::admin.pages.sections.create', compact('page', 'section', 'sectionTypes', 'availableLayouts'));
    }

    /**
     * Store a newly created section in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Modules\LandingPage\Entities\LpPage  $page
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request, LpPage $page)
    {
        $sectionTypesKeys = array_keys($this->getSectionTypes());
        $availableLayoutsKeys = array_keys($this->getAvailableLayouts($request->input('type')));

        $validatedData = $request->validate([
            'title' => 'required|string|max:255',
            'type' => 'required|string|in:' . implode(',', $sectionTypesKeys),
            'layout' => 'required|string|in:' . implode(',', $availableLayoutsKeys),
            'content' => 'nullable|array', // Content will be specific to the section type/layout
            'sort_order' => 'nullable|integer',
        ]);

        // Ensure content is at least an empty array if not provided
        $validatedData['content'] = $validatedData['content'] ?? [];

        // If sort_order is not provided, calculate the next one
        if (!isset($validatedData['sort_order']) || $validatedData['sort_order'] === null || $validatedData['sort_order'] === '') {
            $validatedData['sort_order'] = ($page->sections()->max('sort_order') ?? 0) + 1;
        }

        $page->sections()->create($validatedData);

        return redirect()->route('admin.landingpage.pages.edit', $page->id) // Or wherever you manage page sections
                         ->with('success', 'Page section created successfully.');
    }

    /**
     * Show the form for editing the specified section.
     *
     * @param  \Modules\LandingPage\Entities\LpPage  $page
     * @param  \Modules\LandingPage\Entities\LpPageSection  $section
     * @return \Illuminate\Contracts\View\View
     */
    public function edit(LpPage $page, LpPageSection $section)
    {
        $sectionTypes = $this->getSectionTypes();
        $availableLayouts = $this->getAvailableLayouts($section->type); // Get layouts, potentially filtered by current section type

        return view('landingpage::admin.pages.sections.edit', compact('page', 'section', 'sectionTypes', 'availableLayouts'));
    }

    /**
     * Update the specified section in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Modules\LandingPage\Entities\LpPage  $page
     * @param  \Modules\LandingPage\Entities\LpPageSection  $section
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, LpPage $page, LpPageSection $section)
    {
        $sectionTypesKeys = array_keys($this->getSectionTypes());
        $availableLayoutsKeys = array_keys($this->getAvailableLayouts($request->input('type')));

        $validatedData = $request->validate([
            'title' => 'required|string|max:255',
            'type' => 'required|string|in:' . implode(',', $sectionTypesKeys),
            'layout' => 'required|string|in:' . implode(',', $availableLayoutsKeys),
            'content' => 'nullable|array',
            'sort_order' => 'nullable|integer',
        ]);
        
        $validatedData['content'] = $validatedData['content'] ?? [];

        $section->update($validatedData);

        return redirect()->route('admin.landingpage.pages.edit', $page->id)
                         ->with('success', 'Page section updated successfully.');
    }

    /**
     * Remove the specified section from storage.
     *
     * @param  \Modules\LandingPage\Entities\LpPage  $page
     * @param  \Modules\LandingPage\Entities\LpPageSection  $section
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(LpPage $page, LpPageSection $section)
    {
        $section->delete();
        return redirect()->route('admin.landingpage.pages.edit', $page->id)
                         ->with('success', 'Page section deleted successfully.');
    }
}
