<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Api\ApiController;
use App\Models\Bus;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class VehicleController extends ApiController
{
    /**
     * Display a listing of vehicles with pagination and search
     */
    public function index(Request $request)
    {
        $perPage = $request->get('per_page', 15);
        $search = $request->get('search');
        $sortBy = $request->get('sort_by', 'created_at');
        $sortOrder = $request->get('sort_order', 'desc');

        $query = Bus::with(['school', 'driver', 'route']);

        // Apply search
        if ($search) {
            $query->where(function($q) use ($search) {
                $q->where('vehicle_number', 'like', "%{$search}%")
                  ->orWhere('vehicle_model', 'like', "%{$search}%")
                  ->orWhere('driver_name', 'like', "%{$search}%");
            });
        }

        // Apply filters
        if ($request->has('school_id') && $request->school_id) {
            $query->where('school_id', $request->school_id);
        }

        if ($request->has('is_active')) {
            $query->where('is_active', $request->boolean('is_active'));
        }

        // Apply sorting
        $query = $this->applySorting($query, $sortBy, $sortOrder);

        return $this->paginatedResponse($query, $perPage);
    }

    /**
     * Store a newly created vehicle
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'school_id' => 'required|exists:schools,id',
            'vehicle_number' => 'required|string|unique:buses,vehicle_number',
            'vehicle_model' => 'nullable|string',
            'capacity' => 'required|integer|min:1',
            'driver_name' => 'nullable|string',
            'driver_phone' => 'nullable|string',
            'driver_license' => 'nullable|string',
            'insurance_number' => 'nullable|string',
            'insurance_expiry' => 'nullable|date',
            'fitness_expiry' => 'nullable|date',
            'is_active' => 'boolean',
        ]);

        if ($validator->fails()) {
            return $this->errorResponse('Validation failed', 422, $validator->errors());
        }

        $vehicle = Bus::create($request->all());

        return $this->successResponse(
            $vehicle->load('school'),
            'Vehicle created successfully',
            201
        );
    }

    /**
     * Display the specified vehicle
     */
    public function show($id)
    {
        $vehicle = Bus::with(['school', 'route', 'assignments'])->find($id);

        if (!$vehicle) {
            return $this->errorResponse('Vehicle not found', 404);
        }

        return $this->successResponse($vehicle);
    }

    /**
     * Update the specified vehicle
     */
    public function update(Request $request, $id)
    {
        $vehicle = Bus::find($id);

        if (!$vehicle) {
            return $this->errorResponse('Vehicle not found', 404);
        }

        $validator = Validator::make($request->all(), [
            'school_id' => 'sometimes|exists:schools,id',
            'vehicle_number' => 'sometimes|string|unique:buses,vehicle_number,' . $id,
            'vehicle_model' => 'nullable|string',
            'capacity' => 'sometimes|integer|min:1',
            'driver_name' => 'nullable|string',
            'driver_phone' => 'nullable|string',
            'is_active' => 'boolean',
        ]);

        if ($validator->fails()) {
            return $this->errorResponse('Validation failed', 422, $validator->errors());
        }

        $vehicle->update($request->all());

        return $this->successResponse(
            $vehicle->load('school'),
            'Vehicle updated successfully'
        );
    }

    /**
     * Remove the specified vehicle
     */
    public function destroy($id)
    {
        $vehicle = Bus::find($id);

        if (!$vehicle) {
            return $this->errorResponse('Vehicle not found', 404);
        }

        $vehicle->delete();

        return $this->successResponse(null, 'Vehicle deleted successfully');
    }
}
