<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Exceptions\GeneralException;
use App\Http\Controllers\Controller;
use App\Repositories\Auth\UserRepository;
use App\Repositories\Auth\UserDeviceTokenRepository;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Hash;

/**
 * Class AuthApiController.
 */
class AuthApiController extends Controller
{
    /**
     * @var UserRepository
     * @var UserDeviceTokenRepository
     */
    protected $userRepository;
    protected $userDeviceTokenRepository;

    /**
     * AuthApiController constructor.
     *
     * @param UserRepository $userRepository
     * @param UserRepository $userDeviceTokenRepository
     */
    public function __construct(UserRepository $userRepository, UserDeviceTokenRepository $userDeviceTokenRepository)
    {
        $this->userRepository = $userRepository;
        $this->userDeviceTokenRepository = $userDeviceTokenRepository;
    }

    /**
     * The user has been signed up.
     *
     * @param Json ApiRequest $request
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws GeneralException
     */
    public function signup(Request $request)
    {
        $response = array();
        $output = array();
		
		$json = file_get_contents('php://input');
		$obj = json_decode($json, TRUE);
		//print_r($obj);die;
        $email = (isset($obj['email']) ? $obj['email'] : '');
        $password = (isset($obj['password']) ? $obj['password'] : '');
		$mobile_country_code = (isset($obj['mobile_country_code']) ? $obj['mobile_country_code'] : '');
        $mobile_number = (isset($obj['mobile_number']) ? $obj['mobile_number'] : '');
        $device_token = (isset($obj['device_token']) ? $obj['device_token'] : '');

        if($email && $password && $mobile_number) {
            //echo '<pre>'; print_r($this->userRepository->findByCondition(array('email'=>$email)));die;
            //$email_exist = array();
            $email_exist = $this->userRepository->findByCondition(array('email'=>$email));
            $mobile_exist = $this->userRepository->findByCondition(array('mobile_number'=>$mobile_number));
            //echo count($email_exist);die;
            if(count($email_exist) == 0 && count($mobile_exist) == 0) {
                $instArr = array(
                                'email'=>$email,
                                'password'=>$password,
                                'mobile_country_code'=>$mobile_country_code,
                                'mobile_number'=>$mobile_number,
                                );
                $user = $this->userRepository->create($instArr);
                if($user) {
                    if($device_token){
                        $devicetokenArr = array(
                                        'user_id'=>$user->id,
                                        'device_token'=>$device_token
                                        );
                        $userdevice = $this->userDeviceTokenRepository->create($devicetokenArr);
                    }
                    /*************email********************/
                    $to = $email;
                    $email_text='   <tr>
                                       <td style="padding: 20px 10px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px;color: #333; ">
                                           <p>Dear <span style="">User</span> </p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                           <p>Thank you for joining DART.</p>
                                           <p style="font-weight:bold;">Your email and mobile verification code as follows:</p>
                                           <!--<p>Email Verification link: <a href="'.url('email_verification.php?code='.$user->email_verification_code).'">Click here to verify email</a></p>-->
                                           <p>Mobile Verification Code: '.$user->mobile_verification_code.'</p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">Please put the verification code in the required fields in APP to confirm and login';
                    $email_text.='      </td>
                                    </tr>
                                    <tr>
                                        <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                           <p>Stay connected with us. We appreciate very much your trust in us.</p>
                                           <p>Please do not hesitate to contact us for any other requests.</p>
                                        </td>
                                    </tr>';
                            //echo $to; die;
                    $data['email_text'] = $email_text;    
                    Mail::send('mail.email_template', $data, function($message) use ($to)
                    {
                        $message->from('testdevloper007@gmail.com', 'DART APP');
                        $message->to($to);
                        $message->subject('Signup mail');
                    });
                    /*************email********************/
                    $status = 100;
                    $statusCode = 200;
                    $message = "Successful, you get an verification mail to your entered email account, please verify and login to your  account";
                    $output = $user;
                } else {
                    $status = 300;
                    $statusCode = 401;
                    $message = "Authentication error";
                }
            } elseif(count($email_exist) > 0){
                if($email_exist[0]->confirmed==0){
                    /*************email********************/
                    $to = $email;
                    $email_text='   <tr>
                                       <td style="padding: 20px 10px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px;color: #333; ">
                                           <p>Dear <span style="">User</span> </p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                           <p>Thank you for joining DART.</p>
                                           <p style="font-weight:bold;">Your email and mobile verification code as follows:</p>
                                           <!--<p>Email Verification link: <a href="'.url('email_verification.php?code='.$email_exist[0]->email_verification_code).'">Click here to verify email</a></p>-->
                                           <p>Mobile Verification Code: '.$email_exist[0]->mobile_verification_code.'</p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">Please put the verification code in the required fields in APP to confirm and login';
                    $email_text.='      </td>
                                    </tr>
                                    <tr>
                                        <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                           <p>Stay connected with us. We appreciate very much your trust in us.</p>
                                           <p>Please do not hesitate to contact us for any other requests.</p>
                                        </td>
                                    </tr>';
                            //echo $to; die;
                    $data['email_text'] = $email_text;    
                    Mail::send('mail.email_template', $data, function($message) use ($to)
                    {
                        $message->from('testdevloper007@gmail.com', 'DART APP');
                        $message->to($to);
                        $message->subject('Signup mail');
                    });
                    /*************email********************/
                    $status = 100;
                    $statusCode = 200;
                    $message = "Email already exist, again you get an verification mail to your entered email account, please verify and login to your  account";
                    $output = $email_exist[0];
                } else {
                    $status = 300;
                    $statusCode = 404;
                    $message = "This email has benn already exist and approved, please login";
                }
            }  elseif(count($mobile_exist) > 0){
                if($mobile_exist[0]->confirmed==0){
                /*************email********************/
                    $to = $email;
                    $email_text='   <tr>
                                       <td style="padding: 20px 10px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px;color: #333; ">
                                           <p>Dear <span style="">User</span> </p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                           <p>Thank you for joining DART.</p>
                                           <p style="font-weight:bold;">Your email and mobile verification code as follows:</p>
                                           <!--<p>Email Verification link: <a href="'.url('email_verification.php?code='.$mobile_exist[0]->email_verification_code).'">Click here to verify email</a></p>-->
                                           <p>Mobile Verification Code: '.$mobile_exist[0]->mobile_verification_code.'</p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">Please put the verification code in the required fields in APP to confirm and login';
                    $email_text.='      </td>
                                    </tr>
                                    <tr>
                                        <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                           <p>Stay connected with us. We appreciate very much your trust in us.</p>
                                           <p>Please do not hesitate to contact us for any other requests.</p>
                                        </td>
                                    </tr>';
                            //echo $to; die;
                    $data['email_text'] = $email_text;    
                    Mail::send('mail.email_template', $data, function($message) use ($to)
                    {
                        $message->from('testdevloper007@gmail.com', 'DART APP');
                        $message->to($to);
                        $message->subject('Signup mail');
                    });
                    /*************email********************/
                    $status = 100;
                    $statusCode = 200;
                    $message = "Mobile number already exist, again you get an verification mail to your entered email account, please verify and login to your  account";
                    $output = $mobile_exist[0];
                } else {
                    $status = 300;
                    $statusCode = 404;
                    $message = "This mobile number has benn already exist and approved, please login";
                }
            }
        } else {
            $status = 300;
            $statusCode = 404;
            $message = "Please fill all the required fields";
        }
        $response = array('status'=>$status, 'message'=>$message, 'result'=>$output);
        
        return response()->json($response);
    }


