<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\DriverVehicle;
use App\Models\DriverOrderIssue;
use App\Models\Load;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;

class DriverController extends Controller
{
    // ─────────────────────────────────────────────────────────────────
    // 1. Profile
    // ─────────────────────────────────────────────────────────────────

    /** GET /driver/profile */
    public function getProfile(Request $request)
    {
        $user = $request->user()->load('location');
        return response()->json(['success' => true, 'data' => $user]);
    }

    /** POST /driver/profile */
    public function updateProfile(Request $request)
    {
        $request->validate([
            'name'               => 'sometimes|string|max:100',
            'national_id'        => 'sometimes|string|max:20',
            'license_number'     => 'sometimes|string|max:50',
            'smart_card_number'  => 'sometimes|string|max:50',
        ]);

        $user = $request->user();
        $user->update($request->only(['name', 'national_id', 'license_number', 'smart_card_number']));

        return response()->json(['success' => true, 'message' => 'پروفایل بروزرسانی شد', 'data' => $user]);
    }

    /** GET /driver/status — استعلام وضعیت تایید */
    public function getStatus(Request $request)
    {
        $user = $request->user();
        return response()->json([
            'success'       => true,
            'driver_status' => $user->driver_status ?? 'PENDING',
            'is_verified'   => ($user->driver_status === 'VERIFIED'),
        ]);
    }

    // ─────────────────────────────────────────────────────────────────
    // 2. Vehicles
    // ─────────────────────────────────────────────────────────────────

    /** GET /driver/vehicles */
    public function getVehicles(Request $request)
    {
        $vehicles = DriverVehicle::where('driver_id', $request->user()->id)
            ->orderByDesc('is_default')
            ->get();
        return response()->json(['success' => true, 'data' => $vehicles]);
    }

    /** POST /driver/vehicle */
    public function addVehicle(Request $request)
    {
        $request->validate([
            'plate_number'  => 'required|string|max:20',
            'vehicle_type'  => 'nullable|string|max:50',
            'capacity_ton'  => 'nullable|numeric|min:0',
            'smart_card_number' => 'nullable|string|max:50',
        ]);

        $driverId = $request->user()->id;

        // If first vehicle, make it default
        $isFirst = !DriverVehicle::where('driver_id', $driverId)->exists();

        $vehicle = DriverVehicle::create([
            'driver_id'         => $driverId,
            'plate_number'      => $request->plate_number,
            'vehicle_type'      => $request->vehicle_type,
            'fleet_type_code'   => $request->fleet_type_code,
            'capacity_ton'      => $request->capacity_ton,
            'smart_card_number' => $request->smart_card_number,
            'insurance_number'  => $request->insurance_number,
            'insurance_expiry'  => $request->insurance_expiry,
            'is_active'         => true,
            'is_default'        => $isFirst,
        ]);

        return response()->json(['success' => true, 'message' => 'ناوگان ثبت شد', 'data' => $vehicle], 201);
    }

    // ─────────────────────────────────────────────────────────────────
    // 3. Online / Offline  (uses existing LocationController logic)
    // ─────────────────────────────────────────────────────────────────

    /** POST /driver/online */
    public function goOnline(Request $request)
    {
        $request->validate([
            'latitude'  => 'required|numeric',
            'longitude' => 'required|numeric',
            'vehicle_id'=> 'nullable|exists:driver_vehicles,id',
        ]);

        $user = $request->user();
        if ($user->driver_status !== 'VERIFIED') {
            return response()->json(['success' => false, 'message' => 'حساب شما هنوز تایید نشده است'], 403);
        }

        \App\Models\DriverLocation::updateDriverLocation($user->id, [
            'latitude'  => $request->latitude,
            'longitude' => $request->longitude,
            'is_online' => true,
            'vehicle_id'=> $request->vehicle_id,
            'updated_at'=> now(),
        ]);

        return response()->json(['success' => true, 'message' => 'آنلاین شدید']);
    }

