<?php

namespace App\Livewire\Studio\Finance;

use App\Enums\SalaryAdjustmentType;
use App\Livewire\Forms\Studio\Finance\PayrollForm;
use App\Models\Payroll as PayrollModel;
use App\Models\PayrollAdjustment;
use App\Models\User;
use App\Traits\WithAuthorization;
use App\Traits\WithCloseModal;
use App\Traits\WithConfirmation;
use App\Traits\WithToast;
use App\Traits\WithUpdatedData;
use App\Traits\WithUserSelector;
use Flux\Flux;
use Illuminate\Support\Facades\DB;
use Livewire\Attributes\On;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('Penggajian')]
class Payroll extends Component
{
    use WithAuthorization, WithCloseModal, WithConfirmation, WithToast, WithUpdatedData, WithUserSelector;

    public PayrollForm $form;

    public $payrolls;

    public string $method = 'create';

    public string $modalTitle = '';

    public array $users = [];

    public function mount()
    {
        $this->loadPayrolls();

        $this->users = User::whereHas('employee')
            ->latest()
            ->get()
            ->mapWithKeys(fn ($user) => [
                $user->id => $user->employee->full_name,
            ])
            ->toArray();
    }

    private function loadPayrolls()
    {
        $this->payrolls = PayrollModel::with(['user', 'user.employee'])
            ->where('period_month', now()->format('Y-m'))
            ->get();
    }

    #[On('modal:open')]
    public function openModal(string $method, string $modalTitle, ?string $id = null)
    {
        $this->resetValidation();
        $this->resetErrorBag();

        $this->method = $method;
        $this->modalTitle = $modalTitle;
    }

    public function create()
    {
        $this->canOrAbort('manage adjustment');

        $this->form->store();

        $this->loadPayrolls();

        $this->dispatch('refreshDatatable');

        $this->toast('Penyesuaian berhasil ditambahkan.');

        Flux::modals()->close();
    }

    public function delete(PayrollAdjustment $adjustment)
    {
        $this->canOrAbort('manage adjustment');

        DB::transaction(function () use ($adjustment) {
            $payroll = PayrollModel::find($adjustment->payroll_id);

            if ($adjustment->type->value == SalaryAdjustmentType::BONUS->value) {
                $payroll->bonus -= $adjustment->amount;
            } elseif ($adjustment->type->value == SalaryAdjustmentType::DEDUCTION->value) {
                $payroll->deduction -= $adjustment->amount;
            }

            $payroll->total_salary = $payroll->base_salary + $payroll->bonus - $payroll->deduction;

            $payroll->save();

            $adjustment->delete();
        });

        $this->loadPayrolls();

        $this->dispatch('refreshDatatable');
        $this->toast('Penggajian berhasil dihapus.');
        Flux::modals()->close();
    }

    public function render()
    {
        return view('livewire.studio.finance.payrolls', [
            'pageTitle' => 'Penggajian',
        ]);
    }
}
