<?php

namespace App\Livewire\Forms;

use App\Models\MaintenanceRecord;
use Livewire\Form;

class MaintenanceForm extends Form
{
    public ?MaintenanceRecord $maintenanceRecord = null;

    public $vehicle_id = null;

    public $maintenance_type_id = null;

    public $description = '';

    public $date = '';

    public $cost = null;

    public $performed_by = '';

    public $notes = '';

    public $next_service_date = null;

    public $next_service_odometer = null;

    public $odometer_reading = null;

    public function rules()
    {
        return [
            'vehicle_id' => 'required|exists:vehicles,id',
            'maintenance_type_id' => 'required|exists:maintenance_types,id',
            'description' => 'required|string|max:1000',
            'date' => 'required|date',
            'cost' => 'nullable|numeric|min:0',
            'performed_by' => 'nullable|string|max:255',
            'notes' => 'nullable|string|max:1000',
            'next_service_date' => 'nullable|date|after_or_equal:date',
            'next_service_odometer' => 'nullable|integer|min:0',
            'odometer_reading' => 'nullable|integer|min:0',
        ];
    }

    public function setMaintenanceRecord(MaintenanceRecord $maintenanceRecord)
    {
        $this->maintenanceRecord = $maintenanceRecord;
        $this->vehicle_id = $maintenanceRecord->vehicle_id;
        $this->maintenance_type_id = $maintenanceRecord->maintenance_type_id;
        $this->description = $maintenanceRecord->description;
        $this->date = $maintenanceRecord->date->format('Y-m-d');
        $this->cost = $maintenanceRecord->cost;
        $this->performed_by = $maintenanceRecord->performed_by;
        $this->notes = $maintenanceRecord->notes;
        $this->next_service_date = $maintenanceRecord->next_service_date?->format('Y-m-d');
        $this->next_service_odometer = $maintenanceRecord->next_service_odometer;
        $this->odometer_reading = $maintenanceRecord->odometer_reading;
    }

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

        MaintenanceRecord::create($this->all());
        $this->reset();
    }

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

        $this->maintenanceRecord->update($this->all());
        $this->reset();
    }

    public function resetForm()
    {
        $this->reset();
    }
}
