<?php

namespace App\Livewire\Trip;

use App\Models\Trip;
use App\Models\Employee; // Added
use App\Models\Vehicle; // Added
use Livewire\Component;
use Livewire\WithPagination;

class Index extends Component
{
    use WithPagination;

    // Removed: protected $layout = 'layouts.app';

    public $search = '';
    public $sortField = 'id';
    public $sortDirection = 'desc';
    public $perPage = 10;

    // Filters
    public $filter_driver_id = '';
    public $filter_date = '';

    // Form properties
    
    public Trip $trip;
    public $driver_id;
    public $tractor_id;
    public $trailer_id;
    public $start_date;
    public $end_date;
    public $start_odometer_tractor;
    public $end_odometer_tractor;
    public $origin;
    public $destination;
    public $status = 'pending';
    public $notes;

    public $employees;
    public $tractors;
    public $trailers;
    public $isEditing = false; // To differentiate create/edit

    protected $queryString = ['search', 'sortField', 'sortDirection'];

    protected $rules = [
        'driver_id' => 'required|exists:employees,id',
        'tractor_id' => 'required|exists:vehicles,id',
        'trailer_id' => 'nullable|exists:vehicles,id',
        'start_date' => 'required|date',
        'end_date' => 'nullable|date|after_or_equal:start_date',
        'start_odometer_tractor' => 'required|integer|min:0',
        'end_odometer_tractor' => 'nullable|integer|min:0|gte:start_odometer_tractor',
        'origin' => 'required|string|max:255',
        'destination' => 'required|string|max:255',
        'status' => 'required|string|in:pending,in_progress,completed,cancelled',
        'notes' => 'nullable|string|max:1000',
    ];

    public function mount()
    {
        $this->employees = Employee::all();
        $this->tractors = Vehicle::whereHas('vehicleType', function ($query) {
            $query->where('name', 'Tractor Truck');
        })->get();
        $this->trailers = Vehicle::whereHas('vehicleType', function ($query) {
            $query->where('name', 'Trailer');
        })->get();
    }

    public function create()
    {
        $this->resetForm();
        $this->isEditing = false;
        $this->dispatch('open-modal');
    }

    public function edit(Trip $trip)
    {
        $this->trip = $trip;
        $this->driver_id = $this->trip->driver_id;
        $this->tractor_id = $this->trip->tractor_id;
        $this->trailer_id = $this->trip->trailer_id;
        $this->start_date = $this->trip->start_date->format('Y-m-d\TH:i');
        $this->end_date = $this->trip->end_date ? $this->trip->end_date->format('Y-m-d\TH:i') : null;
        $this->start_odometer_tractor = $this->trip->start_odometer_tractor;
        $this->end_odometer_tractor = $this->trip->end_odometer_tractor;
        $this->origin = $this->trip->origin;
        $this->destination = $this->trip->destination;
        $this->status = $this->trip->status;
        $this->notes = $this->trip->notes;
        $this->isEditing = true;
        $this->dispatch('open-modal');
    }

    public function save()
    {
        $this->validate();

        $this->trip->fill([
            'driver_id' => $this->driver_id,
            'tractor_id' => $this->tractor_id,
            'trailer_id' => $this->trailer_id,
            'start_date' => $this->start_date,
            'end_date' => $this->end_date,
            'start_odometer_tractor' => $this->start_odometer_tractor,
            'end_odometer_tractor' => $this->end_odometer_tractor,
            'origin' => $this->origin,
            'destination' => $this->destination,
            'status' => $this->status,
            'notes' => $this->notes,
        ])->save();

        // Update vehicle odometer if trip is completed
        if ($this->status === 'completed' && $this->end_odometer_tractor) {
            $tractor = Vehicle::find($this->tractor_id);
            if ($tractor) {
                $tractor->current_odometer = $this->end_odometer_tractor;
                $tractor->save();
            }
        }

        session()->flash('message', 'Trip saved successfully.');
        $this->dispatch('close-modal');
    }

    public function resetForm()
    {
        $this->trip = new Trip();
        $this->driver_id = null;
        $this->tractor_id = null;
        $this->trailer_id = null;
        $this->start_date = null;
        $this->end_date = null;
        $this->start_odometer_tractor = null;
        $this->end_odometer_tractor = null;
        $this->origin = null;
        $this->destination = null;
        $this->status = 'pending';
        $this->notes = null;
        $this->resetValidation();
    }

    public function closeModal()
    {
        $this->dispatch('close-modal');
        $this->resetForm();
    }

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

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

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

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

    public function delete(Trip $trip)
    {
        $trip->delete();
        session()->flash('message', 'Trip deleted successfully.');
    }

    public function render()
    {
        $trips = Trip::with(['driver', 'tractor', 'trailer', 'creator', 'editor'])
            ->where(function ($query) {
                $query->where('origin', 'like', '%' . $this->search . '%')
                    ->orWhere('destination', 'like', '%' . $this->search . '%')
                    ->orWhereHas('driver', function ($query) {
                        $query->where('first_name', 'like', '%' . $this->search . '%')
                            ->orWhere('last_name', 'like', '%' . $this->search . '%');
                    })
                    ->orWhereHas('tractor', function ($query) {
                        $query->where('plate_number', 'like', '%' . $this->search . '%');
                    });
            })
            ->when($this->filter_driver_id, function ($query) {
                $query->where('driver_id', $this->filter_driver_id);
            })
            ->when($this->filter_date, function ($query) {
                $query->whereDate('start_date', $this->filter_date);
            })
            ->orderBy($this->sortField, $this->sortDirection)
            ->paginate($this->perPage);

        return view('livewire.trip.index', [
            'trips' => $trips,
        ]);
    }
}
