<?php

namespace App\Livewire\Returnsale;

use Livewire\Attributes\On;
use Livewire\Component;

class Additem extends Component
{
    public $selectedItems;
    public $inputs = [];
    
    public function rules()
    {
        $rules = [];
        foreach ($this->selectedItems as $index => $item) {
            $rules["inputs.{$index}.qty"] = ['required', 'integer', 'min:1', 'max:' . $item['qty']];
        }
        return $rules;
    }
    public function messages()
    {
        $messages = [];
        foreach ($this->selectedItems as $index => $item) {
            $messages["inputs.{$index}.qty.required"] = "The quantity is required for {$item['name']}.";
            $messages["inputs.{$index}.qty.min"] = "The quantity must be at least 1 for {$item['name']}.";
            $messages["inputs.{$index}.qty.max"] = "The quantity cannot exceed {$item['qty']} for {$item['name']}.";
        }
        return $messages;
    }

    #[On('openModalWithSelectedData')]
    public function mount($selectedItems)
    {
        // dd($selectedItems);
        $this->inputs = [];
        $this->selectedItems = $selectedItems;
        foreach ($selectedItems as $item) {
            $this->inputs[] = [
                'qty' => 1,
            ];
        }
    }

    public function select()
    {
        $this->validate();

        $overallTotalPrice = 0;

        foreach ($this->selectedItems as $index => &$item) {
            // Get the quantity for the item
            $qty = $this->inputs[$index]['qty'];

            // Calculate the price of the item
            $price = $item['price'] * $qty;

            // Add the price of the item to the overall total price
            $overallTotalPrice += $price;

            $itemReturnDetails[] = [
                'name' => $item['name'],
                'code' => $item['code'],
                'barcode' => $item['barcode'],
                'id_member' => $item['id_member'],
                'id_sales' => $item['id_sales'],
                'disc' => $item['disc'],
                'id_user' => $item['id_user'],
                'invoice' => $item['invoice'],
                'price' => $item['price'],
                'total_price' => $item['total_price'],
                'qty' => $qty,
            ];
        }

        $this->dispatch('afterSubmitItem', $this->selectedItems, $overallTotalPrice);
        // $this->dispatch('afterSelect', data: $overallTotalPrice, datas: $itemReturnDetails)->to(Table::class);
        // $this->dispatch('updateTotalPrice', data: $overallTotalPrice)->to(Table::class);
        $this->dispatch('close-modal');
        $this->close();
    }

    public function close()
    {
        $this->resetValidation();
        $this->reset();
    }

    
    public function render()
    {
        return view('livewire.returnsale.additem');
    }
}
