<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Vehicle;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class DriverVehicleController extends Controller
{
    /**
     * جلب معلومات سيارة السائق
     */
    public function show()
    {
        try {
            $driver = Auth::user();
            if ($driver->user_type !== 'driver') {
                return response()->json(['success' => false, 'message' => 'غير مصرح'], 403);
            }

            $vehicle = Vehicle::where('driver_id', $driver->id)->first();

            if (!$vehicle) {
                $vehicle = Vehicle::create([
                    'driver_id' => $driver->id,
                    'plate_number' => 'DRV-' . $driver->id . '-' . time(),
                    'brand' => '',
                    'model' => '',
                    'year' => now()->year,
                    'color' => '',
                    'vehicle_type' => 'sedan',
                    'service_type' => 'taxi',
                    'has_ac' => true,
                    'passenger_count' => 4,
                    'is_4wd' => false,
                ]);
            }

            return response()->json([
                'success' => true,
                'data' => $vehicle,
                'message' => 'تم جلب بيانات السيارة',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطأ: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * تحديث معلومات سيارة السائق
     */
    public function update(Request $request)
    {
        try {
            $driver = Auth::user();
            if ($driver->user_type !== 'driver') {
                return response()->json(['success' => false, 'message' => 'غير مصرح'], 403);
            }

            $request->validate([
                'plate_number' => 'nullable|string|max:20',
                'brand' => 'nullable|string|max:100',
                'model' => 'nullable|string|max:100',
                'year' => 'nullable|integer|min:1990|max:' . (now()->year + 1),
                'color' => 'nullable|string|max:50',
                'vehicle_type' => 'nullable|string|in:sedan,suv,hatchback,pickup,saloon,van,other',
                'service_type' => 'nullable|string|in:taxi,private,saloon',
                'has_ac' => 'nullable|boolean',
                'passenger_count' => 'nullable|integer|min:1|max:15',
                'is_4wd' => 'nullable|boolean',
                'image' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
            ]);

            $vehicle = Vehicle::where('driver_id', $driver->id)->first();

            if (!$vehicle) {
                $vehicle = new Vehicle(['driver_id' => $driver->id]);
            }

            $data = $request->only([
                'plate_number', 'brand', 'model', 'year', 'color',
                'vehicle_type', 'service_type', 'has_ac', 'passenger_count', 'is_4wd',
            ]);

            if ($request->hasFile('image')) {
                if ($vehicle->image) {
                    Storage::disk('public')->delete($vehicle->image);
                }
                $path = $request->file('image')->store('vehicles', 'public');
                $data['image'] = $path;
            }

            $vehicle->fill($data);
            $vehicle->save();

            return response()->json([
                'success' => true,
                'data' => $vehicle->fresh(),
                'message' => 'تم تحديث بيانات السيارة بنجاح',
            ]);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطأ في التحقق',
                'errors' => $e->errors(),
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطأ: ' . $e->getMessage(),
            ], 500);
        }
    }
}
