<?php

namespace App\Livewire\Financial;

use App\Domain\Pricing\Models\Promotion;
use Carbon\Carbon;
use Livewire\Component;

class CouponValidator extends Component
{
    public string $code = '';
    public ?array $result = null;
    public bool $checking = false;

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

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

        $promotion = Promotion::where('code', strtoupper(trim($this->code)))
            ->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,
            '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');
    }
}
