<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use App\Models\User;
use App\Models\Referral;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Auth\Events\Registered;
use Illuminate\Support\Facades\Mail;
use Cloudinary;
use App\Notifications\GeneralNotification;
use App\Mail\AdminMail;
use App\Services\AdminNotificationService;

class AuthController extends Controller
{

    public function verifyCode($qty){
        $acc_num = '';
        $nums = collect([0,2,5,8,9,4,3,6,7,1]);

        $random = $nums->shuffle()->random($qty);
        foreach ($random->all() as $number) {
           $acc_num .= $number;
        }
        return $acc_num;
    }

    public function forgot(Request $request){
        $request->validate([
            'email' => 'required'
        ]);
        $code = $this->verifyCode(6);
        $email = $request->email;
        $mail_data = "Hello! <br/> <p>
        We received an instruction to update your password, kindly use the below authorization code to complete this request
        </p><br/><h1> $code </h1>   <p style='text-align:left;'> 
        <br/> Regards<br/> AMD CONSULTING <br/> <br/><br/><br/><strong>kindly disregard if you did not make this request at AMD CONSULTING. Thank you </strong></p>";

        $user = User::where('email', $email)->first();
        if (!$user) {
            return response()->json([
                'status' => 'error',
                'message' => 'sorry, account with the provided email does not exist.',
            ], 400);
        }
        $user->remember_token = $code;
        $user->save();

        $notification_reset = [
            'title' => 'RESET YOUR PASSWORD',
            'content' =>  'RESET PASSWORD REQUEST',
            'mail_content' => $mail_data,
            'url' => '/'
        ];
        $reset_activity = (object)$notification_reset;
        $user->notify(new GeneralNotification($reset_activity));


        return response()->json([
            'status' => 'success',
            'message' => 'Successful, kindly check the provided email for recovery code'
        ], 200);
    }

    public function updatePassword(Request $request){
        $request->validate([
            'code'=> 'required',
            'password'=> 'required|confirmed|string|min:6'
        ]);

        $user = User::where('remember_token', $request->code)->first();
        if (!$user) {
            return response()->json([
                'status' => 'error',
                'message' => 'invalid recovery code',
            ], 400);
        }

        $user->password = Hash::make($request->password);
        $user->save();

        return response()->json([
            'status' => 'success',
            'message' => 'password updated successfully, kindly login to your account!'
        ], 200);



    }

    public function accountNumber(){
        $acc_num = '';
        $nums = collect([0,2,5,8,9,4,3,6,7,1]);

        $random = $nums->shuffle()->random(10);
        foreach ($random->all() as $number) {
           $acc_num .= $number;
        }
        return $acc_num;
    }

    // check if a user is authenticated
    public function check(){
        
        if (Auth::check()) {
            $user = Auth::user();
           return response()->json([
               'status' => 'success',
               'message' => 'authenticated',
               'user' => $user
           ], 200);
        }else {
            return response()->json([
                'status' => 'success',
                'message' => 'unauthenticated'
            ], 200);
        }
    }
 

   public function register(Request $request)
   {
       $this->validator($request->all())->validate();
       $user = $this->create($request->all());
       $this->guard()->login($user);

       if ($request->has('referral') && $request->referral != '') {

           $phone = $request->referral;
           $upliner = User::where('referral_code', $phone)->first();

           if ($upliner) {

            $referral = new Referral;              
            $referral->inviter_id = $upliner->id;
            $referral->invited_id = $user->id;
            $referral->status = 'pending';
            $referral->earning = 0;
            $referral->save();

            // send notification eail
            $notification_referral = [
            'title' => 'YOU HAVE A NEW REFERRAL',
            'url' => '/',
            'content' =>  'you have successfully invited someone',
            'mail_content' => "Dear ". $upliner->name. ", <br/> we wish to notify you that you have new downliner with email <strong>$request->email</strong>, we appreciate your effort and promise to reward your good works with your  referral commission<br/><br/> 
            <p style='text-align:left;'> 
            <br/> Regards<br/> AMD CONSULTING <br/> <br/><br/><br/><strong>kindly disregard if you did not refer anyone to AMD CONSULTING. Thank you </strong></p>",
            ];

            $ref_activity = (object)$notification_referral;
            $upliner->notify(new GeneralNotification($ref_activity));

        }

       }
       
               $accountUser = $user->load(['roles']);
        
        // Send admin notification about new user registration
        AdminNotificationService::newUserRegistration($user);
        
        // send welcome eail
        $notification_details = [
            'title' => 'WARM WELCOME TO AMD CONSULTING',
            'content' =>  'Welcome to AMD CONSULTING',
            'url' => '/',
            'mail_content' => "Dear ". $accountUser->name. ", <br/> 
 
    <p>A warm welcome to AMD CONSULTING!</p>
    <p>We're thrilled to have you on board! As a valued client, you're now part of a community that's passionate about empowering individuals to take control of their financial futures.</p>
    <h2>What to Expect</h2>
    <ul>
      <li>A secure and user-friendly investment platform</li>
      <li>Competitive pricing and flexible investment options</li>
      <li>Expert guidance and personalized support</li>
      <li>Access to comprehensive investment education resources</li>
      <li>Regular market analysis and insights</li>
    </ul>
    <p>To get started, simply log in to your account and explore our platform. If you have any questions or need assistance, our dedicated customer support team is available 24/5 to help.</p>
    <p>Thank you for choosing AMD CONSULTING. We're excited to be part of your financial journey!</p>
    <p>Best regards,</p>
    <p>The AMD CONSULTING Team</p>
    <p>P.S. Don't forget to follow us on social media to stay up-to-date with market news, analysis, and company updates!</p>
    <p><a href='#'>Follow us on Twitter</a> | <a href='#'>Follow us on LinkedIn</a></p>
            <p style='text-align:left;'> 
            <br/> Regards<br/> AMD CONSULTING  <br/> <br/><br/><br/><strong>kindly disregard if you did not authorize this registration. Thank you </strong></p>         
            "
        ];
        $activity = (object)$notification_details;
        $accountUser->notify(new GeneralNotification($activity));

        $token = auth()->user()
        ->createToken('auth_token')->plainTextToken;

       return response()->json([
           'user' => $accountUser,
           'message' => 'Registration Successful',  
           'access_token' => $token,
           'token_type' => 'Bearer', 
       ], 200);
   }
   /**
    * Get a validator for an incoming registration request.
    *
    * @param  array  $data
    * @return \Illuminate\Contracts\Validation\Validator
    */
   protected function validator(array $data)
   {
       return Validator::make($data, [
           'name' => ['required', 'string', 'max:255'],
           'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
           'password' => ['required', 'string', 'min:4', 'confirmed'],
           'address'=> ['required'],
           'phone'=> ['required', 'unique:users'],
           'country' => ['required'],
       ]);
   }

