<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\ApiController;
use App\Http\Requests\GuestRoomStoreRequest;
use App\Http\Requests\GuestRoomUpdateRequest;
use App\Http\Resources\GuestRoomResource;
use App\Models\GuestRoom;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class GuestRoomController extends ApiController
{
    /**
     * Construct middleware and initiated backups list
     */
    public function __construct()
    {
        $this->middleware('auth:sanctum');
        $this->middleware('demo')->only(['update', 'destroy']);
    }


    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): JsonResponse
    {
        $guestRooms = GuestRoom::latest()->get();
        return response()->json(GuestRoomResource::collection($guestRooms));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(GuestRoomStoreRequest $request): JsonResponse
    {
        $guestRoom = GuestRoom::create($request->validated());
        \App\Helpers\ActivityLogger::log(__('New guest room added successfully'), $guestRoom->title);
        return response()->json([
            'message' => __('Data saved successfully'),
            'guest_room' => $guestRoom->id,
        ]);
    }

    /**
     * Display the specified resource.
     */
    public function show(GuestRoom $guestRoom): JsonResponse
    {
        return response()->json(new GuestRoomResource($guestRoom));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(GuestRoomUpdateRequest $request, GuestRoom $guestRoom): JsonResponse
    {
        $guestRoom->update($request->validated());
        \App\Helpers\ActivityLogger::log(__('Guest room information updated successfully'), $guestRoom->title);
        return response()->json([
            'message' => __('Data updated successfully'),
        ]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(GuestRoom $guestRoom): JsonResponse
    {
        if ($guestRoom->guestRoomReservations->count() < 1) {
            $guestRoom->delete();
            \App\Helpers\ActivityLogger::log(__('Guest room removed successfully'));
            return response()->json(['message' => __('Data removed successfully')]);
        }

        return response()->json(['message' => __('Unable to remove guest room information is being used')], 422);
    }
}
