<?php

namespace App\Livewire\Pricing;

use App\Domain\Identity\Models\Branch;
use App\Domain\Pricing\Models\BasePrice;
use App\Domain\Training\Models\Activity;
use App\Domain\Training\Models\TrainingProgram;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('سعر أساسي')]
class BasePriceForm extends Component
{
    public ?BasePrice $basePrice = null;
    public bool $editing = false;

    public string $name_ar = '';
    public string $name = '';
    public string $priceable_type = '';
    public string $priceable_id = '';
    public string $branch_id = '';
    public string $amount = '';
    public string $effective_from = '';
    public string $effective_to = '';
    public int $priority = 0;
    public bool $is_active = true;
    public string $notes = '';

    public function mount(?BasePrice $basePrice = null): void
    {
        $this->authorize('pricing.create');

        if ($basePrice && $basePrice->exists) {
            $this->authorize('pricing.update');
            $this->basePrice = $basePrice;
            $this->editing = true;
            $this->name_ar = $basePrice->name_ar;
            $this->name = $basePrice->name ?? '';
            $this->priceable_type = $basePrice->priceable_type ?? '';
            $this->priceable_id = (string) ($basePrice->priceable_id ?? '');
            $this->branch_id = (string) ($basePrice->branch_id ?? '');
            $this->amount = (string) ($basePrice->amount / 100);
            $this->effective_from = $basePrice->effective_from?->format('Y-m-d') ?? '';
            $this->effective_to = $basePrice->effective_to?->format('Y-m-d') ?? '';
            $this->priority = $basePrice->priority ?? 0;
            $this->is_active = $basePrice->is_active;
            $this->notes = $basePrice->notes ?? '';
        } else {
            $this->effective_from = now()->format('Y-m-d');
        }
    }

    public function rules(): array
    {
        return [
            'name_ar' => 'required|string|max:255',
            'name' => 'nullable|string|max:255',
            'priceable_type' => 'required|string|in:training_program,activity',
            'priceable_id' => 'required|integer',
            'branch_id' => 'nullable|integer|exists:branches,id',
            'amount' => 'required|numeric|min:0.01',
            'effective_from' => 'required|date',
            'effective_to' => 'nullable|date|after:effective_from',
            'priority' => 'integer|min:0',
            'is_active' => 'boolean',
            'notes' => 'nullable|string|max:1000',
        ];
    }

    public function messages(): array
    {
        return [
            'name_ar.required' => __('الاسم بالعربية مطلوب'),
            'priceable_type.required' => __('نوع العنصر مطلوب'),
            'priceable_id.required' => __('العنصر مطلوب'),
            'amount.required' => __('المبلغ مطلوب'),
            'amount.min' => __('المبلغ يجب أن يكون أكبر من صفر'),
            'effective_from.required' => __('تاريخ البداية مطلوب'),
            'effective_to.after' => __('تاريخ النهاية يجب أن يكون بعد تاريخ البداية'),
            'branch_id.exists' => __('الفرع المحدد غير صالح'),
        ];
    }

    public function save(): void
    {
        $validated = $this->validate();

        $morphMap = [
            'training_program' => 'App\\Domain\\Training\\Models\\TrainingProgram',
            'activity' => 'App\\Domain\\Training\\Models\\Activity',
        ];

        $data = [
            'name_ar' => $this->name_ar,
            'name' => $this->name ?: null,
            'priceable_type' => $morphMap[$this->priceable_type] ?? $this->priceable_type,
            'priceable_id' => (int) $this->priceable_id,
            'branch_id' => $this->branch_id ? (int) $this->branch_id : null,
            'amount' => (int) round((float) $this->amount * 100),
            'effective_from' => $this->effective_from,
            'effective_to' => $this->effective_to ?: null,
            'priority' => $this->priority,
            'is_active' => $this->is_active,
            'notes' => $this->notes ?: null,
        ];

        if ($this->editing && $this->basePrice) {
            $this->basePrice->update($data);
            session()->flash('success', __('تم تحديث السعر بنجاح'));
        } else {
            $data['created_by'] = auth()->id();
            BasePrice::create($data);
            session()->flash('success', __('تم إنشاء السعر بنجاح'));
        }

        $this->redirect(route('pricing.base-prices'), navigate: true);
    }

    public function render()
    {
        $priceableOptions = [];
        if ($this->priceable_type === 'training_program') {
            $priceableOptions = TrainingProgram::orderBy('name_ar')->pluck('name_ar', 'id')->toArray();
        } elseif ($this->priceable_type === 'activity') {
            $priceableOptions = Activity::orderBy('name_ar')->pluck('name_ar', 'id')->toArray();
        }

        return view('livewire.pricing.base-price-form', [
            'branches' => Branch::orderBy('name_ar')->get(),
            'priceableOptions' => $priceableOptions,
        ]);
    }
}