    /**
     * Resend OTP.
     *
     * @param Json ApiRequest $request
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws GeneralException
     */
    public function resend_otp(Request $request)
    {
        $response = array();
        $output = array();
        
        $json = file_get_contents('php://input');
        $obj = json_decode($json, TRUE);
        $user_id = (isset($obj['user_id']) ? $obj['user_id'] : '');

        if($user_id) {
            $id_exist = $this->userRepository->findByCondition(array('id'=>$user_id));
            if(count($id_exist)>0) {
                $mobile_verification_code = mt_rand(1000,9999);
                $instArr = array(
                                'mobile_verification_code'=>$mobile_verification_code
                                );
                $userupdate = $this->userRepository->updateByCondition(array('id'=>$user_id), $instArr);
                if($userupdate) {
                    $user = $this->userRepository->findByCondition(array('id'=>$user_id));
                    $to = $id_exist[0]->email;
                    $email_text='   <tr>
                                       <td style="padding: 20px 10px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px;color: #333; ">
                                           <p>Dear <span style="">User</span> </p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                           <p>Thank you for joining DART.</p>
                                           <p style="font-weight:bold;">Your email and mobile verification code as follows:</p>
                                           <p>Mobile Verification Code: '.$mobile_verification_code.'</p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">Please put the verification code in the required fields in APP to confirm and login';
                    $email_text.='      </td>
                                    </tr>
                                    <tr>
                                        <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                           <p>Stay connected with us. We appreciate very much your trust in us.</p>
                                           <p>Please do not hesitate to contact us for any other requests.</p>
                                        </td>
                                    </tr>';
                            //echo $to; die;
                    $data['email_text'] = $email_text;    
                    Mail::send('mail.email_template', $data, function($message) use ($to)
                    {
                        $message->from('testdevloper007@gmail.com', 'DART APP');
                        $message->to($to);
                        $message->subject('Signup mail');
                    });
                    /*************email********************/
                    $status = 100;
                    $statusCode = 200;
                    $message = "You get an verification mail to your entered email account, please verify and login to your  account";
                    $output = $user;
                } else {
                    $status = 300;
                    $statusCode = 401;
                    $message = "Some error occured";
                }
            } else {
                    $status = 300;
                    $statusCode = 404;
                    $message = "The user does not exist";
            }
        } else {
            $status = 300;
            $statusCode = 404;
            $message = "Please fill all the required fields";
        }
        $response = array('status'=>$status, 'message'=>$message, 'result'=>$output);
        
        return response()->json($response);
    }


