<?php

namespace App\Http\Controllers;

use App\Models\RideRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use Illuminate\Http\JsonResponse;
use App\Models\CaptainProfile;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
use App\Events\RideAccepted;
use App\Events\RideRequested;
use App\Events\CaptainReached;
use App\Events\RideStarted;
use App\Events\RideCompleted;
use App\Models\Review;

class RideController extends Controller
{
    /**
     * Handle an incoming ride request from a passenger.
     */
   public function requestRide(Request $request)
{
    $validated = $request->validate([
        'pickup_address' => 'required|string',
        'pickup_lat' => 'required|numeric',
        'pickup_lng' => 'required|numeric',
        'dropoff_address' => 'required|string',
        'dropoff_lat' => 'required|numeric',
        'dropoff_lng' => 'required|numeric',
        'vehicle_type' => 'required|string',
    ]);

    $authId = Auth::id();

    // Save the ride request
    $rideRequest = RideRequest::create([
        'passenger_id'   => $authId,
        'pickup_address' => $validated['pickup_address'],
        'pickup_lat'     => $validated['pickup_lat'],
        'pickup_lng'     => $validated['pickup_lng'],
        'dropoff_address'=> $validated['dropoff_address'],
        'dropoff_lat'    => $validated['dropoff_lat'],
        'dropoff_lng'    => $validated['dropoff_lng'],
        'vehicle_type'   => $validated['vehicle_type'],
        'status'         => 'pending',
    ]);

    // Log debug info
    \Log::info('Ride requested', [
        'auth_id_at_save' => $authId,
        'saved_passenger_id' => $rideRequest->passenger_id,
        'ride_id' => $rideRequest->id,
    ]);

    // Fire event (for captains)
    event(new RideRequested($rideRequest));

    return response()->json([
        'success'     => true,
        'redirectUrl' => route('ride.searching', ['rideRequest' => $rideRequest->id])
    ]);
    
}

public function getRideStatus(RideRequest $rideRequest): JsonResponse
{
    // Eager-load the captain's details for the passenger
    $rideRequest->load('captain.captainProfile');

    return response()->json($rideRequest);
}
    /**
     * Get a list of pending rides for the current Captain based on their vehicle type.
     */
    public function getPendingRides(): JsonResponse
    {
        $user = Auth::user();

        $isCaptainAndActive = $user && 
                            $user->role === 'captain' && 
                            optional($user->captainProfile)->status && 
                            $user->captainProfile->status->value === 'active';

        if (!$isCaptainAndActive) {
            return response()->json([], 200);
        }

        $captainVehicleType = $user->captainProfile->vehicle_type;

        $rides = RideRequest::where('status', 'pending')
            ->where('vehicle_type', $captainVehicleType)
            ->get();
        
        return response()->json($rides);
    }

    public function acceptRide(RideRequest $rideRequest): RedirectResponse
{
    if ($rideRequest->status === 'pending') {
        $rideRequest->status = 'in_progress';
        $rideRequest->captain_id = Auth::id();
        $rideRequest->save();

        // Eager-load the captain and their profile before broadcasting
        $rideRequest->load('captain.captainProfile'); // <-- This is the key line

        event(new \App\Events\RideAccepted($rideRequest));

        return redirect()->route('ride.ongoing', $rideRequest->id);
    }
    
    return back()->with('error', 'This ride is no longer available.');
}
public function getRideStatusAjax(RideRequest $rideRequest): JsonResponse
{
    // Verify the authenticated user is either the captain or passenger
    if (!in_array(Auth::id(), [$rideRequest->captain_id, $rideRequest->passenger_id])) {
        return response()->json(['error' => 'Unauthorized'], 403);
    }

    $rideRequest->load(['captain.captainProfile', 'passenger']);

    return response()->json([
        'status' => $rideRequest->status,
        'captain' => $rideRequest->captain ? [
            'id' => $rideRequest->captain->id,
            'name' => $rideRequest->captain->name,
            'captain_profile' => [
                'vehicle_make' => $rideRequest->captain->captainProfile->vehicle_make,
                'vehicle_model' => $rideRequest->captain->captainProfile->vehicle_model,
                'vehicle_plate_number' => $rideRequest->captain->captainProfile->vehicle_plate_number,
                'current_lat' => $rideRequest->captain->captainProfile->current_lat,
                'current_lng' => $rideRequest->captain->captainProfile->current_lng,
            ]
        ] : null,
        'pickup_lat' => $rideRequest->pickup_lat,
        'pickup_lng' => $rideRequest->pickup_lng,
        'dropoff_lat' => $rideRequest->dropoff_lat,
        'dropoff_lng' => $rideRequest->dropoff_lng,
    ]);
}

