<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Driver;
use App\Models\Ride;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;

class DriverController extends Controller
{
    /**
     * Register a new driver profile and vehicle.
     */
    public function register(Request $request)
    {
        $request->validate([
            'make' => 'required',
            'model' => 'required',
            'year' => 'required',
            'license_plate' => 'required|unique:drivers,license_plate',
            'color' => 'required',
        ]);

        $user = $request->user();
        
        $driver = Driver::updateOrCreate(
            ['user_id' => $user->id],
            [
                'make' => $request->make,
                'model' => $request->model,
                'year' => $request->year,
                'license_plate' => $request->license_plate,
                'color' => $request->color,
                'status' => 'active', 
            ]
        );

        $user->update(['user_type' => 'driver']);

        return response()->json([
            'success' => true, 
            'message' => 'Driver registered successfully',
            'driver' => $driver
        ]);
    }

    /**
     * Update driver online status.
     */
    public function updateStatus(Request $request)
    {
        $user = $request->user();

        if ($user->user_type !== 'driver') {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized. Only drivers can update their status.'
            ], 403);
        }

        $validator = Validator::make($request->all(), [
            'is_online' => 'required|boolean',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors()
            ], 422);
        }

        $driver = Driver::where('user_id', $user->id)->first();
        
        if (!$driver) {
            return response()->json([
                'success' => false,
                'message' => 'Driver profile not found.'
            ], 404);
        }

        $driver->update([
            'is_online' => $request->is_online,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Driver status updated successfully.',
            'is_online' => (bool)$driver->is_online
        ]);
    }

    /**
     * Update driver's current location.
     */
    public function updateLocation(Request $request)
    {
        $user = $request->user();
        $driver = Driver::where('user_id', $user->id)->first();

        if (!$driver) {
            return response()->json(['success' => false, 'message' => 'Driver not found.'], 404);
        }

        $validator = Validator::make($request->all(), [
            'latitude' => 'required|numeric',
            'longitude' => 'required|numeric',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
        }

        $driver->update([
            'current_location_lat' => $request->latitude,
            'current_location_lng' => $request->longitude,
        ]);

        return response()->json(['success' => true, 'message' => 'Location updated.']);
    }

    /**
     * Get pending ride requests for the driver.
     */
    public function getPendingRide(Request $request)
    {
        $user = $request->user();
        $driver = Driver::where('user_id', $user->id)->first();

        if (!$driver || !$driver->is_online) {
            return response()->json([
                'success' => false, 
                'message' => 'Driver must be online to receive requests.'
            ], 400);
        }

        // Find rides with 'pending' status that haven't been assigned
        // Haversine formula to find rides within 5km radius
        $latitude = $driver->current_location_lat;
        $longitude = $driver->current_location_lng;

        if (!$latitude || !$longitude) {
            return response()->json([
                'success' => false,
                'message' => 'Driver location unknown.'
            ], 400);
        }

        $ride = Ride::where('status', 'pending')
            ->whereNull('driver_id')
            ->select('*')
            ->selectRaw(
                "(6371 * acos(cos(radians(?)) * cos(radians(pickup_lat)) * cos(radians(pickup_lng) - radians(?)) + sin(radians(?)) * sin(radians(pickup_lat)))) AS distance",
                [$latitude, $longitude, $latitude]
            )
            ->having('distance', '<', 5) // Within 5km
            ->orderBy('distance', 'asc')
            ->first();

        if (!$ride) {
            return response()->json([
                'success' => true,
                'message' => 'No active ride requests nearby.',
                'ride' => null
            ]);
        }

        return response()->json([
            'success' => true,
            'ride' => $ride
        ]);
    }
}
