<?php
declare(strict_types=1);

namespace CronJobs;

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

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

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

    public function run(): array
    {
        $ts = date('Y-m-d H:i:s');
        $today = date('Y-m-d');

        $marked = $this->markOverdue($today, $ts);
        $notified = $this->notifyOverdue();

        Logger::info("SaOverdueSubscriptionJob: {$marked} marked overdue, {$notified} notified");
        return ['marked_overdue' => $marked, 'notified' => $notified];
    }

    private function markOverdue(string $today, string $ts): int
    {
        $subs = $this->db->select(
            "SELECT id FROM sa_subscriptions
             WHERE payment_status = 'unpaid' AND period_end < ?",
            [$today]
        );

        foreach ($subs as $sub) {
            $this->db->update('sa_subscriptions', [
                'payment_status' => 'overdue',
                'updated_at'     => $ts,
            ], 'id = ?', [(int) $sub['id']]);
        }

        return count($subs);
    }

    private function notifyOverdue(): int
    {
        $subs = $this->db->select(
            "SELECT s.id, s.player_id, s.amount, s.period_start, s.period_end,
                    p.full_name_ar, p.phone, p.guardian_phone
             FROM sa_subscriptions s
             INNER JOIN sa_players p ON p.id = s.player_id
             WHERE s.payment_status = 'overdue' AND s.overdue_notified_at IS NULL",
            []
        );

        $count = 0;
        $ts = date('Y-m-d H:i:s');

        foreach ($subs as $sub) {
            $phone = $sub['guardian_phone'] ?: ($sub['phone'] ?? '');
            if ($phone === '') {
                $this->db->update('sa_subscriptions', ['overdue_notified_at' => $ts], 'id = ?', [(int) $sub['id']]);
                continue;
            }

            EventBus::dispatch('sa.subscription.overdue', [
                'player_id'   => (int) $sub['player_id'],
                'player_name' => $sub['full_name_ar'],
                'amount'      => $sub['amount'],
                'period'      => $sub['period_start'] . ' - ' . $sub['period_end'],
                'phone'       => $phone,
            ]);

            $this->db->update('sa_subscriptions', ['overdue_notified_at' => $ts], 'id = ?', [(int) $sub['id']]);
            $count++;
        }

        return $count;
    }
}
