<?php

namespace App\Http\Controllers;

use App\Models\Barber;
use App\Models\BarberBlock;
use Illuminate\Http\Request;

class BarberBlockAdminController extends Controller
{
    public function index(Request $request, int $barberId)
    {
        Barber::findOrFail($barberId);

        $query = BarberBlock::where('barber_id', $barberId)->orderBy('block_date')->orderBy('start_time');

        if ($request->filled('from')) {
            $query->where('block_date', '>=', $request->query('from'));
        }
        if ($request->filled('to')) {
            $query->where('block_date', '<=', $request->query('to'));
        }

        return response()->json($query->get());
    }

    public function store(Request $request, int $barberId)
    {
        Barber::findOrFail($barberId);

        $validated = $request->validate([
            'block_date' => 'required|date',
            'start_time' => 'required|date_format:H:i',
            'end_time' => 'required|date_format:H:i|after:start_time',
            'kind' => 'required|in:block,open',
            'reason' => 'nullable|string|max:200',
        ]);

        $block = BarberBlock::create([
            'barber_id' => $barberId,
            'block_date' => $validated['block_date'],
            'start_time' => $validated['start_time'],
            'end_time' => $validated['end_time'],
            'kind' => $validated['kind'],
            'reason' => $validated['reason'] ?? null,
        ]);

        return response()->json($block, 201);
    }

    public function destroy(int $barberId, int $blockId)
    {
        $block = BarberBlock::where('barber_id', $barberId)->where('id', $blockId)->firstOrFail();
        $block->delete();
        return response()->json(['message' => 'Eliminado']);
    }
}
