<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Services;

use App\Core\App;
use App\Core\Logger;
use App\Modules\Payments\Services\PaymentService;

final class SaPaymentService
{
    public static function paySubscription(int $subscriptionId, string $paymentMethod, array $extra = []): array
    {
        $db = App::getInstance()->db();

        $subscription = $db->selectOne(
            "SELECT s.*, p.full_name_ar as player_name, p.member_id, p.player_type,
                    g.name_ar as group_name
             FROM sa_subscriptions s
             LEFT JOIN sa_players p ON p.id = s.player_id
             LEFT JOIN sa_groups g ON g.id = s.group_id
             WHERE s.id = ?",
            [$subscriptionId]
        );

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

        if ($subscription['payment_status'] === 'paid') {
            return ['success' => false, 'error' => 'الاشتراك مدفوع بالفعل'];
        }

        $amount = (string) ($subscription['final_amount'] ?? '0.00');
        if (bccomp($amount, '0.01', 2) < 0) {
            return ['success' => false, 'error' => 'مبلغ الاشتراك غير صالح'];
        }

        $memberId = !empty($subscription['member_id']) ? (int) $subscription['member_id'] : null;
        $description = 'اشتراك نشاط رياضي';
        if (!empty($subscription['group_name'])) {
            $description .= ' — ' . $subscription['group_name'];
        }

        $paymentData = [
            'member_id'           => $memberId,
            'amount'              => $amount,
            'payment_type'        => 'activity_subscription',
            'payment_method'      => $paymentMethod,
            'related_entity_type' => 'sa_subscriptions',
            'related_entity_id'   => $subscriptionId,
            'description'         => $description,
            'check_number'        => $extra['check_number'] ?? null,
            'check_bank'          => $extra['check_bank'] ?? null,
            'check_date'          => $extra['check_date'] ?? null,
            'visa_reference'      => $extra['visa_reference'] ?? null,
            'transfer_reference'  => $extra['transfer_reference'] ?? null,
            'transfer_bank'       => $extra['transfer_bank'] ?? null,
            'treasury_id'         => $extra['treasury_id'] ?? null,
            'session_id'          => $extra['session_id'] ?? null,
        ];

        if ($memberId === null && !empty($subscription['player_name'])) {
            $paymentData['guest_name'] = $subscription['player_name'];
        }

        $result = PaymentService::processPayment($paymentData);

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

        $db->update('sa_subscriptions', [
            'payment_status' => 'paid',
            'paid_at'        => date('Y-m-d H:i:s'),
            'paid_amount'    => (float) $amount,
            'payment_id'     => $result['payment_id'],
            'receipt_id'     => $result['receipt_id'],
            'receipt_number' => $result['receipt_number'],
            'updated_at'     => date('Y-m-d H:i:s'),
        ], 'id = ?', [$subscriptionId]);

        return [
            'success'        => true,
            'payment_id'     => $result['payment_id'],
            'receipt_id'     => $result['receipt_id'],
            'receipt_number' => $result['receipt_number'],
            'amount'         => $amount,
        ];
    }

    public static function payBooking(int $bookingId, string $paymentMethod, array $extra = []): array
    {
        $db = App::getInstance()->db();

        $booking = $db->selectOne(
            "SELECT b.*, p.full_name_ar as booker_name_resolved, p.member_id, p.player_type
             FROM sa_bookings b
             LEFT JOIN sa_players p ON p.id = b.booker_id AND b.booker_type = 'player'
             WHERE b.id = ?",
            [$bookingId]
        );

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

        if ($booking['payment_status'] === 'paid') {
            return ['success' => false, 'error' => 'الحجز مدفوع بالفعل'];
        }

        $amount = (string) ($booking['total_amount'] ?? '0.00');
        if (bccomp($amount, '0.01', 2) < 0) {
            return ['success' => false, 'error' => 'مبلغ الحجز غير صالح'];
        }

        $memberId = !empty($booking['member_id']) ? (int) $booking['member_id'] : null;
        $paymentType = ($booking['booking_type'] === 'hourly') ? 'hourly_booking' : 'activity_subscription';

        $paymentData = [
            'member_id'           => $memberId,
            'amount'              => $amount,
            'payment_type'        => $paymentType,
            'payment_method'      => $paymentMethod,
            'related_entity_type' => 'sa_bookings',
            'related_entity_id'   => $bookingId,
            'description'         => 'حجز رياضي — ' . ($booking['booker_name'] ?? $booking['booker_name_resolved'] ?? ''),
            'check_number'        => $extra['check_number'] ?? null,
            'check_bank'          => $extra['check_bank'] ?? null,
            'check_date'          => $extra['check_date'] ?? null,
            'visa_reference'      => $extra['visa_reference'] ?? null,
            'transfer_reference'  => $extra['transfer_reference'] ?? null,
            'transfer_bank'       => $extra['transfer_bank'] ?? null,
            'treasury_id'         => $extra['treasury_id'] ?? null,
            'session_id'          => $extra['session_id'] ?? null,
        ];

        if ($memberId === null && !empty($booking['booker_name'])) {
            $paymentData['guest_name'] = $booking['booker_name'];
        }

        $result = PaymentService::processPayment($paymentData);

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

        $db->update('sa_bookings', [
            'payment_status' => 'paid',
            'payment_id'     => $result['payment_id'],
            'receipt_id'     => $result['receipt_id'],
            'receipt_number' => $result['receipt_number'],
            'updated_at'     => date('Y-m-d H:i:s'),
        ], 'id = ?', [$bookingId]);

        return [
            'success'        => true,
            'payment_id'     => $result['payment_id'],
            'receipt_id'     => $result['receipt_id'],
            'receipt_number' => $result['receipt_number'],
            'amount'         => $amount,
        ];
    }

    public static function voidSubscriptionPayment(int $subscriptionId): array
    {
        $db = App::getInstance()->db();

        $subscription = $db->selectOne(
            "SELECT * FROM sa_subscriptions WHERE id = ?",
            [$subscriptionId]
        );

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

        $paymentId = (int) ($subscription['payment_id'] ?? 0);
        if ($paymentId < 1) {
            return ['success' => false, 'error' => 'لا يوجد دفعة مرتبطة'];
        }

        $result = PaymentService::voidPayment($paymentId, 'إلغاء اشتراك نشاط رياضي');

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

        $db->update('sa_subscriptions', [
            'payment_status' => 'unpaid',
            'paid_at'        => null,
            'paid_amount'    => null,
            'payment_id'     => null,
            'receipt_id'     => null,
            'receipt_number' => null,
            'updated_at'     => date('Y-m-d H:i:s'),
        ], 'id = ?', [$subscriptionId]);

        return ['success' => true];
    }
}
