<?php

namespace App\Services;

use App\Models\User;
use App\Models\AffiliateSetting;
use Illuminate\Support\Facades\Log;

class AffiliateService
{
    /**
     * Process affiliate commission for a sale/transaction
     *
     * @param string $referralCode
     * @param float $saleAmount The original sale amount (before any discounts)
     * @param float|null $discountedAmount The amount after discount (if applicable)
     * @return array Commission details
     */
    public static function processCommission(string $referralCode, float $saleAmount, ?float $discountedAmount = null): array
    {
        // Find affiliate by referral code
        $affiliate = User::where('affiliate_code', $referralCode)
                        ->where('is_affiliate', true)
                        ->first();

        if (!$affiliate) {
            return [
                'success' => false,
                'message' => 'Invalid or inactive affiliate code',
                'commission' => 0
            ];
        }

        // Get affiliate settings
        $settings = AffiliateSetting::getSettings();
        $commissionPercentage = $settings->commission_percentage;

        // Determine the amount to calculate commission from
        // Use discounted amount if provided, otherwise use original amount
        $commissionBaseAmount = $discountedAmount ?? $saleAmount;

        // Calculate commission
        $commission = ($commissionBaseAmount * $commissionPercentage) / 100;

        // Credit commission to affiliate balance
        $affiliate->increment('affiliate_balance', $commission);

        // Increment total referred count
        $affiliate->increment('total_referred');

        Log::info('Affiliate commission processed', [
            'affiliate_id' => $affiliate->id,
            'referral_code' => $referralCode,
            'original_amount' => $saleAmount,
            'discounted_amount' => $discountedAmount,
            'commission_base' => $commissionBaseAmount,
            'commission_percentage' => $commissionPercentage,
            'commission_amount' => $commission
        ]);

        return [
            'success' => true,
            'affiliate_id' => $affiliate->id,
            'commission' => $commission,
            'percentage' => $commissionPercentage,
            'base_amount' => $commissionBaseAmount
        ];
    }

    /**
     * Process affiliate commission for subscription payments
     *
     * @param object $payment Payment model instance
     * @return array Commission details
     */
    public static function processSubscriptionCommission($payment): array
    {
        $user = $payment->user->load('referrer');

        if (!$user->referrer_id || !$user->referrer || !$user->referrer->is_affiliate) {
            return [
                'success' => false,
                'message' => 'No valid affiliate referrer found',
                'commission' => 0
            ];
        }

        $settings = AffiliateSetting::getSettings();
        $commission = $payment->amount * ($settings->commission_percentage / 100);

        $user->referrer->increment('affiliate_balance', $commission);
        $user->referrer->increment('total_referred');

        Log::info('Subscription affiliate commission credited', [
            'payment_id' => $payment->id,
            'affiliate_id' => $user->referrer->id,
            'amount' => $payment->amount,
            'commission' => $commission
        ]);

        return [
            'success' => true,
            'affiliate_id' => $user->referrer->id,
            'commission' => $commission,
            'percentage' => $settings->commission_percentage,
            'base_amount' => $payment->amount
        ];
    }

    /**
     * Validate referral code
     *
     * @param string $referralCode
     * @return array Validation result
     */
    public static function validateReferralCode(string $referralCode): array
    {
        $affiliate = User::where('affiliate_code', $referralCode)
                        ->where('is_affiliate', true)
                        ->first();

        if (!$affiliate) {
            return [
                'valid' => false,
                'message' => 'Invalid referral code'
            ];
        }

        return [
            'valid' => true,
            'affiliate' => $affiliate,
            'message' => 'Valid referral code'
        ];
    }

    /**
     * Calculate discounted price for subscription with referral
     *
     * @param float $originalPrice
     * @param string $referralCode
     * @return array Discount calculation result
     */
    public static function calculateSubscriptionDiscount(float $originalPrice, string $referralCode): array
    {
        $validation = self::validateReferralCode($referralCode);

        if (!$validation['valid']) {
            return [
                'success' => false,
                'message' => $validation['message'],
                'original_price' => $originalPrice,
                'discounted_price' => $originalPrice,
                'discount_percentage' => 0,
                'discount_amount' => 0
            ];
        }

        $settings = AffiliateSetting::getSettings();
        $discountPercentage = $settings->discount_percentage;
        $discountAmount = $originalPrice * ($discountPercentage / 100);
        $discountedPrice = $originalPrice - $discountAmount;

        return [
            'success' => true,
            'original_price' => $originalPrice,
            'discounted_price' => $discountedPrice,
            'discount_percentage' => $discountPercentage,
            'discount_amount' => $discountAmount,
            'affiliate' => $validation['affiliate']
        ];
    }
}
