<?php
declare(strict_types=1);

namespace CronJobs;

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

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

    public function shouldRun(): bool
    {
        // Run after October 1 (month 10+)
        return (int) date('n') >= 10;
    }

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

        // Find unpaid subscriptions that are overdue (past September 30)
        $overdue = $this->db->select(
            "SELECT s.id, s.member_id, s.total_amount, s.financial_year
             FROM subscriptions s
             WHERE s.status = 'pending' AND s.paid_amount = 0"
        );

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

        // Check for 5+ consecutive years of non-payment → drop membership
        $members = $this->db->select(
            "SELECT s.member_id, COUNT(DISTINCT s.financial_year) as unpaid_years
             FROM subscriptions s
             WHERE s.status IN ('pending','overdue') AND s.paid_amount = 0
             GROUP BY s.member_id
             HAVING unpaid_years >= 5"
        );

        foreach ($members as $m) {
            $this->db->update('members', [
                'status'     => 'dropped',
                'updated_at' => date('Y-m-d H:i:s'),
            ], '`id` = ? AND `status` = \'active\'', [(int) $m['member_id']]);

            if ($this->db->pdo()->rowCount() > 0) {
                Logger::warning("Membership dropped due to 5+ years non-payment: member #{$m['member_id']}");
                $processed++;
            }
        }

        return ['processed' => $processed];
    }
}