<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Driver;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class DriverController extends Controller
{
    /**
     * Get all drivers for the authenticated operator/tenant
     */
    public function index(Request $request)
    {
        try {
            $user = auth('api')->user();
            
            // Get drivers based on user's tenant
            $query = Driver::query();
            
            if ($user->tenant_id) {
                $query->where('tenant_id', $user->tenant_id);
            } else {
                // If user has no tenant_id, return empty list with warning
                return response()->json([
                    'success' => true,
                    'message' => 'No drivers found. User is not associated with a tenant.',
                    'data' => [
                        'current_page' => 1,
                        'data' => [],
                        'total' => 0,
                        'per_page' => 10,
                        'from' => null,
                        'to' => null,
                        'last_page' => 1,
                    ],
                    'debug_info' => [
                        'user_id' => $user->id,
                        'role' => $user->role,
                        'tenant_id' => $user->tenant_id,
                    ]
                ]);
            }
            
            // Apply search filter
            if ($request->has('search')) {
                $search = $request->input('search');
                // Use 'name' column as it exists in users table
                $query->whereHas('user', function ($q) use ($search) {
                    $q->where('name', 'like', "%{$search}%")
                      ->orWhere('email', 'like', "%{$search}%")
                      ->orWhere('phone', 'like', "%{$search}%");
                });
            }
            
            // Apply status filter
            if ($request->has('status')) {
                $query->where('status', $request->input('status'));
            }
            
            // Pagination
            $perPage = min((int) $request->input('per_page', 10), 100);
            $drivers = $query
                ->select('id', 'user_id', 'tenant_id', 'status', 'is_available', 'average_rating', 'total_trips', 'created_at')
                ->with([
                    'user:id,name,phone,email',
                    'vehicle:id,make,model,color,license_plate',
                ])
                ->orderBy('created_at', 'desc')
                ->paginate($perPage);
            
            return response()->json([
                'success' => true,
                'message' => 'Drivers retrieved successfully',
                'data' => $drivers,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error retrieving drivers: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Toggle the authenticated driver's availability (online / offline)
     */
    public function updateMyAvailability(Request $request)
    {
        try {
            $user = auth('api')->user();
            $driver = Driver::where('user_id', $user->id)->first();

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

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

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

            $driver->update([
                'is_available' => $request->boolean('is_available'),
                'last_seen_at' => now(),
            ]);

            return response()->json([
                'success' => true,
                'message' => $request->boolean('is_available') ? 'You are now online.' : 'You are now offline.',
                'data' => [
                    'is_available' => $driver->is_available,
                    'last_seen_at' => $driver->last_seen_at,
                ],
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error updating availability: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Get the authenticated driver's own profile
     */
    public function getMyProfile(Request $request)
    {
        try {
            $user = auth('api')->user();
            $driver = Driver::with('user', 'tenant', 'vehicle')
                ->where('user_id', $user->id)
                ->first();

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

            return response()->json([
                'success' => true,
                'data' => $driver,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error fetching profile: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Get a single driver by ID
     */
    public function show($id)
    {
        try {
            $driver = Driver::with('user', 'tenant', 'vehicle', 'bookings')
                ->findOrFail($id);
            
            // Check authorization
            $user = auth('api')->user();
            if ($driver->tenant_id !== $user->tenant_id) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized',
                ], 403);
            }
            
            return response()->json([
                'success' => true,
                'data' => $driver,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Driver not found',
            ], 404);
        }
    }

    /**
     * Create a new driver
     */
    public function store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|max:255',
                'email' => 'required|string|email|max:255|unique:users',
                'phone' => 'required|string|max:20',
                'password' => 'required|string|min:8|confirmed',
                'license_number' => 'required|string|unique:drivers',
                'license_expiry' => 'required|date',
                'license_country' => 'string',
                'license_state' => 'string',
                'aadhar_number' => 'string',
                'pan_number' => 'string',
                'address' => 'string',
                'city' => 'string',
                'state' => 'string',
                'zip_code' => 'string',
                'emergency_contact' => 'string',
                'emergency_phone' => 'string',
                'vehicle_id' => 'integer|exists:vehicles,id',
            ]);
            
            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors(),
                ], 422);
            }
            
            $user = auth('api')->user();
            $tenantId = $user->tenant_id;
            
            // Check if user has a tenant
            if (!$tenantId) {
                return response()->json([
                    'success' => false,
                    'message' => 'User is not associated with a tenant. Please contact support.',
                    'debug_info' => [
                        'user_id' => $user->id,
                        'role' => $user->role,
                        'tenant_id' => $user->tenant_id,
                    ]
                ], 400);
            }
            
            // Create user account with correct column name 'name'
            $newUser = User::create([
                'name' => $request->input('name'),
                'email' => $request->input('email'),
                'phone' => $request->input('phone'),
                'password' => Hash::make($request->input('password')),
                'role' => 'driver',
                'tenant_id' => $tenantId,
                'status' => 'active',
            ]);
            
            // Create driver profile
            $driver = Driver::create([
                'tenant_id' => $tenantId,
                'user_id' => $newUser->id,
                'license_number' => $request->input('license_number'),
                'license_expiry' => $request->input('license_expiry'),
                'license_country' => $request->input('license_country'),
                'license_state' => $request->input('license_state'),
                'status' => 'active',
                'total_trips' => 0,
                'total_earnings' => 0,
                'average_rating' => 0,
            ]);
            
            // Load relationships
            $driver->load('user', 'tenant');
            
            return response()->json([
                'success' => true,
                'message' => 'Driver created successfully',
                'data' => $driver,
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error creating driver: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Update a driver
     */
    public function update(Request $request, $id)
    {
        try {
            $driver = Driver::findOrFail($id);
            
            // Check authorization
            $user = auth('api')->user();
            if ($driver->tenant_id !== $user->tenant_id) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized',
                ], 403);
            }
            
            $validator = Validator::make($request->all(), [
                'license_number' => 'string|unique:drivers,license_number,' . $id,
                'license_expiry' => 'date',
                'status' => 'in:active,inactive,suspended,pending_verification,document_review',
                'vehicle_id' => 'integer|exists:vehicles,id',
            ]);
            
            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors(),
                ], 422);
            }
            
            // Update user details if provided - save to full_name / first_name / last_name
            if ($request->has('name') || $request->has('phone')) {
                $updated = [];
                if ($request->has('name')) {
                    $displayName = $request->input('name');
                    $updated['full_name'] = $displayName;
                    if (strpos(trim($displayName), ' ') !== false) {
                        $parts = preg_split('/\s+/', trim($displayName));
                        $updated['first_name'] = array_shift($parts);
                        $updated['last_name'] = implode(' ', $parts);
                    } else {
                        $updated['first_name'] = $displayName;
                        $updated['last_name'] = null;
                    }
                }

                if ($request->has('phone')) {
                    $updated['phone'] = $request->input('phone');
                }

                if (!empty($updated)) {
                    $driver->user->update($updated);
                }
            }
            
            // Update driver details
            $driver->update($request->only([
                'license_number', 'license_expiry', 'license_country', 
                'license_state', 'status', 'vehicle_id'
            ]));
            
            $driver->load('user', 'tenant');
            
            return response()->json([
                'success' => true,
                'message' => 'Driver updated successfully',
                'data' => $driver,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error updating driver: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Delete a driver
     */
    public function destroy($id)
    {
        try {
            $driver = Driver::findOrFail($id);
            
            // Check authorization
            $user = auth('api')->user();
            if ($driver->tenant_id !== $user->tenant_id) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized',
                ], 403);
            }
            
            $driver->delete();
            
            return response()->json([
                'success' => true,
                'message' => 'Driver deleted successfully',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error deleting driver: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Get driver statistics
     */
    public function statistics($id)
    {
        try {
            $driver = Driver::findOrFail($id);
            
            // Check authorization
            $user = auth('api')->user();
            if ($driver->tenant_id !== $user->tenant_id) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized',
                ], 403);
            }
            
            return response()->json([
                'success' => true,
                'data' => [
                    'id' => $driver->id,
                    'name' => $driver->user->full_name ?? ($driver->user->first_name ?? $driver->user->email),
                    'total_trips' => $driver->total_trips,
                    'total_earnings' => $driver->total_earnings,
                    'average_rating' => $driver->average_rating,
                    'status' => $driver->status,
                    'license_expiry' => $driver->license_expiry,
                ],
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Driver not found',
            ], 404);
        }
    }

    /**
     * Update driver status
     */
    public function updateStatus(Request $request, $id)
    {
        try {
            $driver = Driver::findOrFail($id);
            
            // Check authorization
            $user = auth('api')->user();
            if ($driver->tenant_id !== $user->tenant_id) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized',
                ], 403);
            }
            
            $validator = Validator::make($request->all(), [
                'status' => 'required|in:active,pending,suspended,inactive',
            ]);
            
            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors(),
                ], 422);
            }
            
            $driver->update(['status' => $request->input('status')]);
            
            return response()->json([
                'success' => true,
                'message' => 'Driver status updated successfully',
                'data' => $driver,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error updating status: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Get available drivers for the authenticated tenant
     * Fetches drivers from the Driver model (tenant-scoped) and returns profile info.
     */
    public function getAvailableDrivers(Request $request)
    {
        try {
            $user = auth('api')->user();
            $tenantId = $user->tenant_id;

            // Check if user has a tenant
            if (!$tenantId) {
                return response()->json([
                    'success' => false,
                    'message' => 'User is not associated with a tenant.',
                    'data' => []
                ], 400);
            }

            // Query drivers for the tenant. Exclude explicitly suspended drivers but keep statuses like 'on_break'.
            $query = Driver::where('tenant_id', $tenantId)
                ->whereNotIn('status', ['suspended']);

            // Apply search filter if provided (search against related user fields)
            if ($request->has('search') && $request->input('search')) {
                $search = $request->input('search');
                $query->whereHas('user', function ($q) use ($search) {
                    $q->where('full_name', 'like', "%{$search}%")
                      ->orWhere('first_name', 'like', "%{$search}%")
                      ->orWhere('last_name', 'like', "%{$search}%")
                      ->orWhere('email', 'like', "%{$search}%")
                      ->orWhere('phone', 'like', "%{$search}%");
                });
            }

            $drivers = $query->with('user')
                ->orderBy('id', 'desc')
                ->get();

            // Transform to API-friendly shape used by frontend
            $availableDrivers = $drivers->map(function ($driver) {
                $user = $driver->user;
                // Try to get name from various possible columns
                $name = $user->name 
                    ?? ($user->full_name 
                        ?? trim(($user->first_name ?? '') . ' ' . ($user->last_name ?? '')));
                return [
                    'id' => (string)($driver->id),
                    'driver_id' => (string)($driver->id),
                    'user_id' => (string)($user->id ?? $driver->user_id),
                    'name' => $name ?: ('Driver ' . $driver->id),
                    'first_name' => $user->first_name ?? null,
                    'last_name' => $user->last_name ?? null,
                    'email' => $user->email ?? null,
                    'phone' => $user->phone ?? null,
                    'avatar_url' => $user->avatar_url ?? null,
                    'status' => $driver->status ?? ($user->status ?? 'active'),
                    'rating' => $driver->average_rating ?? 0,
                    'total_trips' => $driver->total_trips ?? 0,
                    'user_type' => $user->user_type ?? 'driver',
                ];
            })->values();

            return response()->json([
                'success' => true,
                'message' => 'Available drivers retrieved successfully',
                'data' => $availableDrivers,
                'total' => count($availableDrivers),
                'tenant_id' => $tenantId,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error retrieving available drivers: ' . $e->getMessage(),
                'data' => []
            ], 500);
        }
    }
}
