<?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()
    {
        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 updatedFormMemberId(?string $member_id = null)
    {
        $customer = Customer::with('user')->find($member_id);

        if (! $customer) {
            return;
        }

        $memberId = $customer->user?->id;

        $this->vouchers = Voucher::whereHas('users', function ($q) use ($memberId) {
            $q->where('user_id', $memberId);
        })
            ->where(function ($q) {
                $q->where(function ($q) {
                    $q->whereNull('start_date')
                        ->orWhere('start_date', '<=', now());
                });
                $q->where(function ($q) {
                    $q->whereNull('end_date')
                        ->orWhere('end_date', '>=', now());
                });
            })
            ->select('id', 'name', 'type', 'discount_amount', 'max_discount')
            ->orderByRaw("
                CASE
                    WHEN type = 'percentage' THEN
                        LEAST(discount_amount / 100 * COALESCE(max_discount, 99999999), COALESCE(max_discount, 99999999))
                    ELSE
                        discount_amount
                END DESC
            ")
            ->pluck('name', 'id')
            ->toArray();
    }
}
