<?php

namespace App\Livewire\Client;

use App\Helpers\Utility;
use App\Mail\NotificationMail;
use App\Models\Address;
use App\Models\AddressPurchase;
use App\Models\CFDICatalog;
use App\Models\Invoice;
use App\Models\ProductPricePurchase;
use App\Models\User;
use App\Rules\RFCRule;
use Illuminate\Support\Facades\DB;
use Livewire\Component;

use function Livewire\store;

class Summary extends Component
{
    public $purchase, $addresses, $address_id, $clothes = 0, $products = [], $total = 0, $invoice = 0, $cfdi_catalogs;
    public $full_name, $rfc, $email, $phone, $cfdi_catalogs_id, $last_invoice, $modalOpen = false;

    public function render()
    {
        return view('livewire.client.summary');
    }

    public function mount()
    {
        $search = Utility::searchPurchase();
        $this->purchase = $search['purchase'];
        // info($this->purchase->product_price_purchases);
        if (!is_null($this->purchase)) {
            $this->cfdi_catalogs = CFDICatalog::all();
            $this->cfdi_catalogs_id = $this->cfdi_catalogs->first()->id;
            $invoice = Invoice::join('purchases', 'purchases.id', '=', 'invoices.purchase_id')
                ->where([
                    ['purchases.user_id', '=', auth()->user()->id],
                    ['purchases.invoice', '=', 1]
                ])
                ->orderBy('invoices.id', 'DESC')->select('invoices.*')->first();
            // info($invoice);
            if (!is_null($invoice)) {
                $this->last_invoice = $invoice;
                $this->full_name = $invoice->full_name;
                $this->rfc = $invoice->rfc;
                $this->email = $invoice->email;
                $this->phone = $invoice->phone;
                $this->cfdi_catalogs_id = $invoice->cfdi_catalogs_id;
            }
            // if ($this->purchase->updated == 1 && !auth()->check()) {
            //     $this->first_name = $this->purchase->user->person->first_name;
            //     $this->second_name = $this->purchase->user->person->second_name;
            //     $this->first_surname = $this->purchase->user->person->first_surname;
            //     $this->second_surname = $this->purchase->user->person->second_surname;
            //     $this->phone = $this->purchase->user->person->phone;
            //     $this->email = $this->purchase->user->email;
            //     $this->main_street = $this->purchase->address_purchase->address->main_street;
            //     $this->between_streets = $this->purchase->address_purchase->address->between_streets;
            //     $this->zip_code = $this->purchase->address_purchase->address->zip_code;
            //     $this->reference = $this->purchase->address_purchase->address->reference;
            //     $this->neighborhood = $this->purchase->address_purchase->address->neighborhood;
            // }
            // $this->shipping = ContactDetails::find(8)->resource;

            $this->listProducts();
            $this->listAddress();
            $this->address_id = count($this->addresses) == 0 ? null : $this->addresses->first()->id;
            // $this->selectAddress();
        }
    }

    public function listProducts()
    {
        $this->total = 0;
        Utility::validateProductStatus(is_null($this->purchase) ? [] : $this->purchase->product_price_purchases);
        $this->products = is_null($this->purchase) ? [] : ProductPricePurchase::where('purchase_id', $this->purchase->id)->get();
        // info($this->products);

        foreach ($this->products as $cart) {
            // info($cart->product_price->product->status_id);
            if ($cart->product_price->product->status_id == 5) {
                $cart->delete();
            }
            // info($cart->product_price->price);
            $this->total += $cart->product_price->price * $cart->quantity;
        }
        // $this->total = $this->clothes + $this->shipping;
    }

    public function editInventory($product_price_purchase_id, $option = null)
    {
        try {
            // info($product_price_purchase_id);
            // info($option);
            $cart = ProductPricePurchase::where('id', $product_price_purchase_id)->first();
            // info($cart->clothing_sizes_product->clothingSize->id);
            switch ($option) {
                case 'minus':
                    $quantity = $cart->quantity - 1;
                    if ($quantity != 0) {
                        $cart->update(['quantity' => $quantity]);
                    } else {
                        $cart->delete();
                    }
                    break;
                case 'plus':
                    // info($cart);
                    $inventory = $cart->product_price->product->quantity();
                    // info($inventory);
                    $quantity = $cart->quantity + 1;
                    if ($quantity > 5 || $quantity >= $inventory) {
                        return $this->addError('product-' . $cart->id, 'El máximo permitido por pedido es de 5 productos.');
                    }
                    $cart->update(['quantity' => $quantity]);

                    break;
                case 'delete':
                    $cart->delete();
                    break;
                default:
                    # code...
                    break;
            }
        } catch (\Throwable $th) {
            //throw $th;
            info($th);
        }

        $this->listProducts();
    }

