<?php
declare(strict_types=1);

namespace CronJobs;

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

/**
 * Monthly (1st): verifies pending loan installments for the current month's payroll deduction.
 */
class HrLoanDeductionReminderJob
{
    private Database $db;
    public function __construct(Database $db) { $this->db = $db; }

    public function shouldRun(): bool
    {
        // Run on the 1st-3rd of each month
        return (int) date('j') <= 3;
    }

    public function run(): array
    {
        $today = date('Y-m-d');
        $monthEnd = date('Y-m-t');
        $reminded = 0;
        $overdue = 0;

        // Find pending installments due this month
        $pendingInstallments = $this->db->select(
            "SELECT li.id, li.loan_id, li.installment_number, li.amount, li.due_date,
                    l.employee_profile_id, hp.first_name_ar, hp.last_name_ar
             FROM hr_loan_installments li
             JOIN hr_employee_loans l ON l.id = li.loan_id
             JOIN hr_employee_profiles hp ON hp.id = l.employee_profile_id
             WHERE li.status = 'pending'
               AND li.due_date >= ?
               AND li.due_date <= ?
               AND l.status IN ('disbursed', 'repaying')
               AND l.is_archived = 0",
            [$today, $monthEnd]
        );

        if (count($pendingInstallments) > 0) {
            $totalAmount = '0.00';
            foreach ($pendingInstallments as $inst) {
                $totalAmount = bcadd($totalAmount, (string) $inst['amount'], 2);
            }

            $this->db->insert('notification_queue', [
                'type'           => 'system',
                'recipient_type' => 'employee',
                'recipient_id'   => 0,
                'subject'        => 'تذكير: أقساط السلف',
                'message'        => "يوجد " . count($pendingInstallments) . " قسط سلفة مستحق هذا الشهر بإجمالي " . number_format((float) $totalAmount, 2) . " ج.م. تأكد من خصمها في الرواتب.",
                'data_json'      => json_encode(['hr_type' => 'hr_loan_deduction', 'link' => '/hr/loans'], JSON_UNESCAPED_UNICODE),
                'status'         => 'pending',
                'created_at'     => date('Y-m-d H:i:s'),
            ]);
            $reminded = count($pendingInstallments);
        }

        // Flag overdue installments from previous months
        $overdueInstallments = $this->db->select(
            "SELECT li.id, li.loan_id
             FROM hr_loan_installments li
             JOIN hr_employee_loans l ON l.id = li.loan_id
             WHERE li.status = 'pending'
               AND li.due_date < ?
               AND l.status IN ('disbursed', 'repaying')
               AND l.is_archived = 0",
            [$today]
        );

        $overdue = count($overdueInstallments);
        if ($overdue > 0) {
            $this->db->insert('notification_queue', [
                'type'           => 'system',
                'recipient_type' => 'employee',
                'recipient_id'   => 0,
                'subject'        => 'تنبيه: أقساط سلف متأخرة',
                'message'        => "يوجد {$overdue} قسط سلفة متأخر عن موعد السداد. يرجى مراجعة حالة السلف.",
                'data_json'      => json_encode(['hr_type' => 'hr_loan_overdue', 'link' => '/hr/loans'], JSON_UNESCAPED_UNICODE),
                'status'         => 'pending',
                'created_at'     => date('Y-m-d H:i:s'),
            ]);
        }

        if ($reminded > 0 || $overdue > 0) {
            Logger::info("HR Loan Deduction Reminder: {$reminded} pending this month, {$overdue} flagged overdue");
        }

        return [
            'pending_this_month' => $reminded,
            'flagged_overdue'    => $overdue,
        ];
    }
}
