<?php

namespace App\Http\Controllers;

use App\Http\Requests\MealPackageRequest;
use App\Models\Image;
use App\Models\MealPackage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;

class MealPackageController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {

        $perPage = request('per_page', 10);

        $mealPackages = MealPackage::with(['availabilityRules'])
            ->orderBy('sort_order')
            ->paginate($perPage)
            ->withQueryString();

        return Inertia::render('dashboard/meal-packages/index', [
            'meal_packages' => $mealPackages,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return Inertia::render('dashboard/meal-packages/meal-package');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(MealPackageRequest $request)
    {
        DB::beginTransaction();

        try {
            // Create meal package
            $mealPackage = MealPackage::create([
                'sort_order' => $request['sort_order'],
                'title' => $request['title'],
                'description' => $request['description'] ?? null,
                'price' => $request['is_variant'] ? 0 : $request['price'],
                'scope' => $request['scope'],
                'tag' => $request['tag'] ?? null,
                'is_icon' => $request['is_icon'] ?? true,
                'icon_value' => $request['icon_value'] ?? null,
                'is_allow_select_days' => $request['is_allow_select_days'] ?? false,
                'is_variant' => $request['is_variant'] ?? false,
                'is_published' => $request['is_published'] ?? true,
                'default_availability' => $request['default_availability'] ?? true,
            ]);

            // Attach images (polymorphic)
            if (!empty($request['images'])) {
                foreach ($request['images'] as $index => $img) {
                    $image = Image::find('id', $img['id'] ?? null);
                    if (!$image) continue;

                    // Attach via morphToMany pivot table
                    $mealPackage->images()->attach($image->id, [
                        'role' => $index === 0 ? 'thumbnail' : 'gallery',
                        'sort_order' => $index,
                    ]);
                }
            }

            // 2️⃣ If is_variant = FALSE → delete everything
            if ($request->is_variant && !empty($request->variants)) {
                foreach ($request->variants as $variant) {
                    $mealPackage->variants()->create([
                        'sort_order' => $variant['sort_order'],
                        'title' => $variant['title'],
                        'description' => $variant['description'] ?? null,
                        'price' => $variant['price'],
                        'is_published' => $variant['is_published'] ?? false,
                        'is_icon' => $variant['is_icon'] ?? true,
                        'icon_value' => $variant['icon_value'] ?? null,
                        'default_availability' => $variant['default_availability'] ?? true,
                    ]);
                }
            }

            DB::commit();

            return redirect()
                ->route('meal-packages.index')
                ->with('success', 'Meal package created successfully.');
        } catch (\Exception $e) {

            DB::rollBack();

            return back()->withErrors([
                'error' => 'Something went wrong while creating the meal package.'
            ]);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(MealPackage $mealPackage)
    {
        $mealPackage->load([
            'images' =>  fn($q) => $q->orderBy('sort_order'),
            'availabilityRules',
            'variants' =>  fn($q) => $q->orderBy('sort_order'),
            'variants.availabilityRules',
        ]);

        return Inertia::render('dashboard/meal-packages/meal-package', [
            'mealPackage' => $mealPackage,
            'mode' => 'view'
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(MealPackage $mealPackage)
    {
        $mealPackage->load([
            'images' =>  fn($q) => $q->orderBy('sort_order'),
            'availabilityRules',
            'variants' =>  fn($q) => $q->orderBy('sort_order'),
            'variants.availabilityRules',
        ]);

        return Inertia::render('dashboard/meal-packages/meal-package', [
            'mealPackage' => $mealPackage,
            'mode' => 'edit'
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(MealPackageRequest $request, MealPackage $mealPackage)
    {

        DB::beginTransaction();

        try {
            $validated = $request;

            if ($mealPackage['scope'] !== $validated['scope']) {
                $this->cleanupScopeRelations($mealPackage, $validated['scope']);
            }

            // 1️⃣ Update main fields
            $mealPackage->update([
                'sort_order' => $validated['sort_order'],
                'title' => $validated['title'],
                'description' => $validated['description'] ?? null,
                'price' => $request['is_variant'] ? 0 : $request['price'],
                'scope' => $validated['scope'],
                'tag' => $validated['tag'] ?? null,
                'is_icon' => $validated['is_icon'] ?? true,
                'icon_value' => $validated['icon_value'] ?? null,
                'is_allow_select_days' => $validated['is_allow_select_days'] ?? false,
                'is_variant' => $validated['is_variant'] ?? false,
                'is_published' => $validated['is_published'] ?? true,
                'default_availability' => $validated['default_availability'] ?? true,
            ]);



            // 2️⃣ Sync images (morphMany)
            if (isset($validated['images'])) {

                $syncData = [];

                foreach ($validated['images'] as $img) {
                    $syncData[$img['id']] = [
                        'role' => $img['role'],
                        'sort_order' => $img['sort_order'],
                    ];
                }

                // This will:
                // - Attach new ones
                // - Update existing pivot data
                // - Remove images not in array
                $mealPackage->images()->sync($syncData);
            } else {
                // If no images sent, detach all
                $mealPackage->images()->detach();
            }


            // 2️⃣ If is_variant = FALSE → delete everything
            if (!$request->is_variant) {

                $mealPackage->variants()->delete();
            }

            // 3️⃣ If is_variant = TRUE → sync properly
            else {

                $incoming = collect($request->variants ?? []);
                $processedIds = [];

                foreach ($incoming as $variant) {

                    // UPDATE existing
                    if (is_numeric($variant['id'] ?? null)) {

                        $model = $mealPackage->variants()->updateOrCreate(
                            ['id' => $variant['id']],
                            [
                                'sort_order' => $variant['sort_order'],
                                'title' => $variant['title'],
                                'description' => $variant['description'] ?? null,
                                'price' => $variant['price'],
                                'is_published' => $variant['is_published'] ?? false,
                                'is_icon' => $variant['is_icon'] ?? true,
                                'icon_value' => $variant['icon_value'] ?? null,
                                'default_availability' => $variant['default_availability'] ?? true,
                            ]
                        );
                    }

                    // CREATE new
                    else {

                        $model = $mealPackage->variants()->create([
                            'sort_order' => $variant['sort_order'],
                            'title' => $variant['title'],
                            'description' => $variant['description'] ?? null,
                            'price' => $variant['price'],
                            'is_published' => $variant['is_published'] ?? false,
                            'is_icon' => $variant['is_icon'] ?? true,
                            'icon_value' => $variant['icon_value'] ?? null,
                            'default_availability' => $variant['default_availability'] ?? true,
                        ]);
                    }

                    $processedIds[] = $model->id;
                }

                // 🔥 Delete variants that were removed in frontend
                $mealPackage->variants()
                    ->whereNotIn('id', $processedIds)
                    ->delete();
            }


            DB::commit();

            return redirect()
                ->route('meal-packages.index')
                ->with('success', 'Meal package updated successfully.');
        } catch (\Exception $e) {
            DB::rollBack();

            return back()->withErrors([
                // 'error' => 'Something went wrong while updating the meal package.'
                'error' => $e->getMessage()
            ]);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(MealPackage $mealPackage)
    {

        //  1️⃣ Detach all images (pivot table)
        $mealPackage->images()->detach(); // removes all image link
        $mealPackage->variants()->delete();
        $mealPackage->delete();

        return back()->with('success', 'Meal package deleted successfully.');
    }


    private function cleanupScopeRelations(MealPackage $mealPackage, string $newScope)
    {
        switch ($newScope) {
            case 'room':
                $mealPackage->roomCategories()->detach();
                break;

            case 'room_category':
                $mealPackage->rooms()->detach();
                break;

            default:
                $mealPackage->rooms()->detach();
                $mealPackage->roomCategories()->detach();
                break;
        }
    }
}
