<?php

namespace App\Livewire\Cashier;

use App\Models\DetailInvoice;
use App\Models\Invoice;
use App\Models\Sales;
use Illuminate\Support\Facades\DB;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Livewire\Attributes\On;
use Livewire\Attributes\Rule;
use Livewire\Component;

class ChangeInvoice extends Component
{
    use LivewireAlert;

    public $invoicesbx;
    // #[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.')]
    public string $itemcodebars = '';

    #[On('invoiceStatusChanged')]
    public function mount()
    {
        $invoicesbx = DB::table('Luv2_invoice')
            ->leftJoin('Luv2_salesemp', 'Luv2_invoice.id_sales', '=', 'Luv2_salesemp.code')
            ->leftJoin('Luv2_users', 'Luv2_invoice.id_user', '=', 'Luv2_users.id')
            ->where('sandbox', 'Y')
            ->select(
                'Luv2_invoice.*',
                'Luv2_salesemp.name as sales_name',
                'Luv2_users.name as users_name'
            )
            ->orderBy('Luv2_invoice.created_at', 'DESC')
            ->get();
        // $invoicesbx = Invoice::where('sandbox', 'Y')->get();
        $this->invoicesbx = $invoicesbx;
        $this->invoicesbx = $this->invoicesbx->map(function ($invoice) {
            if ($invoice->note) {
                // Decode the invoice note into an associative array
                $invoiceNote = json_decode($invoice->note, true);

                // Access the cash and transfer values
                $cash = $invoiceNote['cash'];
                $transfer = $invoiceNote['transfer'];

                // Set the cash and transfer values on the invoice object
                $invoice->cash = $cash;
                $invoice->transfer = $transfer;
            }
            // Fetch related Luv2_detailinvoice records for each Luv2_invoice
            $details = DB::table('Luv2_detailinvoice')
                ->leftJoin('Luv2_item', 'Luv2_detailinvoice.code', '=', 'Luv2_item.code')
                ->leftJoin('Luv2_member', 'Luv2_detailinvoice.id_member', '=', 'Luv2_member.code')
                ->where('invoice', $invoice->no)
                ->select(
                    'Luv2_detailinvoice.*',
                    'Luv2_item.barcode as item_barcode',
                    'Luv2_member.name as member_name',

                )
                ->get();

            // Attach the details to the invoice
            $invoice->details = $details;

            return $invoice;
        });
    }

    public function changeStatus($code)
    {
        $invoice = Invoice::where('no', $code)->first();
        $invoice->sandbox = 'N';
        $invoice->save();
        DetailInvoice::where('invoice', $invoice->no)->update(['sandbox' => 'N']);

        $this->dispatch('invoiceStatusChanged');
        $this->alert('info', 'Invoice no : ' . $invoice->no . ' Changed', [
            'position' => 'top-right',
            'timer' => 3000,
            'toast' => true,
            'timerProgressBar' => true,
        ]);
    }

    public function changeItemSandbox($invoice, $code)
    {
        $checkitem = DB::table('Luv2_item')->where('code', $this->itemcode)->first();
        $item = DB::table('Luv2_item')->where('code', $code)->first();
        $itemprice = DB::table('Luv2_item_pricelist')->where('item_code', $code)->first();
        $detailinvoice = DB::table('Luv2_detailinvoice')->where('invoice', $invoice)->where('code', $code)->first();
        $headerinvoice = DB::table('Luv2_invoice')->where('no', $invoice)->first();

        if ($checkitem) {
            if ($itemprice) {
                DB::table('Luv2_item_pricelist')
                    ->where('item_code', $this->itemcode)
                    ->update([
                        'item_code' => $this->itemcode,
                        'price' => $this->itemprice,
                    ]);
            }

            if ($detailinvoice) {
                DB::table('Luv2_detailinvoice')
                    ->where('invoice', $invoice)
                    ->where('code', $code)
                    ->update([
                        'code' => $this->itemcode,
                        'barcode' => $this->itemcodebars,
                        'nprice' => $this->itemprice,
                        'name' => $this->itemname,
                        'sandbox' => 'N',
                    ]);
            }
            if($headerinvoice){
                DB::table('Luv2_invoice')
                    ->where('no', $invoice)
                    ->update([
                        'sandbox' => 'N'
                    ]);
            }
        } else {
            if ($item) {
                DB::table('Luv2_item')
                    ->where('code', $code)
                    ->update([
                        'code' => $this->itemcode,
                        'barcode' => $this->itemcodebars,
                        'name' => $this->itemname,
                    ]);
            }

            if ($itemprice) {
                DB::table('Luv2_item_pricelist')
                    ->where('item_code', $code)
                    ->update([
                        'item_code' => $this->itemcode,
                        'price' => $this->itemprice,
                    ]);
            }

            if ($detailinvoice) {
                DB::table('Luv2_detailinvoice')
                    ->where('invoice', $invoice)
                    ->where('code', $code)
                    ->update([
                        'code' => $this->itemcode,
                        'barcode' => $this->itemcodebars,
                        'nprice' => $this->itemprice,
                        'name' => $this->itemname,
                        'sandbox' => 'N',
                    ]);
            }
            if($headerinvoice){
                DB::table('Luv2_invoice')
                    ->where('no', $invoice)
                    ->update([
                        'sandbox' => 'N'
                    ]);
            }
        }

        $this->alert('success', 'Item Sandbox : ' . $detailinvoice->name . ' Succesfully changed', [
            'position' => 'top-right',
            'timer' => 3000,
            'toast' => true,
            'timerProgressBar' => true,
        ]);
        $this->dispatch('finish');
    }

    #[On('finish')]
    public function torefresh()
    {
        $this->dispatch('torefresh');
    }

    #[On('torefresh')]
    public function afterSuccess()
    {
        return redirect()->route('welcome.dashboard');
    }

    public function isSaveButtonDisabled(): bool
    {
        // Check if any of the fields are empty
        if (empty($this->itemcode) || empty($this->itemname) || empty($this->itemprice) || empty($this->itemcodebars)) {
            return true;
        }

        // Check if validation rules are not fulfilled
        if ($this->getErrorBag()->hasAny(['itemname', 'itemprice', 'itemcodebars'])) {
            return true;
        }

        return false;
    }

    public function render()
    {
        return view('livewire.cashier.change-invoice');
    }
}
