<?php

namespace App\Console\Commands;

use App\Enums\IsPaid;
use App\Jobs\StorePushNotification;
use App\Models\Payroll;
use App\Models\PushNotification;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Console\Command;

class ClosePayrolls extends Command
{
    protected $signature = 'payroll:close {--current} {--month= : Target month in Y-m format}';

    protected $description = 'Mark payrolls as paid for the current month or the specified month. Default: current month.';

    public function handle(): void
    {
        $targetMonth = $this->option('month') ?: Carbon::now()->format('Y-m');

        if ($this->option('current')) {
            $targetMonth = Carbon::now()->format('Y-m');
        }

        $updatedCount = Payroll::where('period_month', $targetMonth)
            ->where('is_paid', IsPaid::NOT_PAID)
            ->update([
                'is_paid' => IsPaid::PAID,
                'paid_at' => now(),
            ]);

        if ($updatedCount === 0) {
            $this->warn('Tidak ada payroll yang perlu ditutup untuk bulan '.formatDateLocalized($targetMonth, 'F Y').'.');

            return;
        }

        $userIds = Payroll::where('period_month', $targetMonth)
            ->where('is_paid', IsPaid::PAID)
            ->pluck('user_id')
            ->unique();

        StorePushNotification::dispatch(
            PushNotification::whereIn('user_id', $userIds)->get(),
            [
                'title' => 'Hari Ditunggu Telah Tiba 🎉',
                'body' => 'Hari ini kamu gajian untuk periode '.formatDateLocalized($targetMonth, 'F Y').'. Terima kasih sudah berkontribusi.',
                'url' => route('studio.finance.payroll.index'),
            ],
        );

        $userIds = User::role('Developer')->pluck('id')->toArray();
        StorePushNotification::dispatch(
            PushNotification::whereIn('user_id', $userIds)->get(),
            [
                'title' => 'Hari Gajian Karyawan 💸',
                'body' => 'Hari ini karyawan dijadwalkan menerima gaji periode '.formatDateLocalized($targetMonth, 'F Y').'. Pastikan saldo dan proses transfer telah siap.',
                'url' => route('studio.finance.payroll.index'),
            ],
        );

        $this->info('Payroll untuk bulan '.formatDateLocalized($targetMonth, 'F Y')." berhasil ditandai selesai. Total: {$updatedCount}");
    }
}
