<?php

namespace App\Livewire\Cashier;

use App\Models\Cart;
use App\Models\Item;
use App\Models\ItemPrice;
use App\Models\SandboxItem;
use App\Models\Settings;
use App\Models\Warehouse;
use Exception;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Livewire\Attributes\Rule;
use Livewire\Component;

class Additem extends Component
{
    public $codeNull = false;

    public $actionButton = "store";

    #[Rule('required', message: 'The Item Code field is required.')]
    #[Rule('min:3', message: 'The Item Code field must be at least 3 characters.')]
    #[Rule('unique:Luv2_item,code', message: 'The Item Code has been taken and must be unique.')]
    public string $itemcode;

    #[Rule('required', message: 'The Item Name field is required.')]
    #[Rule('min:4', message: 'The Item Name field must be at least 4 characters.')]
    public string $itemname = '';

    #[Rule('required', message: 'The Item Price field is required.')]
    #[Rule('numeric', message: 'The Item Price field must be a number.')]
    public string $itemprice = '';


    #[Rule('required', message: 'The Item Code Bars field is required.')]
    #[Rule('min:4', message: 'The Item Code Bars field must be at least 4 characters.')]
    #[Rule('unique:Luv2_item,barcode', message: 'The Item Barcode has been taken and must be unique.')]
    public string $itemcodebars = '';
    public $errMsg = '';

    public function updatedcodeNull($value)
    {
        if ($value) {
            $this->itemcode = $this->itemcodebars;
        } else {
            $this->itemcode = '';
            $this->itemcode = $this->itemcode;
        }
    }

    public function store()
    {
        DB::beginTransaction();

        try {
            $this->validate([
                'itemcode' => 'required|min:3|unique:Luv2_item,code',
                'itemcodebars' => 'unique:Luv2_item,barcode'
            ]);

            $user = Auth::user();
            $setting = Settings::where('wh_code', $user->whs_code)->first();
            $whs = Warehouse::where('code', $setting->wh_code)->first();
            $pricelist = $whs->id_pricelist;

            $item = Item::create([
                'code' => $this->itemcode,
                'barcode' => $this->itemcodebars,
                'name' => $this->itemname,
                'group_code' => 109,
                'status' => 1,
            ]);

            $itemprice = ItemPrice::create([
                'item_code' => $this->itemcode,
                'price' => $this->itemprice,
                'id_pricelist' => $pricelist,
            ]);

            $cart = Cart::create([
                'code' => $this->itemcode,
                'barcode' => $this->itemcodebars,
                'name' => $this->itemname,
                'price' => $this->itemprice,
                'nprice' => $this->itemprice,
                'sandbox' => 'Y',
                'promo' => 0,
                'promo_tipe' => 0,
                'discount' => 0,
                'qty' => 1,
                'total_price' => $this->itemprice,
                'id_user' => $user->id,
            ]);

            $sandbox = SandboxItem::create([
                'code' => $this->itemcode,
                'name' => $this->itemname,
                'barcode' => $this->itemcodebars,
                'price' => $this->itemprice,
            ]);

            DB::commit();

            $this->dispatch('closeModal');
            $this->dispatch('cart-created')->to(Table::class);
            $this->dispatch('updatePrice')->to(Transaction::class);
            $this->dispatch('updateSearch')->to(Transaction::class);


            $this->reset();
        } catch (ValidationException $e) {
            // $this->errMsg = "Validation Failed : " . $e->getMessage();
            $this->errMsg = "Cant Create Sandbox Item Because there are Validation Failed";

        } catch (\Exception $e) {
            DB::rollBack();
            // Handle other exceptions if needed
            // $this->errMsg = "An unexpected error occured : " . $e->getMessage();
            $this->errMsg = "Cant Create Sandbox Item Because An unexpected error occured";

        }
    }

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

    public function resetModal()
    {
        $this->itemcode = '';
        $this->itemname = '';
        $this->itemcodebars = '';
        $this->itemprice = '';
        $this->errMsg = '';
        $this->resetValidation();
    }
}
