<?php
declare(strict_types=1);

namespace CronJobs;

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

/**
 * Daily: alerts when an employee's probation period is about to end (7 days).
 */
class HrProbationEndJob
{
    private Database $db;
    public function __construct(Database $db) { $this->db = $db; }

    public function shouldRun(): bool
    {
        return true; // Runs daily
    }

    public function run(): array
    {
        $today = date('Y-m-d');
        $alertDate = date('Y-m-d', strtotime('+7 days'));
        $alerted = 0;

        // Find employees whose probation ends within 7 days
        $probationEnding = $this->db->select(
            "SELECT hp.id, hp.first_name_ar, hp.last_name_ar, hp.employee_number,
                    hp.hire_date, hp.probation_end_date,
                    DATEDIFF(hp.probation_end_date, ?) as days_remaining
             FROM hr_employee_profiles hp
             WHERE hp.employment_status = 'active'
               AND hp.probation_end_date IS NOT NULL
               AND hp.probation_end_date >= ?
               AND hp.probation_end_date <= ?
               AND hp.is_archived = 0",
            [$today, $today, $alertDate]
        );

        foreach ($probationEnding as $emp) {
            $daysRemaining = (int) $emp['days_remaining'];
            $employeeName = $emp['first_name_ar'] . ' ' . $emp['last_name_ar'];

            $this->db->insert('notification_queue', [
                'type'           => 'system',
                'recipient_type' => 'employee',
                'recipient_id'   => 0,
                'subject'        => 'انتهاء فترة اختبار',
                'message'        => "فترة اختبار الموظف {$employeeName} ستنتهي خلال {$daysRemaining} يوم (تاريخ الانتهاء: {$emp['probation_end_date']})",
                'data_json'      => json_encode(['hr_type' => 'hr_probation_end', 'link' => '/hr/employees/' . (int) $emp['id']], JSON_UNESCAPED_UNICODE),
                'status'         => 'pending',
                'created_at'     => date('Y-m-d H:i:s'),
            ]);
            $alerted++;
        }

        // Also flag employees whose probation has passed but status not updated
        $probationPassed = $this->db->select(
            "SELECT id FROM hr_employee_profiles
             WHERE employment_status = 'probation'
               AND probation_end_date IS NOT NULL
               AND probation_end_date < ?
               AND is_archived = 0",
            [$today]
        );

        $confirmed = 0;
        foreach ($probationPassed as $emp) {
            $this->db->update('hr_employee_profiles', [
                'employment_status' => 'active',
                'updated_at'        => date('Y-m-d H:i:s'),
            ], '`id` = ? AND `is_archived` = 0', [(int) $emp['id']]);
            $confirmed++;
        }

        if ($alerted > 0 || $confirmed > 0) {
            Logger::info("HR Probation End Job: {$alerted} alerts, {$confirmed} auto-confirmed");
        }

        return [
            'alerted'   => $alerted,
            'confirmed' => $confirmed,
        ];
    }
}
