<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Services;

use App\Core\App;
use App\Core\EventBus;
use App\Modules\Cashier\Services\PaymentRequestService;
use App\Modules\SportsActivity\SaConstants;

final class CardRenewalService
{
    public static function renewCard(int $cardId, int $months = 1): array
    {
        $db = App::getInstance()->db();

        $card = $db->selectOne(
            "SELECT c.*, p.full_name_ar, p.member_id, p.player_type
             FROM sa_player_cards c
             JOIN sa_players p ON p.id = c.player_id
             WHERE c.id = ? AND c.is_archived = 0",
            [$cardId]
        );

        if (!$card) {
            return ['success' => false, 'error' => 'الكارت غير موجود'];
        }

        if (!in_array($card['status'], [SaConstants::CARD_EXPIRED, SaConstants::CARD_ACTIVE], true)) {
            return ['success' => false, 'error' => 'حالة الكارت لا تسمح بالتجديد (' . $card['status'] . ')'];
        }

        $feeRow = $db->selectOne(
            "SELECT config_value FROM system_config WHERE config_key = ?",
            ['sa.card_renewal_fee']
        );
        $fee = (float) ($feeRow['config_value'] ?? '25.00');

        if ($fee <= 0) {
            return self::applyRenewal($cardId, $months, null);
        }

        $memberId = (int) ($card['member_id'] ?? 0);
        $description = 'تجديد كارت نشاط رياضي — ' . ($card['full_name_ar'] ?? '');

        $result = PaymentRequestService::createRequest([
            'member_id'           => $memberId,
            'payment_type'        => SaConstants::PAY_TYPE_CARD_RENEWAL,
            'amount'              => (string) $fee,
            'description_ar'      => $description,
            'related_entity_type' => SaConstants::ENTITY_PLAYER_CARDS,
            'related_entity_id'   => $cardId,
        ]);

        if (!$result['success']) {
            return $result;
        }

        return [
            'success'        => true,
            'request_id'     => $result['request_id'],
            'request_number' => $result['request_number'],
            'fee'            => $fee,
            'months'         => $months,
        ];
    }

    public static function completeRenewal(int $cardId, int $paymentId): array
    {
        return self::applyRenewal($cardId, 1, $paymentId);
    }

    private static function applyRenewal(int $cardId, int $months, ?int $paymentId): array
    {
        $db = App::getInstance()->db();

        $card = $db->selectOne(
            "SELECT * FROM sa_player_cards WHERE id = ? AND is_archived = 0",
            [$cardId]
        );

        if (!$card) {
            return ['success' => false, 'error' => 'الكارت غير موجود'];
        }

        $baseDate = ($card['valid_until'] && $card['valid_until'] >= date('Y-m-d'))
            ? $card['valid_until']
            : date('Y-m-d');

        $newValidUntil = date('Y-m-d', strtotime("+{$months} months", strtotime($baseDate)));

        $db->update('sa_player_cards', [
            'status'      => SaConstants::CARD_ACTIVE,
            'valid_until' => $newValidUntil,
            'updated_at'  => date('Y-m-d H:i:s'),
        ], 'id = ?', [$cardId]);

        $db->update('sa_players', [
            'card_status' => SaConstants::CARD_ACTIVE,
            'updated_at'  => date('Y-m-d H:i:s'),
        ], 'id = ?', [(int) $card['player_id']]);

        EventBus::dispatch('sa.card.renewed', [
            'card_id'     => $cardId,
            'player_id'   => (int) $card['player_id'],
            'valid_until' => $newValidUntil,
            'payment_id'  => $paymentId,
        ]);

        return [
            'success'     => true,
            'card_id'     => $cardId,
            'valid_until' => $newValidUntil,
        ];
    }
}
