<?php
declare(strict_types=1);

namespace CronJobs;

use App\Core\Database;
use App\Core\Logger;
use App\Modules\Notifications\Services\CronNotificationService;
use App\Modules\Notifications\Services\NotificationScheduler;

/**
 * Processes time-based notification triggers and sends pending scheduled notifications.
 * Runs daily (or every hour for more granular checks).
 */
class NotificationTriggerCronJob
{
    private Database $db;

    public function __construct(Database $db)
    {
        $this->db = $db;
    }

    public function shouldRun(): bool
    {
        return true; // Runs every cron cycle
    }

    public function run(): array
    {
        $totalProcessed = 0;

        // 1. Process scheduled notifications that are due
        $sendResults = NotificationScheduler::processPendingNotifications(200);
        $totalProcessed += $sendResults['sent'];

        // 2. Run cron-based checks (these schedule new notifications)
        $hour = (int) date('G');

        // Medical expiry — check once daily in the morning
        if ($hour >= 8 && $hour <= 9) {
            $medical = CronNotificationService::checkMedicalExpiry();
            $totalProcessed += $medical['processed'];
        }

        // Subscription payment due — check once daily
        if ($hour >= 9 && $hour <= 10) {
            $subscription = CronNotificationService::checkSubscriptionPaymentDue();
            $totalProcessed += $subscription['processed'];
        }

        // Reservation reminders — check in the evening for tomorrow
        if ($hour >= 17 && $hour <= 18) {
            $reservations = CronNotificationService::checkReservationReminders();
            $totalProcessed += $reservations['processed'];
        }

        // Membership renewal — check once daily
        if ($hour >= 10 && $hour <= 11) {
            $membership = CronNotificationService::checkMembershipRenewal();
            $totalProcessed += $membership['processed'];
        }

        // Coach metrics — run on 1st of each month
        if ((int) date('j') === 1 && $hour >= 11 && $hour <= 12) {
            $coach = CronNotificationService::calculateCoachMetrics();
            $totalProcessed += $coach['processed'];
        }

        Logger::info("NotificationTriggerCronJob completed: sent={$sendResults['sent']}, failed={$sendResults['failed']}, scheduled={$totalProcessed}");

        return ['processed' => $totalProcessed, 'sent' => $sendResults['sent'], 'failed' => $sendResults['failed']];
    }
}
