<?php
declare(strict_types=1);

namespace CronJobs;

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

/**
 * Daily: alerts 30 days before contract end; auto-expires past contracts.
 */
class HrContractExpiryJob
{
    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('+30 days'));
        $expired = 0;
        $alerted = 0;

        // 1. Auto-expire contracts past their end date
        $expiredContracts = $this->db->select(
            "SELECT c.id, c.employee_profile_id, hp.first_name_ar, hp.last_name_ar
             FROM hr_contracts c
             JOIN hr_employee_profiles hp ON hp.id = c.employee_profile_id
             WHERE c.status = 'active'
               AND c.end_date IS NOT NULL
               AND c.end_date < ?
               AND c.is_archived = 0",
            [$today]
        );

        foreach ($expiredContracts as $c) {
            $this->db->update('hr_contracts', [
                'status'     => 'expired',
                'updated_at' => date('Y-m-d H:i:s'),
            ], '`id` = ?', [(int) $c['id']]);
            $expired++;
        }

        // 2. Alert for contracts expiring within 30 days
        $expiringContracts = $this->db->select(
            "SELECT c.id, c.employee_profile_id, c.end_date,
                    hp.first_name_ar, hp.last_name_ar, hp.employee_number,
                    DATEDIFF(c.end_date, ?) as days_remaining
             FROM hr_contracts c
             JOIN hr_employee_profiles hp ON hp.id = c.employee_profile_id
             WHERE c.status = 'active'
               AND c.end_date IS NOT NULL
               AND c.end_date >= ?
               AND c.end_date <= ?
               AND c.is_archived = 0",
            [$today, $today, $alertDate]
        );

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

            // Insert notification for HR managers
            $this->db->insert('notifications', [
                'type'       => 'hr_contract_expiry',
                'title'      => 'عقد قارب على الانتهاء',
                'message'    => "عقد الموظف {$employeeName} سينتهي خلال {$daysRemaining} يوم (تاريخ الانتهاء: {$c['end_date']})",
                'link'       => '/hr/contracts/' . (int) $c['id'],
                'is_read'    => 0,
                'created_at' => date('Y-m-d H:i:s'),
            ]);
            $alerted++;
        }

        if ($expired > 0 || $alerted > 0) {
            Logger::info("HR Contract Expiry Job: {$expired} expired, {$alerted} near-expiry alerts sent");
        }

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