<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\HomeSection;
use App\Models\Menu;
use App\Models\Product;
use Illuminate\Http\Request;

class HomeSectionController extends Controller
{
    /**
     * Home sections list
     */
    public function index()
    {
        $data['PageTitle'] = 'Home Sections';

        $data['sections'] = HomeSection::with('menu')
            ->orderBy('order')
            ->get();

        // Sidebar active flags (jodi lage future e)
        $data['parentHomeSectionShowClass'] = 'show';
        $data['homeSectionActiveClass']     = 'active';

        return view('backend.home-section.index')->with($data);
    }

    /**
     * Create form
     */
    public function create()
    {
        $data['PageTitle'] = 'Add Home Section';

        // শুধু main menus (parent_id = null) নিবো
        $data['menus'] = Menu::whereNull('parent_id')
            ->orderBy('order')
            ->get();

        $data['parentHomeSectionShowClass'] = 'show';
        $data['homeSectionActiveClass']     = 'active';

        return view('backend.home-section.create')->with($data);
    }

    /**
     * Store new home section
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'menu_id'      => 'required|exists:menus,id',
            'title'        => 'nullable|string|max:255',
            'subtitle'     => 'nullable|string|max:255',
            'max_products' => 'nullable|integer|min:1|max:100',
            'order'        => 'nullable|integer',
            'is_active'    => 'nullable|boolean',
        ]);

        HomeSection::create([
            'menu_id'      => $validated['menu_id'],
            'title'        => $validated['title'] ?? null,
            'subtitle'     => $validated['subtitle'] ?? null,
            'max_products' => $validated['max_products'] ?? 8,
            'order'        => $validated['order'] ?? 0,
            'is_active'    => $request->has('is_active') ? (bool) ($validated['is_active'] ?? 1) : true,
        ]);

        return redirect()
            ->route('admin.home-section.index')
            ->with('success', 'Home section created successfully.');
    }

    /**
     * Edit form
     */
    public function edit($id)
    {
        $section = HomeSection::findOrFail($id);

        $data['PageTitle'] = 'Edit Home Section';
        $data['section']   = $section;

        $data['menus'] = Menu::whereNull('parent_id')
            ->orderBy('order')
            ->get();

        $data['parentHomeSectionShowClass'] = 'show';
        $data['homeSectionActiveClass']     = 'active';

        return view('backend.home-section.edit')->with($data);
    }

    /**
     * Update
     */
    public function update(Request $request, $id)
    {
        $section = HomeSection::findOrFail($id);

        $validated = $request->validate([
            'menu_id'      => 'required|exists:menus,id',
            'title'        => 'nullable|string|max:255',
            'subtitle'     => 'nullable|string|max:255',
            'max_products' => 'nullable|integer|min:1|max:100',
            'order'        => 'nullable|integer',
            'is_active'    => 'nullable|boolean',
        ]);

        $section->update([
            'menu_id'      => $validated['menu_id'],
            'title'        => $validated['title'] ?? null,
            'subtitle'     => $validated['subtitle'] ?? null,
            'max_products' => $validated['max_products'] ?? $section->max_products,
            'order'        => $validated['order'] ?? $section->order,
            'is_active'    => $request->has('is_active') ? (bool) ($validated['is_active'] ?? 0) : false,
        ]);

        return redirect()
            ->route('admin.home-section.index')
            ->with('success', 'Home section updated successfully.');
    }

    /**
     * Delete
     */
    public function destroy($id)
    {
        $section = HomeSection::findOrFail($id);
        $section->delete();

        return redirect()
            ->route('admin.home-section.index')
            ->with('success', 'Home section deleted successfully.');
    }

    /**
     * নির্দিষ্ট সেকশনের জন্য প্রোডাক্ট ম্যানেজ করার পেজ
     */
    public function manageProducts($id)
    {
        $section = HomeSection::with(['menu', 'products'])->findOrFail($id);

        // সব প্রোডাক্ট দেখাবো (ইচ্ছে করলে পরে filter করা যাবে)
        $products = Product::with('category')
            ->orderBy('id', 'desc')
            ->get();

        return view('backend.home-section.manage-products', [
            'PageTitle' => 'Manage Section Products',
            'section'   => $section,
            'products'  => $products,
        ]);
    }

    /**
     * নির্দিষ্ট সেকশনের জন্য প্রোডাক্ট update (attach/detach)
     */
    public function updateProducts(Request $request, $id)
    {
        $section = HomeSection::findOrFail($id);

        $validated = $request->validate([
            'product_ids'   => 'nullable|array',
            'product_ids.*' => 'integer|exists:products,id',
        ]);

        $syncData = [];

        if (!empty($validated['product_ids'])) {
            foreach ($validated['product_ids'] as $index => $productId) {
                $syncData[$productId] = ['position' => $index];
            }
        }

        // pivot table sync
        $section->products()->sync($syncData);

        return redirect()
            ->route('admin.home-section.index')
            ->with('success', 'Section products updated successfully.');
    }
}
