<?php

namespace App\Console\Commands;

use App\Enums\IsPaid;
use App\Enums\RoleEnum;
use App\Models\Payroll;
use App\Models\User;
use Illuminate\Console\Command;

class GenerateMonthlyPayroll extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'payroll:generate {month?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate monthly payroll for administrators';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $month = $this->argument('month') ?? now()->format('Y-m');
        $prevMonth = now()->parse($month.'-01')->subMonth()->format('Y-m');

        $payrollsToPay = Payroll::where('period_month', $prevMonth)
            ->paid()
            ->get();

        foreach ($payrollsToPay as $payroll) {
            $payroll->update([
                'is_paid' => IsPaid::PAID,
            ]);
        }

        $users = User::role(RoleEnum::ADMINISTRATOR->value)->get();

        $count = 0;
        foreach ($users as $user) {
            $exists = Payroll::where('user_id', $user->id)
                ->where('period_month', $month)
                ->exists();

            if (! $exists) {
                $baseSalary = $user->base_salary;

                Payroll::create([
                    'user_id' => $user->id,
                    'period_month' => $month,
                    'base_salary' => $baseSalary,
                    'bonus' => 0,
                    'deduction' => 0,
                    'total_salary' => $baseSalary,
                    'is_paid' => IsPaid::NOT_PAID,
                ]);
                $count++;
            }
        }

        if ($payrollsToPay->count() > 0) {
            $this->info("Berhasil memproses pembayaran untuk {$payrollsToPay->count()} data payroll bulan {$prevMonth}.");
        }

        $this->info("Berhasil membuat {$count} data payroll baru untuk bulan {$month}.");
    }
}
