<?php

namespace App\Traits\Order;

use App\Enums\UserStatus;
use App\Models\Customer;
use App\Models\Voucher;
use Livewire\Attributes\Computed;

trait WithMember
{
    public string $searchMember = '';

    #[Computed]
    public function members(): array
    {
        if ($this->searchMember === '') {
            return [];
        }

        return Customer::whereHas('user', fn ($q) => $q->where('status', UserStatus::ACTIVE))
            ->where('phone_number', 'like', '%'.$this->searchMember.'%')
            ->get()
            ->map(fn ($customer) => [
                'id' => $customer->id,
                'name' => $customer?->name,
                'phone_number' => $customer?->phone_number,
            ])
            ->toArray();
    }

    public function updatedFormVoucherId(?string $voucherId = null): void
    {
        $voucher = Voucher::find($voucherId);

        if (! $voucher) {
            $this->voucherDiscount = 0;

            $this->total = $this->getTotal();

            return;
        }

        $subtotal = $this->getSubtotal();

        $this->voucherDiscount = $this->calculateDiscount($subtotal, $voucher->id);

        $this->total = $this->getTotal();
    }

    public function updatedFormMemberId(?string $memberId = null): void
    {
        $customer = Customer::with('user')->find($memberId);

        if (! $customer) {
            $this->voucherDiscount = 0;

            $this->form->voucher_id = '';

            $this->vouchers = [];

            $this->total = $this->getTotal();

            return;
        }

        $this->loadVouchers($customer->user?->id, $this->form->outlet_id);
    }

    public function updatedFormOutletId(?string $outletId = null): void
    {
        $customer = Customer::with('user')->find($this->form->member_id);
        if (! $customer) {
            return;
        }

        $this->loadVouchers($customer->user?->id, $outletId);
    }

    private function loadVouchers(?string $memberId, ?string $outletId): void
    {
        $this->vouchers = Voucher::whereHas('users', fn ($q) => $q->where('user_id', $memberId))
            ->whereHas('outlets', fn ($q) => $q->where('outlet_id', $outletId))
            ->active()
            ->orderBy('discount_amount', 'desc')
            ->pluck('name', 'id')
            ->toArray();
    }
}