    /** POST /driver/offline */
    public function goOffline(Request $request)
    {
        \App\Models\DriverLocation::where('driver_id', $request->user()->id)
            ->update(['is_online' => false]);
        return response()->json(['success' => true, 'message' => 'آفلاین شدید']);
    }

    /** POST /driver/location */
    public function updateLocation(Request $request)
    {
        $request->validate([
            'latitude'  => 'required|numeric|between:-90,90',
            'longitude' => 'required|numeric|between:-180,180',
            'speed'     => 'nullable|numeric|min:0|max:300',
            'bearing'   => 'nullable|numeric|min:0|max:360',
        ]);

        \App\Models\DriverLocation::updateDriverLocation($request->user()->id, [
            'latitude'  => $request->latitude,
            'longitude' => $request->longitude,
            'speed'     => $request->speed,
            'bearing'   => $request->bearing,
            'is_online' => true,
            'updated_at'=> now(),
        ]);

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

    // ─────────────────────────────────────────────────────────────────
    // 4. Available Orders
    // ─────────────────────────────────────────────────────────────────

    /** GET /driver/orders/available */
    public function availableOrders(Request $request)
    {
        $user = $request->user();
        if ($user->driver_status !== 'VERIFIED') {
            return response()->json(['success' => false, 'message' => 'حساب شما هنوز تایید نشده است'], 403);
        }

        $orders = Load::whereNull('driver_id')
            ->where('status', 'pending')
            ->with('requester:id,name,phone')
            ->orderByDesc('created_at')
            ->paginate(20);

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

    // ─────────────────────────────────────────────────────────────────
    // 5. Accept / Reject
    // ─────────────────────────────────────────────────────────────────

    /** POST /driver/orders/{id}/accept */
    public function acceptOrder(Request $request, $id)
    {
        $user = $request->user();

        // Idempotency: if already accepted by THIS driver, return success
        $existing = Load::where('id', $id)->where('driver_id', $user->id)->first();
        if ($existing && $existing->driver_order_status === 'ACCEPTED') {
            return response()->json(['success' => true, 'message' => 'این بار قبلاً قبول شده است', 'data' => $existing]);
        }

        // Pessimistic lock to prevent race condition (two drivers accepting same load)
        $load = DB::transaction(function () use ($id, $user) {
            $load = Load::lockForUpdate()->find($id);

            if (!$load) return null;
            if ($load->driver_id && $load->driver_id !== $user->id) {
                throw new \Exception('این بار قبلاً توسط راننده دیگری پذیرفته شده است');
            }

            $load->update([
                'driver_id'           => $user->id,
                'driver_order_status' => 'ACCEPTED',
                'driver_accepted_at'  => now(),
                'status'              => 'in_progress',
            ]);

            return $load;
        });

        if (!$load) {
            return response()->json(['success' => false, 'message' => 'بار یافت نشد'], 404);
        }

        return response()->json(['success' => true, 'message' => 'بار پذیرفته شد', 'data' => $load]);
    }

    /** POST /driver/orders/{id}/reject */
    public function rejectOrder(Request $request, $id)
    {
        $load = Load::find($id);
        if (!$load) return response()->json(['success' => false, 'message' => 'بار یافت نشد'], 404);

        // Just log rejection - don't block
        return response()->json(['success' => true, 'message' => 'درخواست رد شد']);
    }

    // ─────────────────────────────────────────────────────────────────
    // 6. Order Details
    // ─────────────────────────────────────────────────────────────────

    /** GET /driver/orders/{id} */
    public function getOrder(Request $request, $id)
    {
        $load = Load::where('id', $id)
            ->where('driver_id', $request->user()->id)
            ->with(['requester:id,name,phone', 'vehicle', 'issues'])
            ->firstOrFail();

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

    // ─────────────────────────────────────────────────────────────────
    // 7. State Machine Transitions
    // ─────────────────────────────────────────────────────────────────

    /** POST /driver/orders/{id}/arrived-origin */
    public function arrivedOrigin(Request $request, $id)
    {
        $load = $this->getDriverLoad($request, $id);
        $this->requireStatus($load, ['ACCEPTED']);
        $load->update(['driver_order_status' => 'ARRIVED_ORIGIN', 'arrived_origin_at' => now()]);
        return $this->orderResponse($load, 'رسیدن به مبدا ثبت شد');
    }

    /** POST /driver/orders/{id}/loaded */
    public function markLoaded(Request $request, $id)
    {
        $load = $this->getDriverLoad($request, $id);
        $this->requireStatus($load, ['ARRIVED_ORIGIN']);

        $photoPath = null;
        if ($request->hasFile('cargo_photo')) {
            $photoPath = $request->file('cargo_photo')->store('cargo-photos', 'public');
        }

        $load->update([
            'driver_order_status' => 'LOADED',
            'loaded_at'           => now(),
            'cargo_photo_path'    => $photoPath,
        ]);
        return $this->orderResponse($load, 'بارگیری تایید شد');
    }

    /** POST /driver/orders/{id}/start */
    public function startTrip(Request $request, $id)
    {
        $load = $this->getDriverLoad($request, $id);
        $this->requireStatus($load, ['LOADED']);
        $load->update(['driver_order_status' => 'IN_TRANSIT', 'trip_started_at' => now()]);
        return $this->orderResponse($load, 'سفر آغاز شد');
    }

    /** POST /driver/orders/{id}/pause */
    public function pauseTrip(Request $request, $id)
    {
        $load = $this->getDriverLoad($request, $id);
        $this->requireStatus($load, ['IN_TRANSIT']);
        $load->update(['driver_order_status' => 'PAUSED']);
        return $this->orderResponse($load, 'توقف موقت ثبت شد');
    }

    /** POST /driver/orders/{id}/resume */
    public function resumeTrip(Request $request, $id)
    {
        $load = $this->getDriverLoad($request, $id);
        $this->requireStatus($load, ['PAUSED']);
        $load->update(['driver_order_status' => 'IN_TRANSIT']);
        return $this->orderResponse($load, 'ادامه سفر ثبت شد');
    }

    /** POST /driver/orders/{id}/arrived-destination */
    public function arrivedDestination(Request $request, $id)
    {
        $load = $this->getDriverLoad($request, $id);
        $this->requireStatus($load, ['IN_TRANSIT', 'PAUSED']);
        $load->update(['driver_order_status' => 'ARRIVED_DESTINATION', 'arrived_destination_at' => now()]);
        return $this->orderResponse($load, 'رسیدن به مقصد ثبت شد');
    }

    /** POST /driver/orders/{id}/delivery */
    public function registerDelivery(Request $request, $id)
    {
        $request->validate([
            'receiver_name'       => 'required|string',
            'national_id'         => 'required|string',
            'phone'               => 'required|string',
        ]);

        $load = $this->getDriverLoad($request, $id);
        $this->requireStatus($load, ['ARRIVED_DESTINATION']);

        // Generate OTP for confirmation
        $otp = (string) rand(100000, 999999);

        $load->update([
            'delivery_receiver_name'       => $request->receiver_name,
            'delivery_receiver_national_id'=> $request->national_id,
            'delivery_receiver_phone'      => $request->phone,
            'delivery_otp'                 => Hash::make($otp),
        ]);

        // In production: send OTP via SMS
        return response()->json([
            'success' => true,
            'message' => 'اطلاعات گیرنده ثبت شد. کد تایید ارسال شد',
            'otp'     => $otp, // Only in dev; remove in production
        ]);
    }

    /** POST /driver/orders/{id}/confirm-delivery */
    public function confirmDelivery(Request $request, $id)
    {
        $request->validate(['otp' => 'required|string']);

        $load = $this->getDriverLoad($request, $id);
        $this->requireStatus($load, ['ARRIVED_DESTINATION']);

        if (!$load->delivery_otp || !Hash::check($request->otp, $load->delivery_otp)) {
            return response()->json(['success' => false, 'message' => 'کد تایید نامعتبر است'], 422);
        }

        $load->update([
            'driver_order_status' => 'DELIVERED',
            'delivered_at'        => now(),
            'delivery_confirmed'  => true,
            'status'              => 'delivered',
        ]);

        return $this->orderResponse($load, 'تحویل بار تایید شد ✓');
    }

    // ─────────────────────────────────────────────────────────────────
    // 8. Issue Reporting
    // ─────────────────────────────────────────────────────────────────

    /** POST /driver/orders/{id}/issue */
    public function reportIssue(Request $request, $id)
    {
        $request->validate([
            'issue_type'  => 'required|in:BREAKDOWN,ACCIDENT,DELAY,OTHER',
            'description' => 'nullable|string|max:1000',
        ]);

        $load = $this->getDriverLoad($request, $id);

        $issue = DriverOrderIssue::create([
            'load_id'     => $load->id,
            'driver_id'   => $request->user()->id,
            'issue_type'  => $request->issue_type,
            'description' => $request->description,
        ]);

        return response()->json(['success' => true, 'message' => 'مشکل ثبت شد', 'data' => $issue], 201);
    }

    // ─────────────────────────────────────────────────────────────────
    // 9. Financial
    // ─────────────────────────────────────────────────────────────────

    /** GET /driver/orders/{id}/invoice */
    public function getInvoice(Request $request, $id)
    {
        $load = $this->getDriverLoad($request, $id);
        $load->load('bill');

        return response()->json([
            'success' => true,
            'data' => [
                'freight_amount'       => $load->freight_amount,
                'insurance_amount'     => $load->insurance_amount,
                'tax_amount'           => $load->tax_amount,
                'legal_toll_amount'    => $load->legal_toll_amount,
                'terminal_share_amount'=> $load->terminal_share_amount,
                'final_price'          => $load->final_price,
                'payment_terms'        => $load->payment_terms,
                'bill_number'          => $load->bill?->bill_number,
            ],
        ]);
    }

    /** POST /driver/orders/{id}/settle */
    public function settleOrder(Request $request, $id)
    {
        $load = $this->getDriverLoad($request, $id);
        $this->requireStatus($load, ['DELIVERED']);
        $load->update(['driver_order_status' => 'SETTLED', 'settled_at' => now()]);
        return $this->orderResponse($load, 'تسویه ثبت شد');
    }

    // ─────────────────────────────────────────────────────────────────
    // 10. History
    // ─────────────────────────────────────────────────────────────────

    /** GET /driver/orders/history */
    public function orderHistory(Request $request)
    {
        $orders = Load::where('driver_id', $request->user()->id)
            ->whereNotNull('driver_order_status')
            ->with('bill:id,load_id,bill_number,tracking_code')
            ->orderByDesc('updated_at')
            ->paginate(20);

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

    // ─────────────────────────────────────────────────────────────────
    // Helpers
    // ─────────────────────────────────────────────────────────────────

    private function getDriverLoad(Request $request, $id): Load
    {
        $load = Load::where('id', $id)->where('driver_id', $request->user()->id)->first();
        if (!$load) abort(404, 'بار یافت نشد یا به شما تخصیص نیافته است');
        return $load;
    }

    private function requireStatus(Load $load, array $allowed): void
    {
        if (!in_array($load->driver_order_status, $allowed)) {
            abort(422, 'وضعیت فعلی بار اجازه این عملیات را نمی‌دهد. وضعیت فعلی: ' . $load->driver_order_status);
        }
    }

    private function orderResponse(Load $load, string $message)
    {
        return response()->json(['success' => true, 'message' => $message, 'data' => $load->fresh()]);
    }
}
