<?php
declare(strict_types=1);

namespace CronJobs;

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

class SaCardExpiryJob
{
    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');
        $reminderDate = date('Y-m-d', strtotime('+7 days'));

        $expired = $this->expireCards($today, $ts);
        $reminded = $this->sendExpiryReminders($today, $reminderDate);

        Logger::info("SaCardExpiryJob: {$expired} expired, {$reminded} reminders sent");
        return ['expired' => $expired, 'reminded' => $reminded];
    }

    private function expireCards(string $today, string $ts): int
    {
        $cards = $this->db->select(
            "SELECT id, player_id FROM sa_player_cards
             WHERE status = 'active' AND valid_until IS NOT NULL AND valid_until < ?
             AND is_archived = 0",
            [$today]
        );

        foreach ($cards as $card) {
            $this->db->update('sa_player_cards', [
                'status'     => 'expired',
                'updated_at' => $ts,
            ], 'id = ?', [(int) $card['id']]);
        }

        return count($cards);
    }

    private function sendExpiryReminders(string $today, string $reminderDate): int
    {
        $cards = $this->db->select(
            "SELECT c.id, c.card_number, c.valid_until, c.player_id,
                    p.full_name_ar, p.phone, p.guardian_phone
             FROM sa_player_cards c
             INNER JOIN sa_players p ON p.id = c.player_id
             WHERE c.status = 'active' AND c.valid_until BETWEEN ? AND ?
             AND c.is_archived = 0",
            [$today, $reminderDate]
        );

        $count = 0;
        foreach ($cards as $card) {
            $phone = $card['guardian_phone'] ?: ($card['phone'] ?? '');
            if ($phone === '') {
                continue;
            }

            EventBus::dispatch('sa.card.expiry_reminder', [
                'player_id'   => (int) $card['player_id'],
                'player_name' => $card['full_name_ar'],
                'card_number' => $card['card_number'],
                'expiry_date' => $card['valid_until'],
                'phone'       => $phone,
            ]);
            $count++;
        }

        return $count;
    }
}
