<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Driver;
use App\Models\Load;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class DriverPortalController extends Controller
{
    private function resolveDriver(Request $request): ?Driver
    {
        $user = $request->user();

        if (!$user || !$user->company_id) {
            return null;
        }

        return Driver::query()
            ->where('company_id', $user->company_id)
            ->where(function ($query) use ($user) {
                $query->where('email', $user->email)
                    ->orWhere('name', $user->name);
            })
            ->with('truck')
            ->first();
    }

    public function dashboard(Request $request): JsonResponse
    {
        $user = $request->user();

        if ($user->role !== 'driver') {
            return response()->json([
                'success' => false,
                'message' => 'Only drivers can access this dashboard.',
            ], 403);
        }

        $driver = $this->resolveDriver($request);

        if (!$driver) {
            return response()->json([
                'success' => true,
                'data' => [
                    'driver' => null,
                    'stats' => [
                        'assigned_loads' => 0,
                        'completed_loads' => 0,
                        'pending_loads' => 0,
                        'total_earnings' => 0,
                        'truck' => null,
                    ],
                    'recent_loads' => [],
                ],
            ], 200);
        }

        $loadsQuery = Load::query()->where('driver_id', $driver->id);

        $assignedLoads = (clone $loadsQuery)->count();
        $completedLoads = (clone $loadsQuery)->where('status', 'completed')->count();
        $pendingLoads = (clone $loadsQuery)->whereIn('status', ['pending', 'processed'])->count();
        $totalEarnings = (clone $loadsQuery)->sum('driver_salary');

        $recentLoads = (clone $loadsQuery)
            ->with('truck')
            ->latest()
            ->limit(5)
            ->get();

        return response()->json([
            'success' => true,
            'data' => [
                'driver' => [
                    'id' => $driver->id,
                    'name' => $driver->name,
                    'email' => $driver->email,
                    'phone' => $driver->phone,
                ],
                'stats' => [
                    'assigned_loads' => $assignedLoads,
                    'completed_loads' => $completedLoads,
                    'pending_loads' => $pendingLoads,
                    'total_earnings' => (float) $totalEarnings,
                    'truck' => $driver->truck ? [
                        'id' => $driver->truck->id,
                        'number' => $driver->truck->number,
                        'name' => $driver->truck->name,
                    ] : null,
                ],
                'recent_loads' => $recentLoads,
            ],
        ], 200);
    }

    public function loads(Request $request): JsonResponse
    {
        $user = $request->user();

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

        $driver = $this->resolveDriver($request);

        if (!$driver) {
            return response()->json([
                'success' => true,
                'data' => [],
                'pagination' => [
                    'current_page' => 1,
                    'per_page' => (int) $request->input('per_page', 15),
                    'total' => 0,
                    'last_page' => 1,
                ],
            ], 200);
        }

        $query = Load::query()
            ->where('driver_id', $driver->id)
            ->with(['truck', 'driver'])
            ->latest();

        if ($request->filled('status')) {
            $query->where('status', $request->input('status'));
        }

        if ($request->filled('search')) {
            $search = $request->input('search');
            $query->where(function ($builder) use ($search) {
                $builder->where('load_number', 'like', "%{$search}%")
                    ->orWhere('pickup_location', 'like', "%{$search}%")
                    ->orWhere('delivery_location', 'like', "%{$search}%")
                    ->orWhere('broker_company', 'like', "%{$search}%");
            });
        }

        $loads = $query->paginate($request->input('per_page', 15));

        return response()->json([
            'success' => true,
            'data' => $loads->items(),
            'pagination' => [
                'current_page' => $loads->currentPage(),
                'per_page' => $loads->perPage(),
                'total' => $loads->total(),
                'last_page' => $loads->lastPage(),
            ],
        ], 200);
    }
}
