<?php

namespace App\Http\Controllers\user;

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

class PurchaseController extends Controller
{
    public function purchaseConfirmation($id)
    {
        session()->put('pop', true);

        $package = Package::find($id);
        $user = Auth::user();
        $rebate = Rebate::first();

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

        //Maintained vip rules
        $userPackagePurchasedOrNot = Purchase::where('user_id', $user->id)->where('tab', 'vip')->first();
        if (!$userPackagePurchasedOrNot && $package->tab != 'vip') {
            return back()->with('error', "Wrong plan chooses");
        }

        if ($package->tab != 'vip') {
            //Search parent package from purchase table using package_id
            $getPurchaseWithParentPackage = Purchase::where('package_id', $package->package_id)->orderByDesc('id')->first();

            if (!$getPurchaseWithParentPackage) {
                return back()->with('error', "You can't jump vip");
            }
        }

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

                //Purchase Table Create
                $purchase = new Purchase();
                $purchase->user_id = Auth::id();
                $purchase->package_id = $package->id;
                $purchase->tab = $package->tab;
                $purchase->amount = $package->price;
                $purchase->hourly = ($package->commission_with_avg_amount / $package->validity) / 24;
                $purchase->daily_income = $package->commission_with_avg_amount / $package->validity;
                $purchase->return_total = $package->commission_with_avg_amount;
                $purchase->date = now()->addHours(24);
                $purchase->validity = now()->addDays($package->validity);
                $purchase->status = 'active';
                $purchase->save();

                // Referral Commission Distribution
                $this->distributeCommission($user, $package);

                return redirect()->back()->with('success', "Product Buy Successful.");
            } else {
                return back()->with('error', "Deposit balance too low");
            }
        } else {
            return back()->with('error', "This is default vip");
        }
    }

    public function vip_confirm($vip_id)
    {
        $vip = Package::find($vip_id);
        return view('app.main.vip_confirm', compact('vip'));
    }

    protected function ref_user($ref_by)
    {
        return User::where('ref_id', $ref_by)->first();
    }

    /**
     * NEW METHOD: Watch Video & Earn
     */
    public function watchVideo(Request $request, $videoId)
    {
        $user = Auth::user();

        // Get active purchase
        $purchase = Purchase::where('user_id', $user->id)->where('status', 'active')->latest()->first();
        if (!$purchase) {
            return response()->json(['status' => false, 'msg' => '⚠ You have no active package']);
        }

        $limit = $purchase->package->daily_watch_limit ?? 0;

        // Count today's watched videos
        $today = now()->toDateString();
        $watchedToday = DB::table('video_views')
            ->where('user_id', $user->id)
            ->whereDate('watched_at', $today)
            ->count();

        if ($watchedToday >= $limit) {
            return response()->json([
                'status' => false,
                'msg' => "⚠ Daily limit ($limit videos) reached. Come back tomorrow."
            ]);
        }

        // Calculate earning per video
        $earning = $purchase->daily_income / $limit;

        // Save video view
        DB::table('video_views')->insert([
            'user_id' => $user->id,
            'video_id' => $videoId,
            'earned_amount' => $earning,
            'watched_at' => now(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        // Update user balance
        $user->increment('balance', $earning);

        return response()->json([
            'status' => true,
            'earning' => $earning,
            'balance' => $user->balance,
            'msg' => "🎉 Earned $$earning successfully!"
        ]);
    }

    /**
     * Referral Commission Distribution Logic
     */
    protected function distributeCommission($user, $package)
    {
        $first_ref = User::where('ref_id', $user->ref_by)->first();
        if ($first_ref) {
            $amount = $package->price * $package->ref1 / 100;
            $first_ref->increment('balance', $amount);

            $this->saveLedger($first_ref->id, $user->id, 'First Level Commission Received', $amount, 'first');

            $second_ref = User::where('ref_id', $first_ref->ref_by)->first();
            if ($second_ref) {
                $amount = $package->price * $package->ref2 / 100;
                $second_ref->increment('balance', $amount);

                $this->saveLedger($second_ref->id, $user->id, 'Second Level Commission Received', $amount, 'second');

                $third_ref = User::where('ref_id', $second_ref->ref_by)->first();
                if ($third_ref) {
                    $amount = $package->price * $package->ref3 / 100;
                    $third_ref->increment('balance', $amount);

                    $this->saveLedger($third_ref->id, $user->id, 'Third Level Commission Received', $amount, 'third');
                }
            }
        }
    }

    protected function saveLedger($userId, $fromUserId, $text, $amount, $step)
    {
        $ledger = new UserLedger();
        $ledger->user_id = $userId;
        $ledger->get_balance_from_user_id = $fromUserId;
        $ledger->reason = 'commission';
        $ledger->perticulation = $text;
        $ledger->amount = $amount;
        $ledger->debit = $amount;
        $ledger->status = 'approved';
        $ledger->step = $step;
        $ledger->date = date('d-m-Y H:i');
        $ledger->save();
    }
}
