<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\TransportCompany;
use App\Models\BusRoute;
use App\Models\BusSchedule;
use App\Models\SeatBooking;

class InterstateController extends Controller
{
    public function getCompanies()
    {
        return response()->json(['success' => true, 'companies' => TransportCompany::all()]);
    }

    public function searchRoutes(Request $request)
    {
        $request->validate(['origin' => 'required', 'destination' => 'required', 'date' => 'required|date']);
        $schedules = BusSchedule::with('route.company')
            ->whereDate('departure_date', $request->date)
            ->whereHas('route', function($q) use ($request) {
                $q->where('origin', $request->origin)->where('destination', $request->destination);
            })->get();
        return response()->json(['success' => true, 'schedules' => $schedules]);
    }

    public function bookSeat(Request $request)
    {
        $request->validate([
            'bus_schedule_id' => 'required|exists:bus_schedules,id', 
            'seat_numbers' => 'required|array', 
            'passenger_name' => 'required|string',
            'passenger_phone' => 'required|string',
            'next_of_kin_phone' => 'required|string',
        ]);

        $schedule = BusSchedule::with('route')->findOrFail($request->bus_schedule_id);
        $price = $schedule->route ? $schedule->route->price : 0;
        
        $booking = SeatBooking::create([
            'user_id' => $request->user()->id, 
            'bus_schedule_id' => $schedule->id,
            'seat_numbers' => $request->seat_numbers, 
            'pickup_option' => $request->pickup_option ?? 'Park',
            'passenger_name' => $request->passenger_name, 
            'passenger_phone' => $request->passenger_phone,
            'next_of_kin_phone' => $request->next_of_kin_phone,
            'total_amount' => count($request->seat_numbers) * $price,
            'status' => 'confirmed', 
            'ticket_qr_code' => 'TKT-'.strtoupper(uniqid())
        ]);

        $existingBooked = $schedule->booked_seat_numbers ?? [];
        $schedule->booked_seat_numbers = array_merge($existingBooked, $request->seat_numbers);
        $schedule->available_seats -= count($request->seat_numbers);
        $schedule->save();
        
        return response()->json(['success' => true, 'booking' => $booking]);
    }
}