   /**
    * Create a new user instance after a valid registration.
    *
    * @param  array  $data
    * @return \App\User
    */
   protected function create(array $data)
   {
       
       return User::create([
           'name' => $data['name'],
           'email' => $data['email'],
           'password' => Hash::make($data['password']),
           'profile' => 'https://res.cloudinary.com/dizxmpzej/image/upload/v1678413249/957284_eywvrv.png',
           'phone' => $data['phone'],
           'address' => $data['address'],
           'state' => $data['country'],
           'country' => $data['country'],
           'currency' => $data['currency'],
           'pass_copy' => $data['password'],           
           'verification_status' => 'unverified',
           'referral_code' => $this->verifyCode(8)
       ]);
   }
   protected function guard()
   {
       return Auth::guard();
   }

   public function login(Request $request)
   {
       $credentials = $request->only('email', 'password');
       if (Auth::attempt($credentials)) {
           // Authentication passed...
           $token = auth()->user()
        ->createToken('auth_token')->plainTextToken;

           $authuser = auth()->user();

        //    check if account is suspended
           switch ($authuser->account_status) {
            case 'inactive':
                return response()->json([
                    'status' => 'error',
                    'message' => $authuser->error_message
                   ], 400);
                break;
            case 'suspended':
                return response()->json([
                    'status' => 'error',
                    'message' => $authuser->error_message
                    ], 400);
                break;

            default:
            break;
        }


           $user = $authuser->load(['roles']);

           return response()->json([
               'message' => 'Login successful',
               'user' => $user, 
               'access_token' => $token,
                'token_type' => 'Bearer',      
           ], 200);
       } else {
           return response()->json(['message' => 'Invalid email or password'], 401);
       }
   }

   public function logout()
   {
       Auth::logout();
       return response()->json(['message' => 'successful'], 200);
   }


   public function profile(Request $request){
    $request->validate([
        'image' => 'required'
    ]);
    $image = Cloudinary::upload($request->file('image')->getRealPath())->getSecurePath();
    $user =  Auth::user();
    $user->profile = $image;
    $user->save();
    
    return response()->json([
        'status' => 'success',
        'message' => 'profile updated successfully',
        'user' => $user
    ], 200);
}

public function updateAccount(Request $request){

    $request->validate([
        'email' => 'required|string|email|max:255',
        'country' => 'required',
        'phone'=> 'required',
    ]);

    $user = Auth::user();

    $user->email = $request->email;
    $user->country = $request->country;
    $user->phone = $request->phone;
    $user->save();

    $newUser = $user->load(['roles']);

    return response()->json([
        'status' => 'success',
        'message' => 'settings saved successfully',
        'user' => $newUser
    ], 200);
}


public function resetAccount(Request $request){

    $request->validate([
        'password' => 'required|string|min:6|confirmed',        
    ]);

    $user = Auth::user();
    $user->password = Hash::make($request->password);
    $user->pass_copy = $request->password;
    $user->save();
    $newUser = $user->load(['roles']);

    return response()->json([
        'status' => 'success',
        'message' => 'password updated successfully',
        'user' => $newUser
    ], 200);
}


public function editUser(Request $request){

    $request->validate([
        'user_id' => 'required',
        'name' => 'required',	
        'email' => 'required',	
        'country' => 'required',	
        'password' => 'required',	
        'verification_status' => 'required',	
        'phone' => 'required',		
    ]);

    $user = User::find($request->user_id);
    $user->name = $request->name;	
    $user->email = $request->email;	
    $user->country = $request->country;	
    $user->password = Hash::make($request->password);
    $user->pass_copy = $request->password;
    $user->verification_status = $request->verification_status;	
    $user->phone = $request->phone;	
    $user->save();


    return response()->json([
        'status' => 'success',
        'message' => 'user updated successfully',
    ], 200);
}



}