    /**
     * Mobile number OTP verification.
     *
     * @param Json ApiRequest $request
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws GeneralException
     */
    public function mobile_otp_verification(Request $request)
    {
        $response = array();
        $output = array();
        $json = file_get_contents('php://input');
        $obj = json_decode($json, TRUE);
        //print_r($obj);die();
        $otp = $obj['otp'];
        $authorization = explode('Bearer ', $request->header('Authorization'));
        $authorization = end($authorization);

        if($otp && $authorization) {
            $user_authorize = $this->userRepository->findByCondition(array('remember_token'=>$authorization));
            //print_r($authorization);die;
            if(count($user_authorize) > 0) {
                $user = $this->userRepository->findByCondition(array('mobile_verification_code'=>$otp,'remember_token'=>$authorization));
        
                if(count($user) > 0) {
                    $update_arr = [
                        'mobile_verification_code'   => 0,
                        'confirmed' => 1
                    ];
                    $user = $this->userRepository->updateByCondition(array('mobile_verification_code'=>$otp,'remember_token'=>$authorization), $update_arr);
                    if($user) {
                        $status = 100;
                        $statusCode = 200;
                        $message = "Successful";
                    } else {
                        $status = 300;
                        $statusCode = 402;
                        $message = "Sorry something wrong !!!";
                    }
                } else {
                    $status = 300;
                    $statusCode = 401;
                    $message = "OTP Verification code mismatch, click resend OTP";
                }
            } else {
                $status = 300;
                $statusCode = 401;
                $message = "Unauthenticated user";
            }
            
        } else {
            $status = 300;
            $statusCode = 404;
            $message = "Please fill all the required fields";
        }
        $response = array('status'=>$status, 'message'=>$message, 'result'=>$output);
        return response()->json($response);
    }


