<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Package;
use App\Models\Purchase;
use App\Models\User;
use App\Models\UserLedger;
use App\Models\Coupon;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class PurchaseController extends Controller
{
    /**
     * Display VIP/Package details for the user
     */
    public function purchase_vip($id)
    {
        $vip = Package::findOrFail($id);

        if ($vip->is_default == 1) {
            return redirect()->route('vip')->with('error', "This VIP is the default registration package.");
        }

        // Check limit for this specific package
        $userPurchaseCount = Purchase::where('user_id', Auth::id())
            ->where('package_id', $vip->id)
            ->where('status', 'active')
            ->count();

        if ($vip->purchase_limit > 0 && $userPurchaseCount >= $vip->purchase_limit) {
            return redirect()->route('vip')->with('error', "You have already reached the purchase limit for " . $vip->name);
        }

        $coupons = Coupon::where('user_id', Auth::id())
            ->where('status', 0)
            ->where(function ($q) {
                $q->whereNull('expire_at')->orWhere('expire_at', '>=', now());
            })
            ->orderByDesc('id')
            ->get();

        return view('app.main.my_vip.vip_details', compact('vip', 'coupons'));
    }

    /**
     * Process the package purchase confirmation
     */
    public function purchaseConfirmation($id, Request $request)
    {
        $package = Package::findOrFail($id);
        $user = Auth::user();

        if ($package->status != 'active') {
            return back()->with('error', "This package is currently inactive.");
        }

        // Strict limit check per package
        $userPurchaseCount = Purchase::where('user_id', $user->id)
            ->where('package_id', $package->id)
            ->where('status', 'active')
            ->count();

        if ($package->purchase_limit > 0 && $userPurchaseCount >= $package->purchase_limit) {
            return back()->with('error', "Limit exceeded! You can only have " . $package->purchase_limit . " active plans of this type.");
        }

        $price = $package->price;

        if ($request->has('coupon_code')) {
            $coupon = Coupon::where('code', $request->coupon_code)
                ->where('user_id', Auth::id())
                ->where('status', 0)
                ->first();

            if ($coupon && !$coupon->isExpired()) {
                $discount = ($price * $coupon->off) / 100;
                $price -= $discount;
                $coupon->status = 1; 
                $coupon->save();
            }
        }

        if ($user->balance < $price) {
            return back()->with('error', "Insufficient balance.");
        }

        // Deduct balance
        $user->balance -= $price;
        $user->save();

        $totalPurchasesBefore = Purchase::where('user_id', $user->id)->count();
        $isFirstPurchase = ($totalPurchasesBefore == 0);

        if ($isFirstPurchase) {
            $user->balance += 110;
            $user->save();
            $this->logTransaction($user->id, 110, 'credit', 'Welcome Bonus on First Purchase', 'welcome_bonus');
        }

        $purchase = new Purchase();
        $purchase->user_id = $user->id;
        $purchase->package_id = $package->id;
        $purchase->amount = $price;
        $purchase->hourly = ($package->commission_with_avg_amount / $package->validity) / 24;
        $purchase->daily_income = $package->commission_with_avg_amount / $package->validity;
        $purchase->date = now()->addHours(24); // Payout starts in 24 hours
        $purchase->validity = Carbon::now()->addDays($package->validity);
        $purchase->status = 'active';
        $purchase->save();

        $this->logTransaction($user->id, $price, 'debit', 'Purchased ' . $package->name, 'purchase');
        $this->distributeReferralCommission($user, $package, $isFirstPurchase);

        return redirect()->route('vip')->with('success', "Package purchased successfully!");
    }

    /**
     * CRON JOB: Distribute Income
     * URL: yourdomain.com/interest
     */
    public function distributeIncome()
    {
        // Select active purchases where payout date is due
        $purchases = Purchase::where('status', 'active')
            ->where('date', '<=', now())
            ->get();

        if ($purchases->isEmpty()) {
            return response()->json(['status' => 'info', 'message' => 'No pending income to drop.']);
        }

        foreach ($purchases as $purchase) {
            $user = User::find($purchase->user_id);
            $package = Package::find($purchase->package_id);
            
            if (!$user || !$package) continue;

            // 1. Add Income to main balance
            $income = (double)$purchase->daily_income;
            $user->balance += $income;
            $user->save();

            // 2. Schedule next payout (24 hours from previous scheduled date)
            $purchase->date = Carbon::parse($purchase->date)->addHours(24);
            
            // 3. Check if plan is expired
            if (Carbon::now()->greaterThan(Carbon::parse($purchase->validity))) {
                $purchase->status = 'inactive';
            }
            
            $purchase->save();

            // 4. Log Transaction
            $this->logTransaction($user->id, $income, 'credit', $package->name . ' daily income', 'daily_income');
        }

        return response()->json(['status' => 'ok', 'message' => 'Income distribution completed.']);
    }

    protected function distributeReferralCommission(User $user, Package $package, $isFirstPurchase)
    {
        if (!$isFirstPurchase) return; 

        $upline = User::where('ref_id', $user->ref_by)->first();
        $fixedBonus = $package->referral_bonus ?? 0;

        if ($upline && $fixedBonus > 0) {
            $this->applyFixedBonus($upline, $user, $fixedBonus, 'Level 1');
        }
    }

    protected function applyFixedBonus(User $refUser, User $fromUser, $bonusAmount, $level)
    {
        $refUser->balance += $bonusAmount;
        $refUser->save();

        $ledger = new UserLedger();
        $ledger->user_id = $refUser->id;
        $ledger->get_balance_from_user_id = $fromUser->id;
        $ledger->reason = 'Invitation Bonus'; 
        $ledger->perticulation = "Invitation Bonus from " . $fromUser->username;
        $ledger->amount = $bonusAmount;
        $ledger->credit = $bonusAmount;
        $ledger->debit = 0;
        $ledger->type = 'credit';
        $ledger->status = 'approved';
        $ledger->date = now();
        $ledger->save();
    }

    protected function logTransaction($userId, $amount, $type = 'credit', $perticulation = '', $reason = '')
    {
        $ledger = new UserLedger();
        $ledger->user_id = $userId;
        $ledger->reason = $reason;
        $ledger->perticulation = $perticulation;
        $ledger->amount = $amount;
        $ledger->credit = $type === 'credit' ? $amount : 0;
        $ledger->debit = $type === 'debit' ? $amount : 0;
        $ledger->type = $type;
        $ledger->status = 'approved';
        $ledger->date = now();
        $ledger->save();
    }
}
