<?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
{
    // Show VIP details + available coupons
    public function purchase_vip($id)
    {
        $vip = Package::findOrFail($id);

        if ($vip->is_default == 1) {
            return redirect()->route('vip')->with('error', "This VIP is default when you registered in our platform");
        }

        // Check if already active
        $v = Purchase::where('user_id', Auth::id())
            ->where('package_id', $vip->id)
            ->where('validity', 'valid')
            ->first();

        if ($v) {
            return redirect()->route('vip')->with('error', "This VIP already active");
        }

        // Fetch user's active coupons
        $coupons = Coupon::where('user_id', Auth::id())
            ->where('status', 0) // 0 = valid
            ->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'));
    }

    // Confirm VIP purchase
    public function purchaseConfirmation($id, Request $request)
    {
        $package = Package::findOrFail($id);
        $user = Auth::user();

        if ($package->status != 'active') {
            return back()->with('error', "In-Active");
        }

        $price = $package->price;

        // ✅ Apply coupon discount if provided
        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;

                // mark coupon as used
                $coupon->status = 1;
                $coupon->save();
            }
        }

        if ($package->price <= $user->balance) {
            User::where('id', $user->id)->update([
                'balance'=> $user->balance - $price,
            ]);

            // Create purchase record
            $purchase = new Purchase();
            $purchase->user_id = Auth::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);
            $purchase->validity = Carbon::now()->addDays($package->validity);
            $purchase->status = 'active';
            $purchase->save();

            // handle referrals
            $this->distributeReferralCommission($user, $package, $price);

            return redirect()->route('vip')->with('success', "Purchase successful");
        }

        return back()->with('error', "Insufficient Balance");
    }

    // Handle referral commissions
    protected function distributeReferralCommission(User $user, Package $package, $amount)
    {
        $first_ref = User::where('ref_id', $user->ref_by)->first();

        if ($first_ref) {
            $this->payCommission($first_ref, $user, $amount, setting('first_ref'), 'first');

            $second_ref = User::where('ref_id', $first_ref->ref_by)->first();
            if ($second_ref) {
                $this->payCommission($second_ref, $user, $amount, setting('second_ref'), 'second');

                $third_ref = User::where('ref_id', $second_ref->ref_by)->first();
                if ($third_ref) {
                    $this->payCommission($third_ref, $user, $amount, setting('third_ref'), 'third');
                }
            }
        }
    }

    // Helper to create ledger entries
    protected function payCommission($refUser, $fromUser, $amount, $percentage, $step)
    {
        $commission = $amount * $percentage / 100;

        $refUser->update([
            'balance' => $refUser->balance + $commission,
        ]);

        $ledger = new UserLedger();
        $ledger->user_id = $refUser->id;
        $ledger->get_balance_from_user_id = $fromUser->id;
        $ledger->reason = 'commission';
        $ledger->perticulation = 'Commission from ' . $fromUser->username;
        $ledger->amount = $commission;
        $ledger->debit = $commission;
        $ledger->status = 'approved';
        $ledger->step = $step;
        $ledger->date = now()->format('d-m-Y H:i');
        $ledger->save();
    }
}
