<?php

namespace App\Livewire\Financial;

use App\Domain\Financial\Services\ExpenseService;
use App\Domain\Shared\Exceptions\DomainException;
use App\Domain\Shared\Traits\UsesBranchScope;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('تسجيل إيراد خارجي')]
class ExternalRevenueForm extends Component
{
    use UsesBranchScope;

    public string $source = '';
    public string $amount_display = '';
    public string $description = '';
    public string $payment_method = 'cash';
    public string $reference_number = '';
    public ?string $revenue_date = null;
    public string $notes = '';

    public function mount(): void
    {
        $this->authorize('expenses.create');
        $this->revenue_date = now()->toDateString();
    }

    public function rules(): array
    {
        return [
            'source' => 'required|string|max:255',
            'amount_display' => 'required|numeric|min:0.01',
            'description' => 'required|string|max:500',
            'payment_method' => 'required|in:cash,card,bank_transfer,wallet,online,cheque,other',
            'reference_number' => 'nullable|string|max:100',
            'revenue_date' => 'required|date',
            'notes' => 'nullable|string',
        ];
    }

    public function messages(): array
    {
        return [
            'source.required' => 'مصدر الإيراد مطلوب',
            'amount_display.required' => 'المبلغ مطلوب',
            'amount_display.min' => 'المبلغ يجب أن يكون أكبر من صفر',
            'description.required' => 'وصف الإيراد مطلوب',
            'payment_method.required' => 'اختر طريقة الاستلام',
            'revenue_date.required' => 'تاريخ الإيراد مطلوب',
        ];
    }

    public function save(ExpenseService $service): void
    {
        $this->validate();

        try {
            $service->recordExternalRevenue([
                'branch_id' => $this->getActiveBranchId(),
                'source' => $this->source,
                'amount' => (int) round((float) $this->amount_display * 100),
                'description' => $this->description,
                'payment_method' => $this->payment_method,
                'reference_number' => $this->reference_number ?: null,
                'revenue_date' => $this->revenue_date,
                'notes' => $this->notes ?: null,
            ], auth()->user());

            session()->flash('success', __('تم تسجيل الإيراد الخارجي بنجاح'));
            $this->redirect(route('financial.overview'), navigate: true);
        } catch (DomainException $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.financial.external-revenue-form');
    }
}
