<?php

namespace App\Http\Controllers\Business;

use App\Http\Controllers\Controller;
use App\Models\Referral;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class ReferralController extends Controller
{
    /**
     * Display referral dashboard
     */
    public function index()
    {
        $business = auth()->user()->business;

        // Get or create referral code
        $referralCode = $business->referral_code;
        if (!$referralCode) {
            $referralCode = 'REF-' . strtoupper(Str::random(8));
            $business->update(['referral_code' => $referralCode]);
        }

        // Get referral stats
        $referrals = Referral::where('referrer_business_id', $business->id)
            ->with('referredBusiness')
            ->orderBy('created_at', 'desc')
            ->get();

        $stats = [
            'total_referrals' => $referrals->count(),
            'successful' => $referrals->where('status', 'successful')->count(),
            'pending' => $referrals->where('status', 'pending')->count(),
            'total_earnings' => $referrals->where('status', 'successful')->sum('commission_amount'),
        ];

        return view('business.referral.index', compact('referralCode', 'referrals', 'stats'));
    }

    /**
     * Generate new referral code
     */
    public function generateCode()
    {
        $business = auth()->user()->business;

        $newCode = 'REF-' . strtoupper(Str::random(8));

        $business->update(['referral_code' => $newCode]);

        return response()->json([
            'success' => true,
            'code' => $newCode,
            'message' => 'New referral code generated!'
        ]);
    }

    /**
     * Track referral click
     */
    public function trackClick(Request $request, $code)
    {
        $business = Business::where('referral_code', $code)->first();

        if (!$business) {
            return redirect()->route('business.register');
        }

        // Store referral code in session
        session(['referral_code' => $code]);

        return redirect()->route('business.register')
            ->with('referral_message', 'You were referred by ' . $business->business_name);
    }

    /**
     * Process referral
     */
    public function process(Request $request)
    {
        $referralCode = session('referral_code');

        if (!$referralCode) {
            return;
        }

        $referrerBusiness = Business::where('referral_code', $referralCode)->first();

        if (!$referrerBusiness) {
            return;
        }

        $newBusiness = auth()->user()->business;

        Referral::create([
            'referrer_business_id' => $referrerBusiness->id,
            'referred_business_id' => $newBusiness->id,
            'referral_code' => $referralCode,
            'status' => 'pending',
            'commission_rate' => 10, // 10% commission
        ]);

        session()->forget('referral_code');
    }

    /**
     * Mark referral as successful (called when payment is made)
     */
    public function markSuccessful($referredBusinessId, $amount)
    {
        $referral = Referral::where('referred_business_id', $referredBusinessId)
            ->where('status', 'pending')
            ->first();

        if (!$referral) {
            return;
        }

        $commission = $amount * ($referral->commission_rate / 100);

        $referral->update([
            'status' => 'successful',
            'commission_amount' => $commission,
            'completed_at' => now()
        ]);
    }
}
