<?php

namespace App\Livewire\Forms\Studio\Finance;

use App\Enums\SalaryAdjustmentType;
use App\Models\Payroll;
use App\Models\PayrollAdjustment;
use App\Rules\UnsignedInteger;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Livewire\Form;

class PayrollForm extends Form
{
    public array $user_ids = [];

    public string $type = '';

    public string $amount = '';

    public ?string $description = null;

    public function rules(): array
    {
        return [
            'user_ids' => ['required', 'array', 'min:1'],
            'user_ids.*' => ['required', Rule::exists('users', 'id')],
            'type' => ['required', Rule::in(SalaryAdjustmentType::values())],
            'amount' => ['required', new UnsignedInteger],
            'description' => ['required', 'string', 'max:100'],
        ];
    }

    public function validationAttributes(): array
    {
        return [
            'user_ids' => 'pegawai',
            'type' => 'tipe',
            'description' => 'keterangan',
            'amount' => 'jumlah',
        ];
    }

    public function store()
    {
        $this->validate();

        $amount = (int) replaceCurrency($this->amount);

        DB::transaction(function () use ($amount) {
            foreach ($this->user_ids as $user_id) {
                $periodMonth = Carbon::now()->format('Y-m');

                $payroll = Payroll::where('user_id', $user_id)
                    ->where('period_month', $periodMonth)
                    ->first();

                if (! $payroll) {
                    throw new \Exception('Penggajian tidak ditemukan.');
                }

                PayrollAdjustment::create([
                    'payroll_id' => $payroll->id,
                    'type' => $this->type,
                    'description' => $this->description,
                    'amount' => $amount,
                ]);

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

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

                $payroll->save();
            }
        });
    }

    public function update()
    {
        $this->validate();
    }
}