     /**
     * Forget password.
     *
     * @param Json ApiRequest $request
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws GeneralException
     */
    public function forget_password(Request $request)
    {
        $response = array();
        $output = array();
        $json = file_get_contents('php://input');
        $obj = json_decode($json, TRUE);
        $email = $obj['email'];
        //print_r($jsonRequest);die();
        
        if($email) {
            $new_password = mt_rand(100000,999999);
            $update_arr = [
                'password'   => Hash::make($new_password)
            ];
            $user = $this->userRepository->updateByCondition(array('email'=>$email), $update_arr);
            if($user) {
                /*************email********************/
                $to = $email;
                $email_text='   <tr>
                                   <td style="padding: 20px 10px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px;color: #333; ">
                                       <p>Dear <span style="">User</span> </p>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                       <p>Your new password is : '.$new_password.'</p>
                                       <p>Please login with the new pasword and change..</p>
                                    </td>
                                </tr>';
                $email_text.='  <tr>
                                    <td style="font-family: sans-serif; color: #333; padding: 0px 10px 40px; font-size: 16px; line-height: 30px;">
                                       <p>Stay connected with us. We appreciate very much your trust in us.</p>
                                       <p>Please do not hesitate to contact us for any other requests.</p>
                                    </td>
                                </tr>';
                        //echo $to; die;
                $data['email_text'] = $email_text;    
                Mail::send('mail.email_template', $data, function($message) use ($to)
                {
                    $message->from('testdevloper007@gmail.com', 'DART APP');
                    $message->to($to);
                    $message->subject('Forget password mail');
                });
                /*************email********************/
                $status = 100;
                $statusCode = 200;
                $message = "Your new password is sent to the email provided, please find and login using that.";
            } else {
                $status = 300;
                $statusCode = 402;
                $message = "Unregistered email !!!";
            }
        } else {
            $status = 300;
            $statusCode = 404;
            $message = "Please fill all the required fields";
        }
        $response = array('status'=>$status, 'message'=>$message, 'result'=>$output);
        
        return response()->json($response);
    }

     /**
     * The user has been authenticated.
     *
     * @param Json ApiRequest $request
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws GeneralException
     */
    public function user_authentication(Request $request)
    {
        $response = array();
        $output = array();
        $json = file_get_contents('php://input');
        $obj = json_decode($json, TRUE);
        //print_r($obj);die();
        $email = $obj['email'];
        $password = $obj['password'];
        $device_token = (isset($obj['device_token']) ? $obj['device_token'] : '');
        if($email && $password) {
            $user = $this->userRepository->findByCondition(array('email'=>$email));
            
            if(count($user)>0) {
                /*if($device_token){
                    $devicetokenExist = $this->userDeviceTokenRepository->findByCondition(array('user_id'=>$user[0]->id,'device_tokens'=>$device_token));
                    if($devicetokenExist->count()==0){
                        $devicetokenArr = array(
                                        'user_id'=>$user[0]->id,
                                        'device_token'=>$device_token
                                        );
                        $userdevice = $this->userDeviceTokenRepository->create($devicetokenArr);
                    }
                }*/
                if(Hash::check($obj['password'], $user[0]->password)){
                    if($user[0]->status == 1) {
                        if($user[0]->confirmed == 1) {
                            $status = 100;
                            $statusCode = 200;
                            $message = "Successful";
                            $output = $user[0];
                        } else {
                            $status = 300;
                            $statusCode = 403;
                            $message = "Sorry you are not verify your mobile number. Again you get an verification mail to your entered email account, please verify and login to your  account";
                        }
                    } else {
                        $status = 300;
                        $statusCode = 402;
                        $message = "Sorry you are blocked by Admin, please contact";
                    }
                } else {
                    $status = 300;
                    $statusCode = 401;
                    $message = "Invalid credentials";
                }
            } else {
                $status = 300;
                $statusCode = 401;
                $message = "Invalid credentials";
            }
        } else {
            $status = 300;
            $statusCode = 404;
            $message = "Please fill all the required fields";
        }
        $response = array('status'=>$status, 'message'=>$message, 'result'=>$output);
        
        return response()->json($response);
    }
}
