<?php

namespace App\Livewire\Financial;

use App\Domain\Pricing\Models\Promotion;
use App\Domain\Shared\Traits\UsesBranchScope;
use Carbon\Carbon;
use Livewire\Component;

class CouponValidator extends Component
{
    use UsesBranchScope;

    public string $code = '';
    public ?array $result = null;
    public bool $checking = false;

    public function check(): void
    {
        $this->result = null;

        if (empty(trim($this->code))) {
            return;
        }

        $branchId = $this->getActiveBranchId();

        $promotion = Promotion::where('code', strtoupper(trim($this->code)))
            ->when($branchId, fn ($q) => $q->where(fn ($b) => $b->whereNull('branch_id')->orWhere('branch_id', $branchId)))
            ->where('is_active', true)
            ->first();

        if (!$promotion) {
            $this->result = ['valid' => false, 'message' => __('كود غير صالح')];
            return;
        }

        if ($promotion->start_date && Carbon::parse($promotion->start_date)->isFuture()) {
            $this->result = ['valid' => false, 'message' => __('هذا العرض لم يبدأ بعد')];
            return;
        }

        if ($promotion->end_date && Carbon::parse($promotion->end_date)->isPast()) {
            $this->result = ['valid' => false, 'message' => __('انتهت صلاحية هذا العرض')];
            return;
        }

        if ($promotion->max_uses && $promotion->times_used >= $promotion->max_uses) {
            $this->result = ['valid' => false, 'message' => __('تم استنفاد عدد مرات الاستخدام')];
            return;
        }

        $this->result = [
            'valid' => true,
            'message' => __('كود صالح'),
            'name' => $promotion->name_ar ?? $promotion->name,
            'type' => $promotion->adjustment_type,
            'value' => $promotion->adjustment_value,
            // Percentages are basis points in the column, so the raw number is
            // not displayable. The view renders this instead.
            'value_label' => in_array($promotion->adjustment_type, [
                \App\Domain\Pricing\Enums\AdjustmentType::PercentageDiscount,
                \App\Domain\Pricing\Enums\AdjustmentType::PercentageIncrease,
            ], true)
                ? \App\Domain\Pricing\Support\Percent::label($promotion->adjustment_value)
                : format_money($promotion->adjustment_value),
            'remaining' => $promotion->max_uses ? ($promotion->max_uses - $promotion->times_used) : null,
            'expires' => $promotion->end_date,
        ];

        $this->dispatch('coupon-validated', promotionId: $promotion->id, code: $this->code);
    }

    public function render()
    {
        return view('livewire.financial.coupon-validator');
    }
}
