<?php

namespace App\Http\Controllers\User;
use App\Http\Controllers\Controller;
use App\Models\Admin\Country;
use App\Models\User;
use App\Models\Admin\UserDailySpin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use App\Models\Admin\UserMessage;
use App\Models\referredDist;
use App\Models\commissionSave;

class UserProfileController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('user.pages.profile');

    }
    
    public function user_profile($id)
    {
        $user = User::find($id);
        return view('user.pages.user-profile', compact('user'));
    }



    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
   public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit()
    {
        $countries = Country::orderBy('name', 'ASC')->get();
        return view('user.pages.profile-manage', compact('countries'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
   
    public function update(Request $request, $id)
{
    // return $request;
    $validatedData = $request->validate([
            'name' => 'required|min:3|max:50',
            'image' => 'mimes:jpg,jpeg,png|max:1024',
        ]);
        $user = User::find($id);
        if(Auth::user()->code == NULL){
            $last_ac = User::select('id')->latest()->first();
            if (isset($last_ac)) {
                $code = sprintf('%04d', $last_ac->id + 1000001);
            } else {
                $code = sprintf('%04d', 1000001);
            }
            $user->code = $code;
        }

        $user->name = $request->name;
        $user->phone = $request->phone;
        //$user->age = $request->age;
        
        
        if ($request->has('update_image')) {
            
            $image = $request->file('image');
            if ($image) {
                if(file_exists($user->image)){
                    unlink($user->image);
                }
                $image_name = Str::random(20);
                $ext = strtolower($image->getClientOriginalExtension());
                $image_full_name = $image_name.'.'.$ext;
                $upload_path = 'backend/img/user/';
                $image_url = $upload_path.$image_full_name;
                $success = $image->move($upload_path, $image_full_name);
                $user->image = $image_url;
            }
            $updateType = 'image';
        } elseif ($request->has('update_password')) {
            // Handle password update
            $user->password = Hash::make($request->password);
            $updateType = 'password';
        } else {
            // Your existing logic for other updates
        }
    
        $user->save();
    
        return redirect()->back()->with('message','Data updated successfully!');
    }

    
    
     public function userUpgradePage()
    {
        return view('user.pages.upgrade');
    }
    
    
    public function userUpgrade(Request $request) {
        

    $ac_status = Auth::user()->premium_status;
    
    
    if ($ac_status == 1) {
        return redirect()->back()->with('error', 'Your account has already been Upgraded');
    }
    

    $deposit = Auth::user()->deposit_balance;
    
    $request->session()->forget('verify_error');

    $request->session()->flash('verify_error', true);

    if ($deposit < 1) {
        return redirect()->back();
    }

    $user = User::where('id', Auth::user()->id)->first();
    $user->premium_status = 1;
    $user->save();
    
    $user->decrement('deposit_balance', 1);

    // Create a message for user upgrade
    $upgradeMessage = new UserMessage();
    $upgradeMessage->user_id = $user->id;
    $upgradeMessage->message_title = 'ACCOUNT_VERIFY';
    $upgradeMessage->message = 'Congratulations! Your account has been verified';
    $upgradeMessage->save();

    // Add a success message
    $request->session()->forget('verify_error');
    $request->session()->flash('verify_success', true);
    
          // Handle commissions for the referral chain
    $current_user_id = Auth::user()->id; // Current logged-in user ID
    $referrer_id = Auth::user()->rfered_by; // ID of the user who referred the current user
    $commission_rules = referredDist::pluck('commission', 'generation')->toArray(); // Commission rules per generation

    $generation = 1; // Start from generation 1

    while ($referrer_id && $generation <= count($commission_rules)) {
        // Fetch the referrer
        $referrer = User::where('id', $referrer_id)->first();

        if ($referrer && $referrer->premium_status == 1) {
            // Calculate the commission for the current generation
            $commission_for_referrer = $commission_rules[$generation] ?? 0;

            // Save the commission log in the commissionSave table
            commissionSave::create([
                'user_id' => $referrer->id, // Referrer receiving the commission
                'referred_user_id' => $current_user_id, // The user referred
                'generation' => $generation,
                'commission' => $commission_for_referrer,
                'created_at' => now('Asia/Dhaka'),
                'updated_at' => now('Asia/Dhaka'),
            ]);

            // Update the referrer's earning balance
            $referrer->earning_balance += $commission_for_referrer;
            $referrer->verify_commision_from_refer += $commission_for_referrer;
            $referrer->save();

            // Send a message to the referrer about the earned commission
            $referrerMessage = new UserMessage();
            $referrerMessage->user_id = $referrer->id;
            $referrerMessage->message_title = 'VERIFY COMMISSION RECEIVED';
            $referrerMessage->message = "Congratulations! You have earned a verification commission of $commission_for_referrer for generation $generation.";
            $referrerMessage->save();
        }

        // Move to the next referrer in the chain
        $referrer_id = $referrer ? $referrer->rfered_by : null;

        // Increment generation
        $generation++;
    }

    return redirect()->back();
}

    
    public function add_spin_mark_to_earning(Request $request){
        $user = User::find(Auth::user()->id);
        $user->earning_balance = $user->earning_balance + $request->mark;
        $user->save();
        
        $uspin = new UserDailySpin();
        $uspin->user_id = Auth::user()->id;
        $uspin->spin_amount = $request->mark;
        $uspin->save();
        
        return 'Updated';
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
   
    
     public function destroy($id)
    {
        //
    }
    
   
}
