<?php

namespace App\Livewire\Vehicles;

use App\Models\Vehicle;
use App\Models\Customer;
use Livewire\Component;
use Livewire\WithPagination;

class Index extends Component
{
    use WithPagination;

    public $search = '';
    public $customer_id = '';
    public $make = '';
    public $status = '';
    public $sortBy = 'created_at';
    public $sortDirection = 'desc';

    protected $queryString = [
        'search' => ['except' => ''],
        'customer_id' => ['except' => ''],
        'make' => ['except' => ''],
        'status' => ['except' => ''],
        'sortBy' => ['except' => 'created_at'],
        'sortDirection' => ['except' => 'desc'],
    ];

    public function updatingSearch()
    {
        $this->resetPage();
    }

    public function updatingCustomerId()
    {
        $this->resetPage();
    }

    public function updatingMake()
    {
        $this->resetPage();
    }

    public function updatingStatus()
    {
        $this->resetPage();
    }

    public function sortBy($field)
    {
        if ($this->sortBy === $field) {
            $this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            $this->sortBy = $field;
            $this->sortDirection = 'asc';
        }
    }

    public function deleteVehicle($vehicleId)
    {
        $vehicle = Vehicle::findOrFail($vehicleId);
        
        // Check if vehicle has any service orders
        if ($vehicle->serviceOrders()->count() > 0) {
            session()->flash('error', 'Cannot delete vehicle with existing service orders. Please complete or cancel them first.');
            return;
        }
        
        $vehicleName = $vehicle->display_name;
        $vehicle->delete();
        
        session()->flash('success', "Vehicle {$vehicleName} has been deleted successfully.");
    }

    public function render()
    {
        $vehicles = Vehicle::query()
            ->with(['customer'])
            ->when($this->search, function ($query) {
                $query->where(function ($q) {
                    $q->where('make', 'like', '%' . $this->search . '%')
                      ->orWhere('model', 'like', '%' . $this->search . '%')
                      ->orWhere('year', 'like', '%' . $this->search . '%')
                      ->orWhere('vin', 'like', '%' . $this->search . '%')
                      ->orWhere('license_plate', 'like', '%' . $this->search . '%')
                      ->orWhereHas('customer', function ($customerQuery) {
                          $customerQuery->where('first_name', 'like', '%' . $this->search . '%')
                                      ->orWhere('last_name', 'like', '%' . $this->search . '%');
                      });
                });
            })
            ->when($this->customer_id, function ($query) {
                $query->where('customer_id', $this->customer_id);
            })
            ->when($this->make, function ($query) {
                $query->where('make', $this->make);
            })
            ->when($this->status, function ($query) {
                $query->where('status', $this->status);
            })
            ->orderBy($this->sortBy, $this->sortDirection)
            ->paginate(15);

        $customers = Customer::orderBy('first_name')->get();
        $makes = Vehicle::distinct()->orderBy('make')->pluck('make')->filter();

        return view('livewire.vehicles.index', [
            'vehicles' => $vehicles,
            'customers' => $customers,
            'makes' => $makes,
        ]);
    }
}
