<?php

namespace App\Http\Controllers\user;

use App\Http\Controllers\Controller;
use App\Models\Video;
use App\Models\VideoView;
use App\Models\Admin;
use App\Models\BonusLedger;
use App\Models\Checkin;
use App\Models\Commission;
use App\Models\Deposit;
use App\Models\Fund;
use App\Models\Improvment;
use App\Models\Mining;
use App\Models\Notice;
use App\Models\Package;
use App\Models\PaymentMethod;
use App\Models\Purchase;
use App\Models\Task;
use App\Models\User;
use App\Models\UserLedger;
use App\Models\VipSlider;
use App\Models\Withdrawal;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{
 public function dashboard()
{
    $user = Auth::user();
    $videos = Video::where('status', 'active')->inRandomOrder()->limit(9)->get();

    $purchase = null;
    if($user) {
        $purchase = Purchase::where('user_id', $user->id)
            ->where('status', 'active')
            ->first();
    }

    return view('app.main.index', compact('user', 'videos', 'purchase'));
}


    // Show video page
    public function watchVideoPage($id)
    {
        $video = Video::findOrFail($id);
        $user = Auth::user();

        if (!$user) {
            return redirect()->route('login')->with('error', 'Please login to watch video.');
        }

        $purchase = Purchase::where('user_id', $user->id)
            ->where('status', 'active')->first();

        if (!$purchase) {
            return redirect()->route('dashboard')->with('error', 'No active package found.');
        }

        return view('app.main.video_watch', compact('video', 'user', 'purchase'));
    }

    // AJAX: mark watched & credit user
    public function watchVideoCredit(Request $request, $videoId)
    {
        $user = Auth::user();
        if (!$user) return response()->json(['status'=>false,'msg'=>'Login required'],401);

        $purchase = Purchase::where('user_id', $user->id)
            ->where('status','active')->first();
        if (!$purchase) return response()->json(['status'=>false,'msg'=>'No active package'],403);

        $package = Package::find($purchase->package_id);
        if (!$package) return response()->json(['status'=>false,'msg'=>'Package missing'],404);

        // Check daily watch limit
        $today = Carbon::today();
        $watchedToday = VideoView::where('user_id',$user->id)
            ->whereDate('created_at',$today)
            ->count();

        $limit = $package->daily_watch_limit ?? 20;
        if ($watchedToday >= $limit) {
            return response()->json(['status'=>false,'msg'=>'Daily watch limit reached']);
        }

        $earning = (float) $package->per_video_earning;

        // Record video view
        VideoView::create([
            'user_id' => $user->id,
            'video_id' => $videoId,
            'earned_amount' => $earning,
            'watched_at' => now(),
        ]);

        // Credit user balance
        $user->balance += $earning;
        $user->save();

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

  public function videos()
{
    $videos = Video::where('status', 'active')->latest()->get();
    $purchase = null;

    if(Auth::check()){
        $purchase = Purchase::where('user_id', Auth::id())
            ->where('status', 'active')
            ->first();
    }

    return view('app.main.videos', compact('videos', 'purchase'));
}

 






    public function return_pay_number($method){
        $method = DB::table('payment_methods')->where('type', $method)->inRandomOrder()->first();
        return response()->json(['status'=> true, 'data'=> $method]);
    }


    public function vip()
    {
        return view('app.main.vip');
    }

    public function purchase_history()
    {
        return view('app.main.purchase_history');
    }






  public function history()
    {
        return view('app.main.history');
    }

    public function history_all()
    {
        return view('app.main.history_all');
    }

    public function ordered()
    {
        return view('app.main.ordered');
    }
   public function myp()
    {
        return view('app.main.myp');
    }

    public function exchange()
    {
        return view('app.main.exchange');
    }




public function checkin(Request $request)
    {
        // check this user already check it
        $check = Checkin::where('user_id', Auth::user()->id)->orderByDesc('id')->first();
        if ($check){
            //check submit today
            $todayCheck = new Carbon($check->date);
            if ($todayCheck->isToday()){
            return redirect()->back()->with('error', 'Spin Check-in balance received.');
            }
        }

        $checkAmount = rand(3,3);

        //Create checkin record
        $model = new Checkin();
        $model->user_id = Auth::id();
        $model->date = Carbon::now();
        $model->amount = $checkAmount;
        $model->save();


        //Added balance in user account
        User::where('id', Auth::user()->id)->update([
//            'balance'=> Auth::user()->balance + setting('checkin_bonus')
            'balance'=> Auth::user()->balance + $checkAmount
        ]);

 return redirect()->back()->with('error', 'Congratulations get daily checkin bonus');
      
    }









    public function vip_commission()
    {
        return view('app.main.vip_commission');
    }

    public function task()
    {
        $user = Auth::user();
        //First Level Users
        $first_level_users = User::where('ref_by', $user->ref_id)->get();
        $first_level_users_ids = [];
        foreach ($first_level_users as $user) {
            array_push($first_level_users_ids, $user->id);
        }

        //Second Level Users
        $second_level_users_ids = [];
        foreach ($first_level_users as $element) {
            $users = User::where('ref_by', $element->ref_id)->get();
            foreach ($users as $user) {
                array_push($second_level_users_ids, $user->id);
            }
        }
        $second_level_users = User::whereIn('id', $second_level_users_ids)->get();

        //Third Level Users
        $third_level_users_ids = [];
        foreach ($second_level_users as $element) {
            $users = User::where('ref_by', $element->ref_id)->get();
            foreach ($users as $user) {
                array_push($third_level_users_ids, $user->id);
            }
        }
        $third_level_users = User::whereIn('id', $third_level_users_ids)->get();
        $team_size = $first_level_users->count() + $second_level_users->count() + $third_level_users->count();

        //Get level wise user ids
        $first_ids = $first_level_users->pluck('id'); //first
        $second_ids = $second_level_users->pluck('id'); //Second
        $third_ids = $third_level_users->pluck('id'); //Third

        $lv1Recharge = Deposit::whereIn('user_id', $first_ids)->where('status', 'approved')->sum('amount');
        $lv2Recharge = Deposit::whereIn('user_id', $second_ids)->where('status', 'approved')->sum('amount');
        $lv3Recharge = Deposit::whereIn('user_id', $third_ids)->where('status', 'approved')->sum('amount');
        $lvTotalDeposit = $lv1Recharge + $lv2Recharge + $lv3Recharge;

        $lv1Withdraw = Withdrawal::whereIn('user_id', $first_ids)->where('status', 'approved')->sum('amount');
        $lv2Withdraw = Withdrawal::whereIn('user_id', $second_ids)->where('status', 'approved')->sum('amount');
        $lv3Withdraw = Withdrawal::whereIn('user_id', $third_ids)->where('status', 'approved')->sum('amount');
        $lvTotalWithdraw = $lv1Withdraw + $lv2Withdraw + $lv3Withdraw;

        $activeMembers1 = Deposit::whereIn('user_id', $first_ids)->where('status', 'approved')->groupBy('user_id')->count();
        $activeMembers2 = Deposit::whereIn('user_id', $second_ids)->where('status', 'approved')->groupBy('user_id')->count();
        $activeMembers3 = Deposit::whereIn('user_id', $third_ids)->where('status', 'approved')->groupBy('user_id')->count();


        $Lv1active = 0;
        $Lv2active = 0;
        $Lv3active = 0;

        foreach ($first_level_users as $uuss) {
            $purchase = Purchase::where('user_id', $uuss->id)->first();
            if ($purchase) {
                $Lv1active = $Lv1active + 1;
            }
        }
        foreach ($second_level_users as $uuss) {
            $purchase = Purchase::where('user_id', $uuss->id)->first();
            if ($purchase) {
                $Lv2active = $Lv2active + 1;
            }
        }
        foreach ($third_level_users as $uuss) {
            $purchase = Purchase::where('user_id', $uuss->id)->first();
            if ($purchase) {
                $Lv3active = $Lv3active + 1;
            }
        }

        $teamTotalActiveMembers = $Lv1active + $Lv2active + $Lv3active;


        return view('app.main.task', compact('team_size', 'teamTotalActiveMembers', 'lv1Recharge', 'lv2Recharge', 'lv3Recharge', 'lv1Withdraw', 'lv2Withdraw', 'lv3Withdraw', 'first_level_users', 'second_level_users', 'third_level_users'));
    }

    public function task_history()
    {
        return view('app.main.task_history');
    }

    public function reword_history()
    {
        return view('app.main.reword_history');
    }

    public function commission()
    {
        return view('app.main.commission');
    }

    public function transfer()
    {
        return view('app.main.transfer');
    }

    public function transfer_request(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'amount'=> 'required'
        ]);
        if ($validate->fails()){
            return redirect()->back()->with('error', 'Amount required.');
        }

        $user = Auth::user();

        if ($user->balance >= $request->amount){

            $user->deposit_balance = $user->deposit_balance + $request->amount;
            $user->balance = $user->balance - $request->amount;
            $user->save();

            return redirect()->back()->with('success', 'Balance transfer successful.');
        }else{
            return redirect()->back()->with('error', 'Withdraw balance low.');
        }
    }

    public function amount_history()
    {
        return view('app.main.amount_history');
    }

 // 🟢 show all packages
