<?php

namespace App\Livewire\HR;

use App\Domain\HR\Enums\AdvanceStatus;
use App\Domain\HR\Models\Trainer;
use App\Domain\HR\Models\TrainerAdvance;
use App\Domain\HR\Services\TrainerAdvanceService;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('السلف')]
class TrainerAdvances extends Component
{
    use WithPagination;

    #[Url]
    public string $statusFilter = '';

    #[Url]
    public string $search = '';

    // Create form
    public bool $showCreateModal = false;
    public ?int $selectedTrainerId = null;
    public string $amount = '';
    public int $installmentsCount = 3;
    public string $reason = '';

    public function mount(): void
    {
        $this->authorize('payroll.manage');
    }

    public function updatedSearch(): void
    {
        $this->resetPage();
    }

    public function updatedStatusFilter(): void
    {
        $this->resetPage();
    }

    public function openCreateModal(): void
    {
        $this->reset(['selectedTrainerId', 'amount', 'installmentsCount', 'reason']);
        $this->installmentsCount = 3;
        $this->showCreateModal = true;
    }

    public function createAdvance(): void
    {
        $this->validate([
            'selectedTrainerId' => 'required|exists:trainers,id',
            'amount' => 'required|numeric|min:1',
            'installmentsCount' => 'required|integer|min:1|max:24',
        ], [
            'selectedTrainerId.required' => 'يجب اختيار مدرب',
            'amount.required' => 'يجب إدخال المبلغ',
            'amount.min' => 'المبلغ يجب أن يكون أكبر من صفر',
            'installmentsCount.required' => 'يجب تحديد عدد الأقساط',
            'installmentsCount.min' => 'قسط واحد على الأقل',
        ]);

        try {
            $trainer = Trainer::findOrFail($this->selectedTrainerId);
            $amountPiasters = (int) round((float) $this->amount * 100);

            $service = app(TrainerAdvanceService::class);
            $service->create(
                $trainer,
                $amountPiasters,
                $this->installmentsCount,
                $this->reason ?: null,
                auth()->user()
            );

            $this->showCreateModal = false;
            session()->flash('success', __('تم تسجيل السلفة بنجاح'));
        } catch (\Throwable $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function cancelAdvance(int $id): void
    {
        try {
            $advance = TrainerAdvance::findOrFail($id);
            $service = app(TrainerAdvanceService::class);
            $service->cancel($advance, auth()->user());
            session()->flash('success', __('تم إلغاء السلفة'));
        } catch (\Throwable $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function pauseAdvance(int $id): void
    {
        try {
            $advance = TrainerAdvance::findOrFail($id);
            $service = app(TrainerAdvanceService::class);
            $service->pause($advance);
            session()->flash('success', __('تم إيقاف السلفة'));
        } catch (\Throwable $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function resumeAdvance(int $id): void
    {
        try {
            $advance = TrainerAdvance::findOrFail($id);
            $service = app(TrainerAdvanceService::class);
            $service->resume($advance);
            session()->flash('success', __('تم استئناف السلفة'));
        } catch (\Throwable $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function render()
    {
        $query = TrainerAdvance::with(['trainer.employee.person', 'trainer.person'])
            ->latest('issued_date');

        if ($this->statusFilter) {
            $query->where('status', $this->statusFilter);
        }

        if ($this->search) {
            $search = $this->search;
            $query->whereHas('trainer.employee.person', function ($q) use ($search) {
                $q->where('name_ar', 'ilike', "%{$search}%");
            })->orWhereHas('trainer.person', function ($q) use ($search) {
                $q->where('name_ar', 'ilike', "%{$search}%");
            });
        }

        $trainers = Trainer::where('status', 'active')
            ->with('employee.person', 'person')
            ->get();

        return view('livewire.hr.trainer-advances', [
            'advances' => $query->paginate(15),
            'statuses' => AdvanceStatus::cases(),
            'trainers' => $trainers,
        ]);
    }
}
