<?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\Carnets\Services\QRCodeGenerator;
use App\Modules\Members\Services\NationalIdParser;
use App\Shared\Services\PhotoUploadService;

final class RegistrationWizardService
{
    public static function startRegistration(array $playerData): array
    {
        $db = App::getInstance()->db();
        $employee = App::getInstance()->currentEmployee();
        $branch = App::getInstance()->currentBranch();

        $nationalId = trim($playerData['national_id'] ?? '');
        $playerType = $playerData['player_type'] ?? 'non_member';
        $memberId = (int) ($playerData['member_id'] ?? 0);
        $fullNameAr = trim($playerData['full_name_ar'] ?? '');
        $fullNameEn = trim($playerData['full_name_en'] ?? '');
        $dateOfBirth = $playerData['date_of_birth'] ?? null;
        $gender = $playerData['gender'] ?? null;
        $phone = trim($playerData['phone'] ?? '');
        $guardianName = trim($playerData['guardian_name'] ?? '');
        $guardianPhone = trim($playerData['guardian_phone'] ?? '');
        $guardianNationalId = trim($playerData['guardian_national_id'] ?? '');
        $guardianRelationship = trim($playerData['guardian_relationship'] ?? '');

        if ($nationalId !== '' && strlen($nationalId) === 14) {
            $parsed = NationalIdParser::parse($nationalId);
            if ($parsed['is_valid']) {
                $dateOfBirth = $dateOfBirth ?: $parsed['dob'];
                $gender = $gender ?: $parsed['gender'];
            }
        }

        $existingPlayer = null;
        if ($nationalId !== '') {
            $existingPlayer = $db->selectOne(
                "SELECT * FROM sa_players WHERE national_id = ? AND is_archived = 0",
                [$nationalId]
            );
        }
        if (!$existingPlayer && $playerType === 'member' && $memberId > 0) {
            $existingPlayer = $db->selectOne(
                "SELECT * FROM sa_players WHERE member_id = ? AND is_archived = 0",
                [$memberId]
            );
        }

        if ($existingPlayer) {
            $playerId = (int) $existingPlayer['id'];
            $updateData = ['updated_at' => date('Y-m-d H:i:s')];
            if ($fullNameAr !== '' && $existingPlayer['full_name_ar'] !== $fullNameAr) {
                $updateData['full_name_ar'] = $fullNameAr;
            }
            if ($phone !== '' && ($existingPlayer['phone'] ?? '') !== $phone) {
                $updateData['phone'] = $phone;
            }
            if ($guardianName !== '' && ($existingPlayer['guardian_name'] ?? '') !== $guardianName) {
                $updateData['guardian_name'] = $guardianName;
                $updateData['guardian_phone'] = $guardianPhone ?: $existingPlayer['guardian_phone'];
            }
            if (count($updateData) > 1) {
                $db->update('sa_players', $updateData, 'id = ?', [$playerId]);
            }
        } else {
            if ($fullNameAr === '') {
                return ['success' => false, 'error' => 'الاسم بالعربي مطلوب'];
            }

            $maxSerial = $db->selectOne(
                "SELECT MAX(CAST(SUBSTRING(registration_serial, 5) AS UNSIGNED)) as max_num FROM sa_players WHERE registration_serial LIKE 'SAP-%'"
            );
            $nextNum = ((int) ($maxSerial['max_num'] ?? 0)) + 1;
            $serialNumber = 'SAP-' . str_pad((string) $nextNum, 5, '0', STR_PAD_LEFT);

            $playerId = $db->insert('sa_players', [
                'registration_serial'   => $serialNumber,
                'full_name_ar'          => $fullNameAr,
                'full_name_en'          => $fullNameEn ?: null,
                'player_type'           => $playerType,
                'member_id'             => $memberId > 0 ? $memberId : null,
                'national_id'           => $nationalId ?: null,
                'date_of_birth'         => $dateOfBirth ?: null,
                'gender'                => $gender ?: null,
                'phone'                 => $phone ?: null,
                'guardian_name'         => $guardianName ?: null,
                'guardian_phone'        => $guardianPhone ?: null,
                'guardian_national_id'  => $guardianNationalId ?: null,
                'guardian_relationship' => $guardianRelationship ?: null,
                'medical_status'        => 'pending',
                'card_status'           => 'inactive',
                'branch_id'             => $branch ? (int) $branch['id'] : null,
                'created_at'            => date('Y-m-d H:i:s'),
                'updated_at'            => date('Y-m-d H:i:s'),
                'created_by'            => $employee ? (int) $employee->id : null,
            ]);
        }

        $fees = self::calculateFees($playerType);
        $registrationNumber = self::generateRegistrationNumber();

        $registrationId = $db->insert('sa_registrations', [
            'registration_number' => $registrationNumber,
            'player_id'           => $playerId,
            'player_type'         => $playerType,
            'member_id'           => $memberId > 0 ? $memberId : null,
            'national_id'         => $nationalId ?: null,
            'status'              => 'in_progress',
            'registration_fee'    => $fees['registration_fee'],
            'card_fee'            => $fees['card_fee'],
            'form_fee'            => $fees['form_fee'],
            'total_fees'          => $fees['total_fees'],
            'branch_id'           => $branch ? (int) $branch['id'] : null,
            'created_by'          => $employee ? (int) $employee->id : null,
            'created_at'          => date('Y-m-d H:i:s'),
            'updated_at'          => date('Y-m-d H:i:s'),
        ]);

        return [
            'success'             => true,
            'registration_id'     => $registrationId,
            'registration_number' => $registrationNumber,
            'player_id'           => $playerId,
            'fees'                => $fees,
        ];
    }

