<?php

namespace App\Http\Controllers;

use App\Http\Requests\BookingRequest;
use App\Models\Booking;
use App\Models\Service;
use App\Models\PaymentGateway;
use App\Services\BookingStateService;
use Illuminate\Support\Facades\Auth;

class ServiceController extends Controller
{
    public function index()
    {
        $services = Service::with('category', 'provider')->where('status', 'published')->paginate(12);

        return view('services.index', compact('services'));
    }

    public function show(Service $service)
    {
        return view('services.show', compact('service'));
    }

    public function book(Service $service, BookingRequest $request, BookingStateService $state)
    {
        $user = Auth::user();
        $slotStart = now()->parse($request->input('slot_start'));

        $booking = Booking::create([
            'service_id' => $service->id,
            'customer_id' => $user->id,
            'provider_id' => $service->user_id,
            'status' => 'draft',
            'booking_mode' => $service->booking_mode,
            'scheduling_type' => $service->scheduling_type,
            'delivery_mode' => $service->delivery_mode,
            'scheduled_start' => $slotStart,
            'scheduled_end' => $service->duration_minutes ? $slotStart->copy()->addMinutes($service->duration_minutes) : null,
            'timezone' => config('app.timezone'),
            'amount' => $service->base_price,
            'escrow_amount' => $service->base_price,
            'currency' => $service->currency,
            'approval_expires_at' => now()->addHours($service->approval_timeout_hours ?? 24),
            'auto_complete_at' => now()->addHours($service->auto_complete_hours ?? 24),
            'dispute_deadline_at' => now()->addHours($service->dispute_window_hours ?? 48),
            'notes' => $request->input('notes'),
        ]);

        $state->transition($booking, $service->booking_mode === 'instant' ? 'pending_payment' : 'pending_provider_approval');

        return redirect()->route('customer.dashboard')->with('status', 'Booking created. Proceed to payment or await provider action.');
    }
}