public function packages()
{
    $packages = Package::all();
    return view('app.main.packages', compact('packages'));
}

// 🟢 show single package details (earning + limit calculation)
public function package_details($id)
{
    $package = Package::findOrFail($id);

    $dailyEarning   = $package->daily_earning;        // accessor from model
    $perVideoEarning = $package->per_video_earning;  // accessor from model
    $dailyLimit      = $package->daily_watch_limit;

    return view('app.main.package_details', compact('package', 'dailyEarning', 'perVideoEarning', 'dailyLimit'));
}




public function profile()
{
    $user = auth()->user();

    // check user ka active package (latest purchase)
    $activePackage = \DB::table('purchases')
        ->join('packages', 'purchases.package_id', '=', 'packages.id')
        ->where('purchases.user_id', $user->id)
        ->orderBy('purchases.created_at', 'desc')
        ->select(
            'packages.name',
            'purchases.amount as invested_amount', // yaha se actual investment
            'packages.validity',
            'purchases.created_at as start_date',
            \DB::raw("DATE_ADD(purchases.created_at, INTERVAL packages.validity DAY) as expiry_date")
        )
        ->first();

    // Total Invested Amount (jitna bhi invest kiya hoga user ne)
    $totalInvested = \DB::table('purchases')
        ->where('user_id', $user->id)
        ->sum('amount');

    return view('app.main.profile', compact('user', 'activePackage', 'totalInvested'));
}


    public function team()
    {
        return view('app.main.team.index');
    }


    public function setting()
    {
        return view('app.main.mine.setting');
    }

    public function recharge()
    {
        return view('app.main.deposit.index');
    }

    public function recharge_amount($amount, $method)
    {
        $payment_method = PaymentMethod::find($method);
        return view('app.main.deposit.recharge_confirm', compact('payment_method', 'amount'));
    }

    public function deposit_history()
    {

        return view('app.main.deposit_history');
    }
    public function depositSubmit(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'amount' => 'required|numeric',
            'payment_method' => 'required',
            'transaction_id' => 'required',
            'photo' => 'required',
        ]);

        if ($validate->fails()) {
            return back()->withErrors($validate->errors());
        }

        $model = new Deposit();
        $model->user_id = Auth::id();
        $path = uploadImage(false ,$request, 'photo', 'upload/payment/', null, null ,$model->photo);

        $model->photo = $path ?? $model->photo;
        $model->method_name = $request->payment_method;
        $model->order_id = rand(00000,99999);
        $model->transaction_id = $request->transaction_id;
        $model->amount = $request->amount;
        $model->final_amount = $request->amount;
        $model->date = date('d-m-Y H:i:s');
        $model->status = 'pending';
        $model->save();
        return redirect()->route('dashboard')->with('success', 'Deposit Success');
    }

    public function update_profile(Request $request)
    {
        $user = User::find(Auth::id());
        $path = uploadImage(false, $request, 'photo', 'upload/profile/', 200, 200, $user->photo);
        $user->photo = $path ?? $user->photo;

        $user->update();
        return redirect()->route('my.profile')->with('success', 'Successful');
    }

    public function personal_details()
    {
        return view('app.main.update_personal_details');
    }

    public function card()
    {
        $methods = PaymentMethod::where('status', 'active')->where('id', '!=', 4)->get();

        return view('app.main.gateway_setup', compact('methods'));
    }

    public function setupGateway(Request $request)
    {

    

        User::where('id', Auth::id())->update([
            'name' => $request->name,
            'gateway_method' => $request->gateway_method,
            'gateway_number' => $request->gateway_number,
        ]);
        return redirect()->back()->with('success', 'Bank Created.');
    }

    public function reset_bank()
    {
        User::where('id', Auth::id())->update([
            'gateway_method' => null,
            'gateway_number' => null,
        ]);
        return redirect()->back()->with('success', 'Bank Reset.');
    }

    public function invite()
    {
        return view('app.main.invite');
    }

    public function level()
    {
        return view('app.main.level');
    }

   public function checkinn()
    {
        return view('app.main.checkinn');
    }

    public function service()
    {
        return view('app.main.service');
    }


    public function appreview()
    {
        return view('app.main.appreview');
    }

    public function rule()
    {
        return view('app.main.rule');
    }

    public function partner()
    {
        return view('app.main.partner');
    }

    public function climRecord()
    {
        return view('app.main.climRecord');
    }

    public function add_bank()
    {
        return view('app.main.gateway_setup');
    }

    public function add_bank_create()
    {
        return view('app.main.add_bank_create');
    }

    public function setting_change_password(Request $request)
    {
        //Check current password
        $user = User::find(Auth::id());
        if (Hash::check($request->old_password, $user->password)) {
            if ($request->new_password == $request->confirm_password) {
                $user->password = Hash::make($request->new_password);
                $user->update();
                return redirect()->route('login_password')->with('success', 'Password changed');
            } else {
                return redirect()->route('login_password')->with('success', 'Password not match.');
            }
        } else {
            return redirect()->route('login_password')->with('success', 'Password not match');
        }
    }

    public function confirm_submit(Request $request)
    {
        $data = $request->all();
        $model = new Deposit();
        $model->user_id = $data['ui'];
        $model->method_name = $data['pm'];
        $model->method_number = '01000000000';
        $model->order_id = $data['oid'];
        $model->transaction_id = $data['tid'];
        $model->number = $data['aca'];
        $model->amount = $data['amount'];
        $model->final_amount = $data['amount'];
        $model->usdt = $data['amount'] / setting('rate');
        $model->date = Carbon::now();
        $model->status = 'pending';
        $model->save();
        return response()->json(['status' => true, 'data' => $data]);
    }

    public function download_apk()
    {
        $file = public_path('nordex.apk');
        return response()->file($file, [
            'Content-Type' => 'application/vnd.android.package-archive',
            'Content-Disposition' => 'attachment; filename="nordex.apk"',
        ]);
    }

}