    public static function capturePhoto(int $registrationId, array $file): array
    {
        $db = App::getInstance()->db();

        $registration = $db->selectOne(
            "SELECT * FROM sa_registrations WHERE id = ? AND status = 'in_progress'",
            [$registrationId]
        );
        if (!$registration) {
            return ['success' => false, 'error' => 'التسجيل غير موجود أو مكتمل'];
        }

        $playerId = (int) $registration['player_id'];
        $result = PhotoUploadService::upload($file, 'sa_players', $playerId);
        if (!$result) {
            return ['success' => false, 'error' => 'فشل رفع الصورة'];
        }

        $db->update('sa_players', [
            'photo_path'  => $result['path'],
            'updated_at'  => date('Y-m-d H:i:s'),
        ], 'id = ?', [$playerId]);

        $db->update('sa_registrations', [
            'photo_captured' => 1,
            'updated_at'     => date('Y-m-d H:i:s'),
        ], 'id = ?', [$registrationId]);

        return [
            'success'    => true,
            'photo_path' => $result['path'],
            'thumbnail'  => $result['thumbnail_path'],
        ];
    }

    public static function selectGroup(int $registrationId, int $groupId, int $months = 1, bool $hasSibling = false): array
    {
        $db = App::getInstance()->db();

        $registration = $db->selectOne(
            "SELECT * FROM sa_registrations WHERE id = ? AND status = 'in_progress'",
            [$registrationId]
        );
        if (!$registration) {
            return ['success' => false, 'error' => 'التسجيل غير موجود أو مكتمل'];
        }

        $group = $db->selectOne(
            "SELECT * FROM sa_groups WHERE id = ? AND status = 'active' AND is_archived = 0",
            [$groupId]
        );
        if (!$group) {
            return ['success' => false, 'error' => 'المجموعة غير موجودة أو غير نشطة'];
        }

        if ((int) $group['current_count'] >= (int) $group['max_capacity']) {
            return ['success' => false, 'error' => 'المجموعة ممتلئة'];
        }

        $playerType = $registration['player_type'];
        $monthlyFee = $playerType === 'member'
            ? (float) $group['monthly_fee_member']
            : (float) $group['monthly_fee_nonmember'];

        $subscriptionAmount = $monthlyFee * max(1, $months);
        $discounts = [];
        $totalDiscount = 0.0;

        // 15% discount for 3-month advance payment
        if ($months >= 3) {
            $advanceRule = $db->selectOne(
                "SELECT * FROM sa_discount_rules WHERE rule_code = 'ADVANCE_3MONTHS_15PCT' AND is_active = 1",
                []
            );
            if ($advanceRule) {
                $discountAmt = $subscriptionAmount * ((float) $advanceRule['discount_value'] / 100);
                $totalDiscount += $discountAmt;
                $discounts[] = ['code' => 'ADVANCE_3MONTHS_15PCT', 'name_ar' => $advanceRule['name_ar'], 'amount' => round($discountAmt, 2)];
            }
        }

        // Sibling discount (if applicable to this academy)
        if ($hasSibling) {
            $siblingRule = $db->selectOne(
                "SELECT * FROM sa_discount_rules WHERE condition_type = 'sibling' AND is_active = 1",
                []
            );
            if ($siblingRule) {
                $acadCode = $siblingRule['academy_code'];
                $applyDiscount = true;
                if ($acadCode) {
                    $program = $db->selectOne("SELECT p.academy_id FROM sa_programs p WHERE p.id = ?", [(int) $group['program_id']]);
                    if ($program) {
                        $academy = $db->selectOne("SELECT code FROM sa_academies WHERE id = ?", [(int) $program['academy_id']]);
                        if (!$academy || $academy['code'] !== $acadCode) {
                            $applyDiscount = false;
                        }
                    }
                }
                if ($applyDiscount) {
                    $remaining = $subscriptionAmount - $totalDiscount;
                    $discountAmt = $remaining * ((float) $siblingRule['discount_value'] / 100);
                    $totalDiscount += $discountAmt;
                    $discounts[] = ['code' => $siblingRule['rule_code'], 'name_ar' => $siblingRule['name_ar'], 'amount' => round($discountAmt, 2)];
                }
            }
        }

        $subscriptionAfterDiscount = round($subscriptionAmount - $totalDiscount, 2);

        $totalFees = (float) $registration['registration_fee']
                   + (float) $registration['card_fee']
                   + (float) $registration['form_fee']
                   + $subscriptionAfterDiscount;

        $db->update('sa_registrations', [
            'group_id'            => $groupId,
            'subscription_amount' => $subscriptionAfterDiscount,
            'total_fees'          => $totalFees,
            'updated_at'          => date('Y-m-d H:i:s'),
        ], 'id = ?', [$registrationId]);

        return [
            'success'             => true,
            'group_name'          => $group['name_ar'],
            'monthly_fee'         => $monthlyFee,
            'months'              => $months,
            'subscription_before_discount' => $subscriptionAmount,
            'discounts'           => $discounts,
            'total_discount'      => round($totalDiscount, 2),
            'subscription_amount' => $subscriptionAfterDiscount,
            'total_fees'          => $totalFees,
        ];
    }

