<?php

namespace App\Http\Livewire\Sale;

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

class ProductSale extends Component
{
    use WithPagination;
    public $sale, $search, $amount;

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

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

    public function render()
    {
        // Lista de los Ids de los productos usados
        $uses = DB::table('product_sale')
            ->where('sale_id', $this->sale->id)
            ->pluck('product_id')
            ->all();
        // Lista de los productos sin usar
        $products = Product::where(
            'description_product',
            'like',
            '%' . Str::lower($this->search) . '%'
        )
            ->where('status_product', true)
            ->whereNotIn('id', $uses)
            ->paginate(3);

        // Lista de los productos usados
        $added = DB::table('product_sale')
            ->join('sales', 'sales.id', '=', 'product_sale.sale_id')
            ->join('products', 'products.id', '=', 'product_sale.product_id')
            ->where('sale_id', $this->sale->id)
            ->select('product_sale.*', 'products.description_product')
            ->paginate(5);
        return view('livewire.sale.product-sale', compact('products', 'added'));
    }


    public function addProduct(Product $product)
    {
        if ($this->amount > 0) {
            // Verificar en stock
            if ($product->stock_product < $this->amount) {
                $this->emit('error', [
                    'title' => 'No hay suficientes productos en STOCK',
                    'subtitile' =>  'Revisar el stock del producto',
                    'footer' => 'LISAC Motors'
                ]);
            } else {
                // Reducir stock
                $product->update([
                    'stock_product' => ($product->stock_product - $this->amount)
                ]);
                // Agregar en Product Sale
                $this->sale
                    ->Product()
                    ->attach($product, [
                        'price_product_sale' => $product->sell_product,
                        'amount_product_sale' => $this->amount,
                        'price_product_buy' => $product->buy_product
                    ]);
                $this->amount = null;
                $this->emitTo('sale.show-sale', 'render');
                $this->emit('notify', 'Producto Agregado');
            }
        } else {
            $this->emit('error', [
                'title' => ' No olvides de llenar la cantidad del producto requerido',
                'subtitile' =>  'Esto es importante para agregar la venta',
                'footer' => 'LISAC Motors'
            ]);
        }
    }

    public function quitProduct($id)
    {
        // Eliminar el elemento en la tabla
        $product_sale = DB::table('product_sale')->where('id', $id)->first();
        $product = Product::find($product_sale->product_id);
        //  Aumentar stock
        $product->update([
            'stock_product' => $product_sale->amount_product_sale + $product->stock_product
        ]);
        // Eliminar
        DB::table('product_sale')->delete($id);
        $this->emitTo('sale.show-sale', 'render');
        $this->emit('notify', 'Se eliminó el producto de la lista');
    }
}