    public function listAddress()
    {
        $this->addresses = Address::where([['user_id', '=', $this->purchase->user_id], ['status_id', '=', '22']])
            ->select('*')
            ->get();
    }

    public function checkInventory()
    {
        $validate = 0;
        // info($this->products);
        foreach ($this->products as $product) {
            $inventory = $product->product_price->product->quantity();
            if ($product->quantity > $inventory) {
                $this->addError('product-' . $product->id, 'No hay inventario suficiente');
                $validate = 1;
            }
        }
        return $validate;
    }

    public function openModal(){
        $this->modalOpen = true;
    }
    public function closeModal()
    {
        $this->modalOpen = false;
    }

    public function save()
    {
        $this->modalOpen = false;
        $this->validate([
            'address_id'    => 'required',
            'invoice'       => 'required|integer|min:0|max:1',
            'full_name'     => $this->invoice == 1 ? 'required|string|max:200' : '',
            'rfc'           => $this->invoice == 1 ? ['required', 'string', 'max:18', new RFCRule()] : '',
            'email'         => $this->invoice == 1 ? 'required|email' : '',
            'phone'         => $this->invoice == 1 ? 'required|integer|regex:/^\d{10}$/' : '',
            'cfdi_catalogs_id' => $this->invoice == 1 ? 'required|integer|exists:cfdi_catalogs,id' : '',
            // 'between_streets' => 'required|string|max:200',
            // 'zip_code' => ['required', 'integer', new ZipRule()],
            // 'reference' => 'required|string|max:200',
            // 'neighborhood' => 'required|string|max:200',
        ]);
        $validate = $this->checkInventory();
        if ($validate == 1) return;
        // return '';
        DB::beginTransaction();
        try {

            $this->purchase->update([
                'status_id'     => 12,
                'created_at'    => now(),
                'invoice'       => $this->invoice,
            ]);

            AddressPurchase::create([
                'address_id' => $this->address_id,
                'purchase_id' => $this->purchase->id,
            ]);

            if ($this->invoice == 1) {
                Invoice::create([
                    'full_name'     => $this->full_name,
                    'rfc'           => $this->rfc,
                    'email'         => $this->email,
                    'phone'         => $this->phone,
                    'cfdi_catalogs_id' => $this->cfdi_catalogs_id,
                    'purchase_id'   => $this->purchase->id,
                ]);
            }

            $adminOne = User::where('id', 1)->first();
            $adminTwo = User::where('id', 2)->first();
            $url = route('purchases.index');
            $total = '$'.number_format($this->total,2);
            $date = date('d-m-Y h:i A',strtotime($this->purchase->created_at));
            $subject = 'Nuevo Pedido Realizado.';
            $textOne = "
                Hola {$adminOne->person->first_name} {$adminOne->person->first_surname},<br><br>

                Le notificamos que el cliente <strong>{$this->purchase->user->person->first_name} {$this->purchase->user->person->first_surname}</strong> ha realizado un nuevo pedido en el sistema.<br>
                Por favor, ingrese al panel de administración para revisarlo y dar seguimiento oportuno.<br><br>

                📌 <strong>Detalles básicos del pedido:</strong><br>
                - Número de pedido: <strong>{$this->purchase->id}</strong><br>
                - Fecha del pedido: <strong>{$date}</strong><br>
                - Total: <strong>{$total}</strong><br><br>

                Puede consultarlo directamente en el sistema accediendo al siguiente enlace:<br>
                👉 <a href='{$url}' target='_blank'>Ver pedido</a><br><br>

                Gracias por su atención.<br><br>
            ";

            $textTwo = "
                Hola {$adminTwo->person->first_name} {$adminTwo->person->first_surname},<br><br>

                Le notificamos que el cliente <strong>{$this->purchase->user->person->first_name} {$this->purchase->user->person->first_surname}</strong> ha realizado un nuevo pedido en el sistema.<br>
                Por favor, ingrese al panel de administración para revisarlo y dar seguimiento oportuno.<br><br>

                📌 <strong>Detalles básicos del pedido:</strong><br>
                - Número de pedido: <strong>{$this->purchase->id}</strong><br>
                - Fecha del pedido: <strong>{$date}</strong><br>
                - Total: <strong>{$total}</strong><br><br>

                Puede consultarlo directamente en el sistema accediendo al siguiente enlace:<br>
                👉 <a href='{$url}' target='_blank'>Ver pedido</a><br><br>

                Gracias por su atención.<br><br>
            ";

            Utility::sendEmail($adminOne->email, new NotificationMail($adminOne, $subject, $textOne));
            Utility::sendEmail($adminTwo->email, new NotificationMail($adminTwo, $subject, $textTwo));

            DB::commit();
            return redirect()->route('compras.index');
            // return $this->addError('product-'.$cart->id, 'No hay inventario suficiente');
        } catch (\Throwable $th) {
            info($th);
            DB::rollBack();
        }
    }
}
