<?php

namespace App\Http\Livewire\Sale;

use App\Models\BankAccount;
use App\Models\Car;
use App\Models\Client;
use App\Models\Sale;
use Livewire\Component;
use Illuminate\Support\Str;

class CreateSale extends Component
{
    // Car
    public $search_car, $car, $car_property;
    // Client
    public $search_client, $client, $client_name;

    public $km, $observation, $condition_id = 1, $bank_account_id;

    protected $rules = [
        'car' => 'required',
        'client' => 'required',
        'bank_account_id' => 'required'
    ];

    protected $messages = [
        'car.required' => 'El vehículo no puede estar vacio',
        'client.required' => 'El conductor no puede estar vacio',
        'bank_account_id.required' => 'El método de pago no puede estar vacio'
    ];

    public function render()
    {
        $cars = Car::with(['Client'])->orWhere('plate', 'like', '%' . Str::lower($this->search_car) . '%')
            ->orWhereHas('Client', function ($query) {
                $query->where('dni', 'like', '%' . Str::lower($this->search_car) . '%');
            })
            ->orWhereHas('Client', function ($query) {
                $query->where('names', 'like', '%' . Str::lower($this->search_car) . '%');
            })
            ->orderBy('id', 'asc')
            ->paginate(3);

        $clients = Client::where('dni', 'like', '%' . Str::lower($this->search_client) . '%')
            ->orWhere('names', 'like', '%' . Str::lower($this->search_client) . '%')
            ->orderBy('id', 'asc')
            ->paginate(3);
        $banks = BankAccount::orderBy('id', 'asc')
            ->where('open', '1')
            ->pluck('name', 'id');
        return view('livewire.sale.create-sale', compact('cars', 'clients', 'banks'));
    }

    public function selectCar($car)
    {
        $this->car = $car;
        $this->car_property = $car['plate'] . ' | ' . $car['client']['names'];
        $this->emit('notify', 'Vehículo Seleccionado');
    }
    public function selectClient($client)
    {
        $this->client = $client;
        $this->client_name = $client['dni'] . ' | ' . $client['names'];
        $this->emit('notify', 'Conductor Seleccionado');
    }

    public function save()
    {
        $this->validate();
        $sale = Sale::create([
            'car_id' => $this->car['id'],
            'client_id' => $this->client['id'],
            'km' => Str::lower($this->km),
            'observation_sale' => Str::lower($this->observation),
            'condition_id' => $this->condition_id,
            'bank_account_id' => $this->bank_account_id
        ]);
        $this->emit('notify', 'Venta Agregada');
        return redirect()->route('sale.show', $sale);
    }
}
