<?php
declare(strict_types=1);

namespace CronJobs;

use App\Core\Database;
use App\Core\Logger;

/**
 * Monthly (20th): reminds if the current month's payroll period is still open/unprocessed.
 */
class HrPayrollReminderJob
{
    private Database $db;
    public function __construct(Database $db) { $this->db = $db; }

    public function shouldRun(): bool
    {
        // Run on the 20th of each month (or after)
        return (int) date('j') >= 20 && (int) date('j') <= 22;
    }

    public function run(): array
    {
        $year = (int) date('Y');
        $month = (int) date('n');
        $reminded = 0;

        // Check if current month's payroll period exists and its status
        $period = $this->db->selectOne(
            "SELECT id, status FROM hr_payroll_periods
             WHERE year = ? AND month = ? AND is_archived = 0",
            [$year, $month]
        );

        $monthNames = [1=>'يناير',2=>'فبراير',3=>'مارس',4=>'أبريل',5=>'مايو',6=>'يونيو',7=>'يوليو',8=>'أغسطس',9=>'سبتمبر',10=>'أكتوبر',11=>'نوفمبر',12=>'ديسمبر'];
        $monthName = $monthNames[$month] ?? (string) $month;

        if (!$period) {
            // No payroll period created yet
            $this->db->insert('notification_queue', [
                'type'           => 'system',
                'recipient_type' => 'employee',
                'recipient_id'   => 0,
                'subject'        => 'تذكير: فترة الرواتب',
                'message'        => "لم يتم إنشاء فترة رواتب شهر {$monthName} {$year} بعد. يرجى إنشاء الفترة وحساب الرواتب.",
                'data_json'      => json_encode(['hr_type' => 'hr_payroll_reminder', 'link' => '/hr/payroll'], JSON_UNESCAPED_UNICODE),
                'status'         => 'pending',
                'created_at'     => date('Y-m-d H:i:s'),
            ]);
            $reminded++;
        } elseif ($period['status'] === 'open') {
            // Period exists but not yet calculated
            $this->db->insert('notification_queue', [
                'type'           => 'system',
                'recipient_type' => 'employee',
                'recipient_id'   => 0,
                'subject'        => 'تذكير: حساب الرواتب',
                'message'        => "فترة رواتب شهر {$monthName} {$year} مفتوحة ولم يتم حساب الرواتب بعد.",
                'data_json'      => json_encode(['hr_type' => 'hr_payroll_reminder', 'link' => '/hr/payroll/' . (int) $period['id']], JSON_UNESCAPED_UNICODE),
                'status'         => 'pending',
                'created_at'     => date('Y-m-d H:i:s'),
            ]);
            $reminded++;
        } elseif ($period['status'] === 'calculated') {
            // Calculated but not approved
            $this->db->insert('notification_queue', [
                'type'           => 'system',
                'recipient_type' => 'employee',
                'recipient_id'   => 0,
                'subject'        => 'تذكير: اعتماد الرواتب',
                'message'        => "رواتب شهر {$monthName} {$year} تم حسابها وبانتظار الاعتماد.",
                'data_json'      => json_encode(['hr_type' => 'hr_payroll_reminder', 'link' => '/hr/payroll/' . (int) $period['id']], JSON_UNESCAPED_UNICODE),
                'status'         => 'pending',
                'created_at'     => date('Y-m-d H:i:s'),
            ]);
            $reminded++;
        }

        if ($reminded > 0) {
            Logger::info("HR Payroll Reminder: {$reminded} reminder(s) sent for {$monthName} {$year}");
        }

        return ['reminded' => $reminded];
    }
}