    public static function calculateFees(string $playerType): array
    {
        $db = App::getInstance()->db();

        $regFeeKey = $playerType === 'member' ? 'sa.registration_fee_member' : 'sa.registration_fee_nonmember';

        $regFeeRow = $db->selectOne("SELECT config_value FROM system_config WHERE config_key = ?", [$regFeeKey]);
        $cardFeeRow = $db->selectOne("SELECT config_value FROM system_config WHERE config_key = ?", ['sa.card_fee']);
        $formFeeRow = $db->selectOne("SELECT config_value FROM system_config WHERE config_key = ?", ['sa.form_fee']);

        $registrationFee = (float) ($regFeeRow['config_value'] ?? ($playerType === 'member' ? '100.00' : '50.00'));
        $cardFee = (float) ($cardFeeRow['config_value'] ?? '25.00');
        $formFee = (float) ($formFeeRow['config_value'] ?? '10.00');

        return [
            'registration_fee' => $registrationFee,
            'card_fee'         => $cardFee,
            'form_fee'         => $formFee,
            'total_fees'       => $registrationFee + $cardFee + $formFee,
        ];
    }

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

        $registration = $db->selectOne(
            "SELECT r.*, p.full_name_ar, p.member_id
             FROM sa_registrations r
             INNER JOIN sa_players p ON p.id = r.player_id
             WHERE r.id = ? AND r.status = 'in_progress'",
            [$registrationId]
        );
        if (!$registration) {
            return ['success' => false, 'error' => 'التسجيل غير موجود أو مكتمل'];
        }

