<?php

namespace App\Http\Livewire\Sale;

use App\Models\Sale;
use App\Models\Service;
use Illuminate\Support\Facades\DB;
use Livewire\Component;
use Livewire\WithPagination;
use Illuminate\Support\Str;

class ServiceSale extends Component
{
    use WithPagination;
    public $sale, $search, $price;

    public function mount(Sale $sale)
    {
        $this->sale = $sale;
    }

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

    public function render()
    {
        $uses = DB::table('sale_service')
            ->where('sale_id', $this->sale->id)
            ->pluck('service_id')
            ->all();
        $services = Service::where(
            'description_service',
            'like',
            '%' . Str::lower($this->search) . '%'
        )
            ->where('status_service', true)
            ->whereNotIn('id', $uses)
            ->paginate(3);
        // Servicios Agregados
        $added = DB::table('sale_service')
            ->join('sales', 'sales.id', '=', 'sale_service.sale_id')
            ->join('services', 'services.id', '=', 'sale_service.service_id')
            ->where('sale_id', $this->sale->id)
            ->select('sale_service.*', 'services.description_service')
            ->paginate(5);

        return view('livewire.sale.service-sale', compact('services', 'added'));
    }

    public function addService(Service $service)
    {
        if ($this->price > 0) {
            $this->sale
                ->Service()
                ->attach($service, ['price_sale_service' => $this->price]);
            $this->emitTo('sale.show-sale', 'render');
            $this->emit('notify', 'Servicio Agregado');
        } else {
            $this->emit('error', [
                'title' => ' No olvides ingresar el precio del servicio',
                'subtitile' =>  'Esto es importante para agregar la venta',
                'footer' => 'LISAC Motors'
            ]);
        }
    }

    public function quitService($id)
    {
        DB::table('sale_service')->delete($id);
        $this->emitTo('sale.show-sale', 'render');
        $this->emit('notify', 'SE QUITÓ EL SERVICIO DE LA LISTA');
    }
}
