<?php
declare(strict_types=1);

namespace CronJobs;

use App\Core\Database;
use App\Core\Logger;
use App\Modules\Subscriptions\Services\OverdueFineApplicator;

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

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

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

        // Mark unpaid subscriptions as overdue (past grace period)
        $currentFY = self::currentFinancialYear();
        $overdue = $this->db->select(
            "SELECT s.id FROM subscriptions s
             WHERE s.status = 'pending' AND s.paid_amount = 0 AND s.financial_year < ?",
            [$currentFY]
        );

        foreach ($overdue as $sub) {
            $this->db->update('subscriptions', [
                'status'     => 'overdue',
                'updated_at' => date('Y-m-d H:i:s'),
            ], '`id` = ? AND `status` = \'pending\'', [(int) $sub['id']]);
            $processed++;
        }

        // Delegate fine calculation, distribution, and drop logic to OverdueFineApplicator
        $result = OverdueFineApplicator::run();
        $processed += $result['fines_applied'] + $result['members_dropped'];

        // Expire reinstatement windows (12-month rule)
        $expireResult = OverdueFineApplicator::expireReinstatements();
        $processed += $expireResult['expired'];

        if (!empty($result['errors'])) {
            foreach ($result['errors'] as $err) {
                Logger::error("OverdueFineJob: " . $err);
            }
        }

        return [
            'processed'        => $processed,
            'fines_applied'    => $result['fines_applied'],
            'members_dropped'  => $result['members_dropped'],
            'reinstatements_expired' => $expireResult['expired'],
        ];
    }

    private static function currentFinancialYear(): string
    {
        $month = (int) date('n');
        $year = (int) date('Y');
        return $month >= 7 ? $year . '/' . ($year + 1) : ($year - 1) . '/' . $year;
    }
}