<?php

namespace App\Livewire\Dashboard;

use App\Helpers\Utility;
use App\Models\Person;
use App\Models\Product as ModelsProduct;
use App\Models\ProductPricePurchase;
use App\Models\Purchase;
use App\Models\User;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Livewire\Component;

class Product extends Component
{
    public $product, $products, $alert = 0, $inventory, $quantity = 1, $success;

    public function render()
    {
        return view('livewire.dashboard.product');
    }

    public function mount()
    {
        // $this->clothing_sizes_products = $this->product->clothingSizesProducts->where('status_id',8);
        // info($this->clothing_sizes_products);
        // $this->size = $this->clothing_sizes_products->first()->id;
        $this->quantity = 1;
        $this->chargeQuantity();

        $this->products = ModelsProduct::where([
            ['category_id', '=', $this->product->category_id],
            ['id', '!=', $this->product->id],
            ['status_id', '=', 4],
        ])->get();
    }

    public function chargeQuantity()
    {
        $this->alert = 0;
        // info($this->size);
        $this->inventory = $this->product->quantity();
        // info($this->inventory);
        // info('inventory');
        // info($this->inventory);
        if ($this->inventory < $this->quantity) $this->quantity = $this->inventory;
    }

    public function save()
    {
        if (!auth()->check()) {
            session()->flash('server', 'Inicia Sesión para Agregar Productos a tu Carrito.');
            return redirect()->route('products');
        }

        $this->resetErrorBag();

        try {
            // info($this->quantity);
            if ($this->quantity < 1) return $this->addError('quantity', 'Debe de elegir al menos 1 elemento del producto.');
            DB::beginTransaction();

            $search = Utility::searchPurchase();
            $purchase = $search['purchase'];
            // $ip = $search['ip'];
            // $arpScan = $search['mac'];
            // info($search);
            // info($purchase);
            // if (is_null($purchase)) {
            //     if (!auth()->check()) {
            //         // info('guardar');
            //         // $employee = Person::create([
            //         //     'first_name' => Str::random(10),
            //         //     // 'second_name' => $this->second_name,
            //         //     'first_surname' => Str::random(10),
            //         //     // 'second_surname' => $this->second_surname,
            //         //     // 'phone' => $this->phone,
            //         //     // 'birth_date' => $this->birth_date,
            //         // ]);

            //         $password = Str::random(10);
            //         $user = User::create([
            //             'email'     => time().'-'.Str::random(10).'@test.com',
            //             'password'  => Hash::make($password),
            //             'status_id' => 2,
            //             'role_id'   => 3,
            //             'person_id' => $employee->id,
            //         ]);
            //     }

            //     $purchase = Purchase::create([
            //         // 'home_delivery' => 1,
            //         // 'invoice'       => 0,
            //         'user_id'       => auth()->check() ? auth()->user()->id : $user->id,
            //         'status_id'     => 19,
            //         // 'token'         => (string) Str::uuid(),
            //         // 'ip'            => $ip,
            //         // 'mac'           => $arpScan,
            //     ]);
            // }
            $product_price_purchase = ProductPricePurchase::where([
                ['product_price_id', '=', $this->product->price->id],
                // ['clothing_sizes_product_id','=',$this->size],
                ['purchase_id', '=', $purchase->id]
            ])->first();


            if (is_null($product_price_purchase)) {
                ProductPricePurchase::create([
                    'quantity' => $this->quantity,
                    'purchase_id' => $purchase->id,
                    'product_price_id' => $this->product->price->id,
                    // 'clothing_sizes_product_id' => $this->size,
                ]);
            } else {
                // info($this->quantity);
                // info($product_price_purchase->quantity);
                $shopping_cart = is_null($product_price_purchase) ? $this->quantity : $product_price_purchase->quantity + $this->quantity;
                if ($shopping_cart > $this->inventory) return $this->dispatch('error', message: 'No hay inventario suficiente, revise su carrito de compras.');

                $shopping_cart = $product_price_purchase->quantity + $this->quantity;
                if ($shopping_cart > 5) return $this->dispatch('error', message: 'Tienes ' . $product_price_purchase->quantity . ' productos en tu inventario. El máximo permitido por pedido es de 5 productos.');

                $quantity = $product_price_purchase->quantity;
                $product_price_purchase->update(['quantity' => $quantity + $this->quantity]);
            }
            DB::commit();
            $this->dispatch('check-cart');
            $this->dispatch('success', message: 'El producto se añadió correctamente a tu pedido.');
        } catch (\Throwable $th) {
            DB::rollback();
            info($th);
        }
        // info($this->size);
        // info($this->product);
        // info($this->product->price);
    }
}
