<?php

namespace App\Http\Controllers\Admin\Room;

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

class CustomerOutingController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = CustomerOuting::query()->with(['reservation.room', 'customer']);
        $query->when($request->reservation_id, fn($q, $v) => $q->where('reservation_id', $v));
        $query->when($request->customer_id, fn($q, $v) => $q->where('customer_id', $v));

        return $this->paginate($query->latest()->paginate($request->input('per_page', 15)));
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'reservation_id' => 'required|exists:reservations,id',
            'customer_id' => 'required|exists:customers,id',
            'out_at' => 'required|date',
            'expected_back_at' => 'nullable|date|after:out_at',
            'reason' => 'nullable|string',
            'risk_note' => 'nullable|string',
        ]);
        $validated['created_by'] = auth()->id();

        return $this->success(CustomerOuting::create($validated));
    }

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

    public function recordBack(Request $request, CustomerOuting $customerOuting): JsonResponse
    {
        if ($customerOuting->actual_back_at) {
            return $this->error('已记录返回时间', 40001);
        }
        $customerOuting->update(['actual_back_at' => $request->input('actual_back_at', now())]);
        return $this->success($customerOuting);
    }
}
