<?php

namespace App\Livewire\Admin\Purchase;

use App\Helpers\Utility;
use App\Mail\NotificationMail;
use App\Models\ContactDetails;
use App\Models\Purchase;
use App\Models\Status;
use App\Rules\StatusRule;
use Illuminate\Support\Facades\DB;
use Livewire\Component;

class Edit extends Component
{
    public $purchase, $status, $status_id, $guide_one, $guide_two, $clothes, $products, $total = 0, $shipping, $date, $payment_date;

    public function render()
    {
        return view('livewire.admin.purchase.edit');
    }

    public function mount()
    {
        $this->status = Status::orderBy('order','ASC')->where('status_type_id', 5)
        // ->whereIn('id',[10,11,12,13,14,17,18,24])
        ->whereNotIn('id', [19,13,14])
        ->get();
        $this->status_id = $this->purchase->status_id;
        $this->guide_one = $this->purchase->guide_one;
        $this->guide_two = $this->purchase->guide_two;
        $this->shipping = $this->purchase->shipping;
        $this->payment_date = $this->purchase->payment_date;
        $this->listProducts();
    }

    public function listProducts()
    {
        $this->clothes = 0;
        $this->products = $this->purchase->product_price_purchases;
        foreach ($this->products as $cart) {
            // info($cart->product_price->price);
            $this->clothes += ($cart->product_price->price * $cart->quantity);
        }
        $this->total = $this->clothes + $this->shipping;
    }

    public function save()
    {
        $this->listProducts();
        $this->validate([
            'guide_one'     => (($this->status_id >= 12 && $this->status_id < 24) ? 'required|' : 'nullable|').'string|min:4|max:35',
            // 'guide_two'     => 'nullable|string|min:4|max:35',
            'status_id'     => ['required', 'integer', new StatusRule(5)],
            'shipping'      => ($this->status_id >= 12 ? 'required|' : 'nullable|').'numeric|min:1|max:999999',
            'payment_date'  => ($this->status_id >= 12 ? 'required|' : 'nullable|').'date|after:today',
            // 'iva'   => 'required|boolean',
        ]);
        DB::beginTransaction();
        try {
            //
            $this->purchase->update([
                'status_id' => $this->status_id,
                'guide_one' => $this->guide_one,
                'shipping'  => $this->shipping,
                'payment_date' => $this->payment_date,
            ]);

            // if ($this->status_id == 24) {
                
            // }

            $message = 'El pedido con ID: '.$this->purchase->id.' tiene un nuevo estatus, entra en la sección de <a href="'. route('compras.index') .'"><strong>Detalles de Compra</strong></a> y revisa el progreso de tu pedido.';
            if ($this->status_id == 17) {
                $message .= ', tu fecha limite de pago es hasta el dáa: '.date('d-m-Y',strtotime($this->payment_date));
            }
            if ($this->status_id == 17) {
                $message .=', El pedido ha sido enviado, y contiene '.(
                    is_null($this->guide_two) 
                    ? 'la siguiente guía: <a href="https://www.dhl.com/global-en/home/tracking.html?tracking-id='.$this->guide_one.'" target="_blank">'.$this->guide_one.'</a>'
                    : 'las siguientes guías:<a href="https://www.dhl.com/global-en/home/tracking.html?tracking-id='.$this->guide_one.'" target="_blank">'.$this->guide_one.'</a> y <a href="https://www.dhl.com/global-en/home/tracking.html?tracking-id='.$this->guide_two.'" target="_blank">'.$this->guide_two.'</a>'
                );
            }

            Utility::sendEmail($this->purchase->user->email, new NotificationMail($this->purchase->user,$this->purchase->status->name,$message));

            DB::commit();
            session()->flash('status', 'Los datos se guardaron correctamente.');
            return redirect()->route('purchases.index');
        } catch (\Throwable $th) {
            DB::rollBack();
            info($th->getMessage());
        }
    }
}