        if ((int) $registration['photo_captured'] === 0) {
            return ['success' => false, 'error' => 'يجب التقاط الصورة أولاً'];
        }
        if (empty($registration['group_id'])) {
            return ['success' => false, 'error' => 'يجب اختيار النشاط أولاً'];
        }

        $totalFees = (float) $registration['total_fees'];
        if ($totalFees <= 0) {
            return ['success' => false, 'error' => 'إجمالي الرسوم غير صالح'];
        }

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

        $result = PaymentRequestService::createRequest([
            'member_id'           => $memberId,
            'payment_type'        => 'sports_registration',
            'amount'              => (string) $totalFees,
            'description_ar'      => $description,
            'related_entity_type' => 'sa_registrations',
            'related_entity_id'   => $registrationId,
        ]);

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

        $db->update('sa_registrations', [
            'status'             => 'pending_payment',
            'payment_request_id' => (int) $result['request_id'],
            'payment_status'     => 'pending',
            'updated_at'         => date('Y-m-d H:i:s'),
        ], 'id = ?', [$registrationId]);

        return [
            'success'        => true,
            'request_id'     => $result['request_id'],
            'request_number' => $result['request_number'],
            'amount'         => $totalFees,
        ];
    }

    public static function generateCard(int $registrationId): array
    {
        $db = App::getInstance()->db();
        $employee = App::getInstance()->currentEmployee();
        $branch = App::getInstance()->currentBranch();

        $registration = $db->selectOne(
            "SELECT r.*, p.photo_path, p.full_name_ar
             FROM sa_registrations r
             INNER JOIN sa_players p ON p.id = r.player_id
             WHERE r.id = ? AND r.payment_status = 'paid'",
            [$registrationId]
        );
        if (!$registration) {
            return ['success' => false, 'error' => 'التسجيل غير موجود أو لم يتم الدفع'];
        }

        $existing = $db->selectOne(
            "SELECT id FROM sa_player_cards WHERE registration_id = ? AND is_archived = 0",
            [$registrationId]
        );
        if ($existing) {
            return ['success' => true, 'card_id' => (int) $existing['id'], 'already_exists' => true];
        }

        $cardNumber = self::generateCardNumber();
        $qrData = QRCodeGenerator::encode('SA:' . $cardNumber);

        $cardId = $db->insert('sa_player_cards', [
            'card_number'     => $cardNumber,
            'player_id'       => (int) $registration['player_id'],
            'registration_id' => $registrationId,
            'card_type'       => 'standard',
            'status'          => 'active',
            'qr_code_data'    => $qrData,
            'valid_from'      => date('Y-m-d'),
            'valid_until'     => null,
            'photo_path'      => $registration['photo_path'],
            'issued_by'       => $employee ? (int) $employee->id : null,
            'branch_id'       => $branch ? (int) $branch['id'] : null,
            'created_at'      => date('Y-m-d H:i:s'),
            'updated_at'      => date('Y-m-d H:i:s'),
        ]);

        $db->update('sa_registrations', [
            'card_generated' => 1,
            'updated_at'     => date('Y-m-d H:i:s'),
        ], 'id = ?', [$registrationId]);

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

        EventBus::dispatch('sa.card.issued', [
            'card_id'         => $cardId,
            'card_number'     => $cardNumber,
            'player_id'       => (int) $registration['player_id'],
            'registration_id' => $registrationId,
        ]);

        return [
            'success'     => true,
            'card_id'     => $cardId,
            'card_number' => $cardNumber,
        ];
    }

    public static function completeRegistration(int $registrationId, ?int $paymentId = null): array
    {
        $db = App::getInstance()->db();

        $registration = $db->selectOne(
            "SELECT * FROM sa_registrations WHERE id = ?",
            [$registrationId]
        );
        if (!$registration) {
            return ['success' => false, 'error' => 'التسجيل غير موجود'];
        }

        $db->update('sa_registrations', [
            'status'         => 'completed',
            'payment_status' => 'paid',
            'completed_at'   => date('Y-m-d H:i:s'),
            'updated_at'     => date('Y-m-d H:i:s'),
        ], 'id = ?', [$registrationId]);

        $db->update('sa_players', [
            'registration_fee_paid' => 1,
            'updated_at'            => date('Y-m-d H:i:s'),
        ], 'id = ?', [(int) $registration['player_id']]);

        $groupId = (int) ($registration['group_id'] ?? 0);
        if ($groupId > 0) {
            $existingEnrollment = $db->selectOne(
                "SELECT id FROM sa_group_players WHERE group_id = ? AND player_id = ? AND status IN ('active','pending_payment')",
                [$groupId, (int) $registration['player_id']]
            );

            if (!$existingEnrollment) {
                $employeeId = (int) ($registration['created_by'] ?? 0);
                $enrollmentId = $db->insert('sa_group_players', [
                    'group_id'                => $groupId,
                    'player_id'               => (int) $registration['player_id'],
                    'enrolled_at'             => date('Y-m-d'),
                    'status'                  => 'active',
                    'activated_by_payment_id' => $paymentId,
                    'created_at'              => date('Y-m-d H:i:s'),
                    'updated_at'              => date('Y-m-d H:i:s'),
                    'created_by'              => $employeeId,
                ]);

                $group = $db->selectOne("SELECT current_count, max_capacity FROM sa_groups WHERE id = ?", [$groupId]);
                $newCount = (int) $group['current_count'] + 1;
                $db->update('sa_groups', [
                    'current_count' => $newCount,
                    'is_full'       => $newCount >= (int) $group['max_capacity'] ? 1 : 0,
                    'updated_at'    => date('Y-m-d H:i:s'),
                ], 'id = ?', [$groupId]);
            }
        }

        EventBus::dispatch('sa.registration.completed', [
            'registration_id' => $registrationId,
            'player_id'       => (int) $registration['player_id'],
            'group_id'        => $groupId,
            'total_fees'      => (float) $registration['total_fees'],
        ]);

        return ['success' => true];
    }

    public static function cancelRegistration(int $registrationId, string $reason = ''): array
    {
        $db = App::getInstance()->db();

        $registration = $db->selectOne(
            "SELECT * FROM sa_registrations WHERE id = ? AND status IN ('in_progress', 'pending_payment')",
            [$registrationId]
        );
        if (!$registration) {
            return ['success' => false, 'error' => 'التسجيل غير موجود أو لا يمكن إلغاؤه'];
        }

        $db->update('sa_registrations', [
            'status'        => 'cancelled',
            'cancelled_at'  => date('Y-m-d H:i:s'),
            'cancel_reason' => $reason ?: null,
            'updated_at'    => date('Y-m-d H:i:s'),
        ], 'id = ?', [$registrationId]);

        if (!empty($registration['payment_request_id']) && $registration['payment_status'] === 'pending') {
            PaymentRequestService::cancelRequest((int) $registration['payment_request_id'], $reason ?: 'إلغاء التسجيل');
        }

        return ['success' => true];
    }

    public static function generateRegistrationNumber(): string
    {
        $db = App::getInstance()->db();
        $year = date('Y');
        $prefix = 'SAR-' . $year . '-';

        $row = $db->selectOne(
            "SELECT MAX(CAST(SUBSTRING(registration_number, " . (strlen($prefix) + 1) . ") AS UNSIGNED)) as max_num
             FROM sa_registrations WHERE registration_number LIKE ?",
            [$prefix . '%']
        );

        $next = ((int) ($row['max_num'] ?? 0)) + 1;
        return $prefix . str_pad((string) $next, 6, '0', STR_PAD_LEFT);
    }

    private static function generateCardNumber(): string
    {
        $db = App::getInstance()->db();
        $year = date('Y');
        $prefix = 'SAC-' . $year . '-';

        $row = $db->selectOne(
            "SELECT MAX(CAST(SUBSTRING(card_number, " . (strlen($prefix) + 1) . ") AS UNSIGNED)) as max_num
             FROM sa_player_cards WHERE card_number LIKE ?",
            [$prefix . '%']
        );

        $next = ((int) ($row['max_num'] ?? 0)) + 1;
        return $prefix . str_pad((string) $next, 6, '0', STR_PAD_LEFT);
    }
}
