<?php

namespace App\Http\Controllers\Admin\Room;

use App\Http\Controllers\Controller;
use App\Models\Room\Room;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class RoomController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Room::query()->with('roomType');
        $query->when($request->room_type_id, fn($q, $v) => $q->where('room_type_id', $v));
        $query->when($request->floor, fn($q, $v) => $q->where('floor', $v));
        $query->when($request->status, fn($q, $v) => $q->where('status', $v));
        $query->when($request->number, fn($q, $v) => $q->where('number', 'like', "%{$v}%"));

        return $this->paginate($query->orderBy('sort')->paginate($request->input('per_page', 50)));
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'room_type_id' => 'required|exists:room_types,id',
            'floor' => 'nullable|string|max:10',
            'number' => 'required|string|max:20',
            'status' => 'sometimes|integer|in:1,2,3,4,5',
            'sort' => 'sometimes|integer',
        ]);
        return $this->success(Room::create($validated));
    }

    public function show(Room $room): JsonResponse
    {
        return $this->success($room->load(['roomType', 'reservations.customer']));
    }

    public function update(Request $request, Room $room): JsonResponse
    {
        $validated = $request->validate([
            'room_type_id' => 'sometimes|exists:room_types,id',
            'floor' => 'nullable|string|max:10',
            'number' => 'sometimes|string|max:20',
            'sort' => 'sometimes|integer',
        ]);
        $room->update($validated);
        return $this->success($room);
    }

    public function destroy(Room $room): JsonResponse
    {
        if ($room->status === 3) {
            return $this->error('入住中的房间无法删除', 40001);
        }
        $room->delete();
        return $this->success(null);
    }

    public function updateStatus(Request $request, Room $room): JsonResponse
    {
        $validated = $request->validate([
            'status' => 'required|integer|in:1,2,3,4,5',
        ]);
        $room->update($validated);
        return $this->success($room);
    }
}
