<?php

namespace App\Livewire\HR;

use App\Domain\HR\Enums\PayslipStatus;
use App\Domain\HR\Enums\StaffPaymentMethod;
use App\Domain\HR\Models\Payslip;
use App\Domain\HR\Services\PayrollService;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('تفاصيل كشف الراتب')]
class PayslipDetail extends Component
{
    public Payslip $payslip;

    public string $paymentMethod = 'cash';
    public string $paymentReference = '';

    public bool $showPaymentModal = false;

    public function mount(Payslip $payslip): void
    {
        $this->authorize('payroll.manage');
        $this->payslip = $payslip->load([
            'trainer.employee.person',
            'trainer.person',
            'items',
            'period',
            'approver',
        ]);
    }

    public function approve(): void
    {
        try {
            $service = app(PayrollService::class);
            $service->approvePayslip($this->payslip, auth()->user());
            $this->payslip = $this->payslip->fresh([
                'trainer.employee.person',
                'trainer.person',
                'items',
                'period',
                'approver',
            ]);
            session()->flash('success', __('تم اعتماد كشف الراتب'));
        } catch (\Throwable $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function openPaymentModal(): void
    {
        $this->showPaymentModal = true;
    }

    public function processPayment(): void
    {
        $this->validate([
            'paymentMethod' => 'required|in:' . implode(',', array_column(StaffPaymentMethod::cases(), 'value')),
            'paymentReference' => 'nullable|string|max:255',
        ]);

        try {
            $service = app(PayrollService::class);
            $service->markPaid(
                $this->payslip,
                $this->paymentMethod,
                $this->paymentReference ?: null,
                auth()->user()
            );
            $this->payslip = $this->payslip->fresh([
                'trainer.employee.person',
                'trainer.person',
                'items',
                'period',
                'approver',
            ]);
            $this->showPaymentModal = false;
            $this->paymentReference = '';
            session()->flash('success', __('تم تسجيل الدفع بنجاح'));
        } catch (\Throwable $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function render()
    {
        $earningItems = $this->payslip->items->where('is_deduction', false)->sortBy('sort_order');
        $deductionItems = $this->payslip->items->where('is_deduction', true)->sortBy('sort_order');

        return view('livewire.hr.payslip-detail', [
            'earningItems'   => $earningItems,
            'deductionItems' => $deductionItems,
            'paymentMethods' => StaffPaymentMethod::cases(),
        ]);
    }
}
