<?php
declare(strict_types=1);

use App\Core\Registries\PermissionRegistry;
use App\Core\EventBus;
use App\Modules\Subscriptions\Services\SubscriptionSyncService;

// Menu registered centrally via Members/bootstrap.php under "membership" parent.

PermissionRegistry::register('subscriptions', [
    'subscription.view'           => ['ar' => 'عرض الاشتراكات',  'en' => 'View Subscriptions'],
    'subscription.collect'        => ['ar' => 'تحصيل اشتراك',    'en' => 'Collect Subscription'],
    'subscription.exempt'         => ['ar' => 'إعفاء من اشتراك', 'en' => 'Exempt Subscription'],
    'subscription.generate_batch' => ['ar' => 'توليد اشتراكات',  'en' => 'Generate Batch'],
]);

// ─── Auto-sync subscriptions when a member or dependent is activated ─────────

// New member activation → create member subscription row + all active dependents
EventBus::listen('member.activated', function (array $data) {
    $memberId = (int) ($data['member_id'] ?? 0);
    if ($memberId) {
        SubscriptionSyncService::syncForMember($memberId);
    }
});

// Path A: fee already paid through Cashier → dependent just became active
EventBus::listen('spouse.fee_paid', function (array $data) {
    $spouseId  = (int) ($data['spouse_id']  ?? 0);
    $memberId  = (int) ($data['member_id']  ?? 0);
    if ($spouseId && $memberId) {
        SubscriptionSyncService::syncForDependent('spouse', $spouseId, $memberId);
    }
});

EventBus::listen('child.fee_paid', function (array $data) {
    $childId  = (int) ($data['child_id']  ?? 0);
    $memberId = (int) ($data['member_id'] ?? 0);
    if ($childId && $memberId) {
        SubscriptionSyncService::syncForDependent('child', $childId, $memberId);
    }
});

EventBus::listen('temporary.fee_paid', function (array $data) {
    $tempId   = (int) ($data['temp_id']   ?? 0);
    $memberId = (int) ($data['member_id'] ?? 0);
    if ($tempId && $memberId) {
        SubscriptionSyncService::syncForDependent('temporary', $tempId, $memberId);
    }
});

// Path B: fee = 0 → dependent was set active immediately in the controller store()
// Guard: only act when fee is zero (status already 'active' at dispatch time).
EventBus::listen('spouse.added', function (array $data) {
    if (bccomp((string) ($data['fee'] ?? '0'), '0', 2) === 0) {
        $spouseId = (int) ($data['spouse_id'] ?? 0);
        $memberId = (int) ($data['member_id'] ?? 0);
        if ($spouseId && $memberId) {
            SubscriptionSyncService::syncForDependent('spouse', $spouseId, $memberId);
        }
    }
});

EventBus::listen('child.added', function (array $data) {
    if (bccomp((string) ($data['fee'] ?? '0'), '0', 2) === 0) {
        $childId  = (int) ($data['child_id'] ?? 0);
        $memberId = (int) ($data['member_id'] ?? 0);
        if ($childId && $memberId) {
            SubscriptionSyncService::syncForDependent('child', $childId, $memberId);
        }
    }
});

EventBus::listen('temporary.added', function (array $data) {
    if (bccomp((string) ($data['fee'] ?? '0'), '0', 2) === 0) {
        $tempId   = (int) ($data['temporary_id'] ?? 0);
        $memberId = (int) ($data['member_id']    ?? 0);
        if ($tempId && $memberId) {
            SubscriptionSyncService::syncForDependent('temporary', $tempId, $memberId);
        }
    }
});

// ─── Sync subscriptions after membership transfers ──────────────────────────

// Child separation / full transfer: create subscription rows + mark as paid (fee was collected upfront)
EventBus::listen('transfer.completed', function (array $data) {
    $targetMemberId = (int) ($data['target_member_id'] ?? 0);
    if ($targetMemberId) {
        SubscriptionSyncService::syncForMember($targetMemberId);
        // Find the payment linked to this transfer
        $db = \App\Core\App::getInstance()->db();
        $payment = $db->selectOne(
            "SELECT id FROM payments WHERE related_entity_type = 'transfer_requests' AND related_entity_id = ? AND is_voided = 0 ORDER BY id DESC LIMIT 1",
            [(int) ($data['transfer_id'] ?? 0)]
        );
        $paymentId = $payment ? (int) $payment['id'] : null;
        SubscriptionSyncService::markCurrentYearPaid($targetMemberId, $paymentId);
    }
    // Refresh source member (remove separated child/spouse subscriptions)
    $sourceMemberId = (int) ($data['source_member_id'] ?? 0);
    if ($sourceMemberId) {
        SubscriptionSyncService::refreshForMember($sourceMemberId);
    }
});

// After death transfer: refresh the new membership's subscriptions
EventBus::listen('death.completed', function (array $data) {
    $newMemberId = (int) ($data['new_member_id'] ?? $data['target_member_id'] ?? 0);
    if ($newMemberId) {
        SubscriptionSyncService::refreshForMember($newMemberId);
    }
});