<?php

namespace App\Http\Controllers;

use App\Http\Requests\AddonRequest;
use App\Models\Addon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;

class AddonController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $perPage = request('per_page', 10);
        $addOns = Addon::with(['images', 'availabilityRules', 'variants'])
            ->paginate($perPage)
            ->withQueryString();

        return Inertia::render('dashboard/add-ons/index', [
            'addons' => $addOns,
        ]);
    }

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

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

        try {

            // Create addon
            $addon = Addon::create([
                'title' => $request['title'],
                'description' => $request['description'] ?? null,

                'price' => $request['price'],
                'unit' => $request['unit'],
                'currency' => $request['currency'],

                'calculation_type' => $request['calculation_type'],
                'scope' => $request['scope'],

                'tag' => $request['tag'] ?? null,
                'icon' => $request['icon'] ?? null,
                'icon_url' => $request['icon_url'] ?? null,

                'is_variant' => $request['is_variant'] ?? false,
                'default_active' => $request['default_active'] ?? true,
                'is_published' => $request['is_published'] ?? true,
            ]);

            /*
            |--------------------------------------------------------------------------
            | Attach Images (Polymorphic)
            |--------------------------------------------------------------------------
            */
            if (!empty($request['images'])) {
                foreach ($request['images'] as $image) {
                    $addon->images()->attach($image['id'], [
                        'role' => $image['role'] ?? 'icon',
                        'sort_order' => $image['sort_order'] ?? 0,
                    ]);
                }
            }

            /*
            |--------------------------------------------------------------------------
            | Attach Rooms (Pivot: addon_room)
            |--------------------------------------------------------------------------
            | Only if scope = room
            */
            if ($request['scope'] === 'room' && !empty($request['room_ids'])) {
                $addon->rooms()->sync($request['room_ids']);
            }

            /*
            |--------------------------------------------------------------------------
            | Sync Variants
            |--------------------------------------------------------------------------
            */
            if ($request->is_variant && !empty($request->variants)) {

                foreach ($request->variants as $variant) {

                    $addon->variants()->create([
                        'title'       => $variant['title'],
                        'description' => $variant['description'] ?? null,
                        'price'       => $variant['price'],
                        'currency'    => $variant['currency'],
                        'max_guests'  => $variant['max_guests'] ?? null,
                        'icon'        => $variant['icon'] ?? null,
                        'icon_url'    => $variant['icon_url'] ?? null,
                    ]);
                }
            }

            DB::commit();

            return redirect()
                ->route('add-ons.index')
                ->with('success', 'Add-On created successfully.');
        } catch (\Exception $e) {

            DB::rollBack();

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

    /**
     * Display the specified resource.
     */
    public function show(Addon $addOn)
    {

        $addOn->load([
            'images' =>  fn($q) => $q->orderBy('sort_order'),
            'availabilityRules',
            'variants'
        ]);


        return Inertia::render('dashboard/add-ons/add-on', [
            'addon' => $addOn,
            'mode' => 'view'
        ]);
    }

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

        return Inertia::render('dashboard/add-ons/add-on', [
            'addon' => $addOn,
            'mode' => 'edit'
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(AddonRequest $request, Addon $addOn)
    {
        DB::beginTransaction();

        try {
            $validated = $request->validated();

            /*
            |--------------------------------------------------------------------------
            | 1️⃣ Update Main Fields
            |--------------------------------------------------------------------------
            */
            $addOn->update([
                'title' => $validated['title'],
                'description' => $validated['description'] ?? null,
                'price' => $validated['price'],
                'unit' => $validated['unit'],
                'currency' => $validated['currency'],
                'calculation_type' => $validated['calculation_type'],
                'scope' => $validated['scope'],
                'tag' => $validated['tag'] ?? null,
                'icon' => $validated['icon'] ?? null,
                'icon_url' => $validated['icon_url'] ?? null,
                'is_variant' => $request['is_variant'] ?? false,
                'default_active' => $request['default_active'] ?? true,
                'is_published' => $request['is_published'] ?? true,
            ]);

            /*
            |--------------------------------------------------------------------------
            | 2️⃣ Sync Images (MorphMany)
            |--------------------------------------------------------------------------
            */
            if (!empty($validated['images'])) {

                // Delete old related images
                $addOn->images()->delete();

                // Recreate
                foreach ($validated['images'] as $image) {
                    $addOn->images()->create([
                        'image_id'   => $image['id'],
                        'role'       => $image['role'] ?? 'icon',
                        'sort_order' => $image['sort_order'] ?? 0,
                    ]);
                }
            } else {
                $addOn->images()->delete();
            }

            /*
            |--------------------------------------------------------------------------
            | 3️⃣ Sync Rooms (Only if scope = room)
            |--------------------------------------------------------------------------
            */
            if ($validated['scope'] === 'room' && !empty($validated['room_ids'])) {
                $addOn->rooms()->sync($validated['room_ids']);
            } else {
                $addOn->rooms()->detach();
            }

            /*
            |--------------------------------------------------------------------------
            | VARIANT LOGIC
            |--------------------------------------------------------------------------
            */

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

                $addOn->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 = $addOn->variants()->updateOrCreate(
                            ['id' => $variant['id']],
                            [
                                'title' => $variant['title'],
                                'description' => $variant['description'] ?? null,
                                'price' => $variant['price'],
                                'currency' => $variant['currency'],
                                'max_guests' => $variant['max_guests'] ?? null,
                                'icon' => $variant['icon'] ?? null,
                                'icon_url' => $variant['icon_url'] ?? null,
                            ]
                        );
                    }

                    // CREATE new
                    else {

                        $model = $addOn->variants()->create([
                            'title' => $variant['title'],
                            'description' => $variant['description'] ?? null,
                            'price' => $variant['price'],
                            'currency' => $variant['currency'],
                            'max_guests' => $variant['max_guests'] ?? null,
                            'icon' => $variant['icon'] ?? null,
                            'icon_url' => $variant['icon_url'] ?? null,
                        ]);
                    }

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

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

            DB::commit();

            return redirect()
                ->route('add-ons.index')
                ->with('success', 'Add-On updated successfully.');
        } catch (\Exception $e) {

            DB::rollBack();

            return back()->withErrors([
                'error' => $e->getMessage()
            ]);
        }
    }
    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Addon $addOn)
    {
        $addOn->delete();

        return back()->with('success', 'Add-On deleted successfully.');
    }
}