    public function declineRide(RideRequest $rideRequest): RedirectResponse
    {
        if ($rideRequest->status === 'pending') {
            $rideRequest->status = 'declined';
            $rideRequest->save();
        }

        return back()->with('success', 'You have declined the ride request.');
    }

   public function showOngoingRide(RideRequest $rideRequest): View
{
    if ((int) $rideRequest->captain_id !== (int) Auth::id()) {
        return redirect()->route('dashboard')
            ->with('error', 'Unauthorized access.');
    }
    
    $rideRequest->load('passenger');
    
    return view('ride.ongoing', compact('rideRequest'));
}


public function showSearchingPage(RideRequest $rideRequest)
{
    // Ensure the logged-in user is the passenger who requested this ride
    if ((int) $rideRequest->passenger_id !== (int) Auth::id()) {
        return redirect()->route('dashboard')
            ->with('error', 'Unauthorized access or ride not found.');
    }

    return view('ride.searching', compact('rideRequest'));
}





    public function showPassengerOngoingRide(RideRequest $rideRequest): View
    {
        if ($rideRequest->passenger_id !== Auth::id()) {
            return redirect()->route('dashboard')->with('error', 'Unauthorized access.');
        }

        return view('ride.ongoing-passenger', compact('rideRequest'));
    }
    // in RideController.php

/**
 * Mark the ride as 'reached pickup location'.
 */
public function captainReached(RideRequest $rideRequest): RedirectResponse
{
    if ((int) $rideRequest->captain_id === (int) Auth::id() && $rideRequest->status === 'in_progress') {
        $rideRequest->status = 'at_pickup';
        $rideRequest->save();

        // Notify the passenger that the captain has arrived
        event(new CaptainReached($rideRequest));

        return back()->with('success', 'You have arrived at the pickup location.');
    }

    return back()->with('error', 'Unable to update ride status.');
}


/**
 * Start the ride journey.
 */
public function startRide(RideRequest $rideRequest): RedirectResponse
{
    if ((int) $rideRequest->captain_id === (int) Auth::id() && $rideRequest->status === 'at_pickup') {
        $rideRequest->status = 'on_ride';
        $rideRequest->save();

        // Notify the passenger that the ride has started
        event(new RideStarted($rideRequest));

        return back()->with('success', 'Ride has started.');
    }

    return back()->with('error', 'Unable to start the ride.');
}


/**
 * Complete the ride.
 */
public function completeRide(RideRequest $rideRequest): RedirectResponse
{
    if ((int) $rideRequest->captain_id === (int) Auth::id() && $rideRequest->status === 'on_ride') {
        $rideRequest->status = 'completed';
        $rideRequest->save();

        event(new RideCompleted($rideRequest));

        // Redirect to review page
        return redirect()->route('ride.review', $rideRequest->id)
            ->with('success', 'Ride completed! Please review your passenger.');
    }

    return back()->with('error', 'Unable to complete the ride.');
}

public function showReviewForm(RideRequest $rideRequest)
{
    // Verify user is either captain or passenger of this ride
    if (!in_array(Auth::id(), [$rideRequest->captain_id, $rideRequest->passenger_id])) {
        return redirect()->route('dashboard')->with('error', 'Unauthorized access.');
    }

    $userToReview = Auth::id() === $rideRequest->captain_id 
        ? $rideRequest->passenger 
        : $rideRequest->captain;

    return view('ride.review', [
        'ride' => $rideRequest,
        'userToReview' => $userToReview,
        'isCaptain' => Auth::id() === $rideRequest->captain_id
    ]);
}

public function submitReview(RideRequest $rideRequest, Request $request)
{
    $validated = $request->validate([
        'rating' => 'required|integer|between:1,5',
        'comment' => 'nullable|string|max:500'
    ]);

    // Determine who is reviewing whom
    $reviewerId = Auth::id();
    $reviewedId = $reviewerId === $rideRequest->captain_id 
        ? $rideRequest->passenger_id 
        : $rideRequest->captain_id;

    // Create review
    Review::create([
        'ride_id' => $rideRequest->id,
        'reviewer_id' => $reviewerId,
        'reviewed_id' => $reviewedId,
        'rating' => $validated['rating'],
        'comment' => $validated['comment']
    ]);

    return redirect()->route('dashboard')
        ->with('success', 'Review submitted successfully!');
}
}