<?php

namespace App\Http\Controllers;

use App\Http\Requests\FacilityRequest;
use App\Models\Facility;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;

class FacilityController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $perPage = request('per_page', 10);

        $facility = Facility::with(['images'])
            ->paginate($perPage)
            ->withQueryString();

        return Inertia::render('dashboard/facilities/index', [
            'facilities' => $facility,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

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

        try {
            $facility = Facility::create([
                'name' => $request['name'],
                'is_icon' => $request['is_icon'],
                'icon_value' => $request['icon_value'],
                'scope' => $request['scope'],
                'is_published' => $request['is_published']
            ]);

            if (!empty($request['images'])) {
                foreach ($request['images'] as $image) {
                    $facility->images()->attach($image['id'], [
                        'role' => $image['role'] ?? 'icon',
                        'sort_order' => $image['sort_order'] ?? 0,
                    ]);
                }
            }

            DB::commit();

            return redirect()
                ->route('facilities.index')
                ->with('success', 'Facility created successfully.');
        } catch (\Exception $e) {

            DB::rollBack();

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

    /**
     * Display the specified resource.
     */
    public function show(Facility $facility)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Facility $facility)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(FacilityRequest $request, Facility $facility)
    {
        DB::beginTransaction();

        try {
            $facility->update([
                'name' => $request['name'],
                'is_icon' => $request['is_icon'],
                'icon_value' => $request['icon_value'],
                'scope' => $request['scope'],
                'is_published' => $request['is_published']
            ]);

            // 2️⃣ Sync images (morphMany)
            if (!empty($request['images'])) {
                // Delete existing images
                $facility->images()->delete();

                // Recreate from request
                foreach ($request['images'] as $image) {
                    $facility->images()->create([
                        'image_id' => $image['id'],
                        'role' => $image['role'] ?? 'icon',
                        'sort_order' => $image['sort_order'] ?? 0,
                    ]);
                }
            } else {
                // No images → delete all
                $facility->images()->delete();
            }


            DB::commit();

            return redirect()
                ->route('facilities.index')
                ->with('success', 'Facility 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(Facility $facility)
    {
        $facility->delete();

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