<?php
declare(strict_types=1);

namespace App\Modules\Sales\Services;

use App\Core\App;

final class ReferralCommissionService
{
    public static function onMemberActivated(int $memberId): void
    {
        $db = App::getInstance()->db();

        $member = $db->selectOne("SELECT id, referred_by_representative_id, membership_value FROM members WHERE id = ?", [$memberId]);
        if (!$member || empty($member['referred_by_representative_id'])) {
            return;
        }

        $repId = (int) $member['referred_by_representative_id'];
        $membershipValue = (float) ($member['membership_value'] ?? 0);
        if ($membershipValue <= 0) {
            return;
        }

        // Don't double-create
        $existing = $db->selectOne(
            "SELECT 1 FROM member_referral_commissions WHERE member_id = ?",
            [$memberId]
        );
        if ($existing) {
            return;
        }

        $rep = $db->selectOne("SELECT id, commission_rate FROM sales_representatives WHERE id = ? AND is_active = 1", [$repId]);
        if (!$rep) {
            return;
        }

        $rate = (float) $rep['commission_rate'];
        $commissionAmount = round($membershipValue * $rate / 100, 2);

        $db->insert('member_referral_commissions', [
            'representative_id' => $repId,
            'member_id'         => $memberId,
            'membership_value'  => $membershipValue,
            'commission_rate'   => $rate,
            'commission_amount' => $commissionAmount,
            'commission_date'   => date('Y-m-d'),
            'status'            => 'pending',
            'created_at'        => date('Y-m-d H:i:s'),
            'updated_at'        => date('Y-m-d H:i:s'),
        ]);
    }
}
