<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends CI_Controller {

	public function __construct() {
		parent::__construct();
		$this->load->library('email');
		$this->load->model('API_CRUD_model');		
	}
	
	public function Login(){


		if(isset($_REQUEST['email']))
		{
			$email=$_REQUEST['email'];
			$password= isset($_REQUEST['password']) ? $_REQUEST['password'] : '';
			$type = isset($_REQUEST['type']) ? $_REQUEST['type'] : '1';

			if($type == '2' OR $type == '4')
			{
				$where='email="'.$email.'"';
				$user_data = $this->API_CRUD_model->getById($where,'user');
				
				if($user_data){
					$user_data->image =  get_image_path($user_data->image,'user');		
					if($user_data->id){
						$response=array('status'=>200,'message'=>'Successfully login','result'=>array($user_data));
					}else{
						$r=array();
						$response=array('status'=>400,'message'=>'Username and pasword is wrong');
					}
				}
				else
				{
					// Facebook User Register 
					$email=$_REQUEST['email'];
					$fullname = isset($_REQUEST['fullname']) ? $_REQUEST['fullname'] : '';
					$mobile= isset($_REQUEST['mobile'])  ? $_REQUEST['mobile'] : '';

					$image = '';
					if(isset($_FILES['image']['name']))
					{
						$image = $this->API_CRUD_model->imageupload($_FILES['image'],'image', FCPATH . 'assets/images/user');
					}

					$data = array(
						'fullname' => $fullname, 
						'email' => $_REQUEST['email'],
						'type' => $type,
						'mobile' => $mobile,
						'image' => $image
					);
	
					$user_id=$this->API_CRUD_model->insert($data,'user');
					unset($data['password']);	
					$data['id']= $user_id;
					$data['image'] = get_image_path($data['image'],'user');	
					$response=array('status'=>200,'message'=>'Add user sucessfuly','result'=>array($data));
					echo json_encode($response);exit;
				}
			}else
			{
				$where='password="'.$password.'" and email="'.$email.'"';
				$user_data = $this->API_CRUD_model->getById($where,'user'); 
				
			if(isset($user_data->id)){
					$user_data->image =  get_image_path($user_data->image,'user');
					$response=array('status'=>200,'message'=>'Successfully login','result'=>array($user_data));
				}else{
					$r=array();
					$response=array('status'=>400,'message'=>'Username and pasword is wrong');
				}
			}
		}else
		{
			$response=array('status'=>400,'message'=>'Please enter email and password ');
		}
		echo json_encode($response);exit;
	}	
	
	public function registration(){		
		if(isset($_REQUEST['fullname']) && isset($_REQUEST['email']) && isset($_REQUEST['password']) && isset($_REQUEST['mobile']))
		{
			$fullname= $_REQUEST['fullname'];
			$email= $_REQUEST['email'];
			$password= $_REQUEST['password'];
			$mobile= $_REQUEST['mobile'];

			$where='email="'.$email.'"';
			$emailresult = $this->API_CRUD_model->getById($where,'user'); 

			$where_mobile='mobile="'.$mobile.'"';
			$mobileresult = $this->API_CRUD_model->getById($where_mobile,'user'); 
	
				
			if(isset($emailresult->id)){
				$response=array('status'=>400,'message'=>'Email address already exists.');
				echo json_encode($response);exit;
			}

			if(isset($mobileresult->id)){
				$response=array('status'=>400,'message'=>'Mobile Number already exists.');
				echo json_encode($response);exit;
			}

			$data = array(
				'fullname'=>$fullname,
				'email'=>$email,
				'password'=>$password,
				'mobile'=>$mobile,
				'type'=>1,
			);

			$user_id=$this->API_CRUD_model->insert($data,'user');

			$settinglist = $this->API_CRUD_model->get('','general_setting');
    	    foreach($settinglist as $set){
    	        $setn[$set->key]=$set->value;
    		}

			$where='id ="'.$user_id.'"';
    		$share_user = $this->API_CRUD_model->getById($where,'user');
			$mail['user'] = $share_user;
			$mail['setn'] = $setn;
			$register = $this->load->view("admin/email/register",$mail,true);
			
			$smtpWhere = 'id="1"';
			$smtp_detail = $this->API_CRUD_model->getById($smtpWhere, 'smtp_setting');
			$emailconfig = get_smtp_setting();

			$this->load->library('email',$emailconfig);

			$this->email->from($smtp_detail->from_email, $smtp_detail->from_name);
			$this->email->to($_REQUEST['email']);
			$this->email->set_mailtype('html');
			$this->email->subject('Register');
			$this->email->message($register);
			$this->email->send();

			$response=array('status'=>200,'message'=>'User registration sucessfuly');
			echo json_encode($response);exit;
		}
		else
		{
			$response=array('status'=>400,'message'=>'Please enter all field');
			echo json_encode($response);exit;
		}		
	}
	
	public function profile(){
		if(isset($_REQUEST['user_id']))
		{
			$user_id = $_REQUEST['user_id'];
			$where = 'id="'.$user_id.'" ';
			$result = $this->API_CRUD_model->getById($where,'user');
			if(isset($result->id)){
				if($result->image)
				{
					$result->image = get_image_path($result->image,'user');	
				}

				$where = 'user_id="'.$user_id.'" ';
				$author_result = $this->API_CRUD_model->getById($where,'author');
				if($author_result->image)
				{
					$author_result->image = get_image_path($author_result->image,'author');	
				}				

				$response=array('status'=>200,'message'=>'Record get successfully','result'=>array($result),'author_profile'=>$author_result);
			}else{
				$response=array('status'=>400,'message'=>'Record not found','result'=>array());
			}
			echo json_encode($response);exit;
		}
		else
		{
			$response=array('status'=>400,'message'=>'Please enter required field','result'=>array());
			echo json_encode($response);exit;
		}
	}
	
	public function update_profile(){
		if(isset($_REQUEST['user_id']))
		{
			$user_id = $_REQUEST['user_id'];
			$data = array();


			if(isset($_REQUEST['fullname']) && $_REQUEST['fullname'] != ''){
				$data['fullname'] = $_REQUEST['fullname'];
			}

			if(isset($_REQUEST['mobile']) && $_REQUEST['mobile'] != ''){
				$data['mobile'] = $_REQUEST['mobile'];
			}

			if(isset($_REQUEST['email']) && $_REQUEST['email'] != ''){
				$data['email'] = $_REQUEST['email'];
			}
			
			if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != '')
			{
				$data['image'] = $this->API_CRUD_model->imageupload($_FILES['image'],'image', FCPATH . 'assets/images/user');
			}

			if(isset($_REQUEST['password']))
			{
				$data['password'] = $_REQUEST['password'];
			}
			
			$data['is_updated'] = "1";
			$where = 'id="'.$user_id.'" ';
			$result = $this->API_CRUD_model->update($_REQUEST['user_id'], 'id', $data, 'user');

			if($result){
				$response=array('status'=>200,'message'=>'User profile update sucessfuly','id'=>(string)$user_id);
				echo json_encode($response);
			}else{
				$response=array('status'=>400,'message'=>'User profile fail');
				echo json_encode($response);
			}
		}else
		{
			$response=array('status'=>400,'message'=>'Please enter all field');
			echo json_encode($response);	
		}
	}

	public function send_mail($message,$email,$subject)
	{
		$smtpWhere='id="1"';
		$smtp_detail = $this->API_CRUD_model->getById($smtpWhere,'smtp_setting');
		$emailconfig = get_smtp_setting();
	    // $this->load->library('email',$emailconfig);
		$this->email->initialize($emailconfig);
		$this->email->from($smtp_detail->from_email, $smtp_detail->from_name);
		$this->email->to($email);
		$this->email->set_mailtype('html');
		$this->email->subject($subject);
		$this->email->message($message);  
		$restul = $this->email->send();
	}
    
    public function forgotpassword(){
        
		if(isset($_REQUEST['email']))
		{
		    $settinglist = $this->API_CRUD_model->get('','general_setting');
    	    foreach($settinglist as $set){
    	        $setn[$set->key]=$set->value;
    		}
    	
    		$where='email ="'.$_REQUEST['email'].'"';
    		$share_user = $this->API_CRUD_model->getById($where,'user');
          
    		if(isset($share_user->id)){
    			
    			if($share_user->type == 1){
        			$mail['user'] = $share_user;
        			$mail['setn'] = $setn;
        			$book_invoice = $this->load->view("admin/email/forgotpassword",$mail,true);
        
        			// $subject = "Forgot Password";
        			// $this->send_mail($book_invoice,$share_user->email,$subject);


        			$smtpWhere = 'id="1"';
					$smtp_detail = $this->API_CRUD_model->getById($smtpWhere, 'smtp_setting');
					$emailconfig = get_smtp_setting();

					$this->load->library('email',$emailconfig);

        			$this->email->from($smtp_detail->from_email, $smtp_detail->from_name);
					$this->email->to($_REQUEST['email']);
					$this->email->set_mailtype('html');
					$this->email->subject('Reset Password');
					$this->email->message($book_invoice);
					$this->email->send();

        			
        			$response=array('status'=>200,'message'=>'Your password has been sent to your email address.');
    		        echo json_encode($response);exit;
    			}else
    			{
    			    $response=array('status'=>200,'message'=>'You have registered with social so please use the social login.');
    		        echo json_encode($response);exit;
    			}
    		}else
    		{
    		    $response=array('status'=>400,'message'=>'Please enter valid email');
		        echo json_encode($response);exit;
    		}
		}
		else
		{
			$response=array('status'=>400,'message'=>'Please enter email');
			echo json_encode($response);exit;
		}		
	}

	public function loginwithotp() {
        try {
            $this->form_validation->set_rules('mobile', 'mobile', 'required');
            if ($this->form_validation->run() == false) {
                $errors = $this->form_validation->error_array();
                sort($errors);
                $array = array('status' => 400, 'message' => $this->lang->line('required_field'));
                echo json_encode($array);
                exit;
            } else {
                $mobileNumber = isset($_POST['mobile']) ? $_POST['mobile'] : '';
                $where = 'mobile="' . $mobileNumber . '"';
                $userData = $this->API_CRUD_model->getById($where, 'user');

                if (isset($userData->id)) {
                    $userId = $userData->id;
                } else {
                    $data = array(
                        'fullname' => '',
                        'email' => '',
                        'password' => '',
                        'type' => '3',
                        'mobile' => $mobileNumber,
                        'image' => ''
                    );
                    $userId = $this->API_CRUD_model->insert($data, 'user');
                }

                $where = "id=" . $userId;
                $userData = $this->API_CRUD_model->getById($where, 'user');

                $userData->image = get_image_path($userData->image,'user');
                $userDatauser_type = 'login'; 
                $response = array('status' => 200, 'message' => "Login successfully", 'result' => array($userData));
                echo json_encode($response);
                exit;
            }
        } catch (Exception $e) {
            $response = array('status' => 400, 'message' => $this->lang->line('error'));
            echo json_encode($response);
            exit;
        }
    }

	public function earn_point() {

        $earn_point = $this->API_CRUD_model->get('', 'earn_point');

        $spin_wheel = $daily_login = $free_coin = [];
        foreach ($earn_point as $key => $value) {
            if($value->point_type == 2){
                $daily_login[] = $value;
            }else{
                $free_coin[] = $value;
            }      
        }  
       
        $response = array('status' => 200, 'daily_login'=>$daily_login,'free_coin' =>$free_coin, 'message' => 'Record get successfully');
       
        echo json_encode($response);
    }

    public function checkStatus()
    {
        if ((isset($_POST['purchase_code']) && $_POST['purchase_code'] != '') and (isset($_POST['package_name']) && $_POST['package_name'] != '')) {
            $url = 'https://divinetechs.com/envato/secureapi/checkStatus.php';
            $envento['purchase_code'] = $_POST['purchase_code'];
            $envento['package_name'] = $_POST['package_name'];
            $envento['base_url'] = $this->config->item('base_url');
            $response = curl($url, $envento);
            
            
            if (isset($response->status) && $response->status == 200) {
                $res = array('status' => 200, 'message' => $response->message);
                echo json_encode($res);exit;
            } else {
                
                if(isset($response->message)){
                    $res = array('status' => 400, 'message' => $response->message);
                    echo json_encode($res);exit;
                }else
                {
                    $res = array('status' => 400, 'message' => "Please check your server your server on something wrong.");
                    echo json_encode($res);exit;
                }
            }
        } else {
            $res = array('status' => 400, 'message' => 'Please enter required field');
            echo json_encode($res);exit;
        }
    }

    public function get_notification() {
        try {
            $this->form_validation->set_rules('user_id', 'user_id', 'required');
            if ($this->form_validation->run() == false) {
                $errors = $this->form_validation->error_array();
                sort($errors);
                $array = array('status' => 400, 'message' => 'Please enter required fields');
                echo json_encode($array);
                exit;
            } else {
               
                $userId = trim($_REQUEST['user_id']);
                $whereUserId = 'user_id="' . $userId . '"';
                $getReadNotificationId = $this->API_CRUD_model->get($whereUserId, 'user_notification_tracking','id','desc');


                $notificationArr = array();
                foreach($getReadNotificationId as $row){
                	
                    array_push($notificationArr, $row->notification_id);
                }
                
                $wherecond = "";
                if(count($notificationArr)>0){
                    $notificationArr = implode(',', $notificationArr);
                    $wherecond = " id  NOT IN(".$notificationArr.")";
                }

                   
                $getAllNotifications = $this->API_CRUD_model->get($wherecond, 'notification','id','desc');

                if(count($getAllNotifications) > 0){
                    $rows = []; 
                    foreach ($getAllNotifications as $key => $value) {
                        
                        if($value->big_picture != ''){
                            $value->big_picture= base_url().'assets/images/notification/'.$value->big_picture;
                        }
                        $rows[] = $value;
                    }

                    $response = array('status' => 200, 'result' => $rows, 'message' => 'successfully get');
                } else {
                    $response = array('status' => 400, 'message' => 'record not found');
                }
               
                echo json_encode($response);
            }
        } catch (Exception $e) {
            $res = array('status' => 400, 'message' => 'error');
            return true;
        }
    }
    
    public function read_notification() {
        try {
        	
            $this->form_validation->set_rules('user_id', 'user_id', 'required');
            $this->form_validation->set_rules('notification_id', 'notification_id', 'required');
            if ($this->form_validation->run() == false) {
                $errors = $this->form_validation->error_array();
                sort($errors);
                $array = array('status' => 400, 'message' => 'Please enter required fields');
                echo json_encode($array);
                exit;
            } else {

                // echo "<pre>";print_r($_REQUEST);die;
                $userId = trim($_REQUEST['user_id']);
                $notification_id = trim($_REQUEST['notification_id']);
                $readArr = array();
                $readArr['user_id'] = $userId;
                $readArr['notification_id'] = $notification_id;
                $readArr['created_at'] = date('Y-m-d h:i:s');
                $this->API_CRUD_model->insert($readArr, 'user_notification_tracking');
                $response = array('status' => 200, 'message' => 'notification read successfully');
                //echo "<pre>";print_r($transactionArr);die;
                echo json_encode($response);

            }
        } catch (Exception $e) {
            $res = array('status' => 400, 'message' => 'error');
            return true;
        }
    }

    public function get_paymentoption(){
    	$payment_option = $this->API_CRUD_model->get('', 'payment_option','id','desc');
    	$data['paytm'] =[];
    	$data['payumoney'] =[];
    	$data['flutterwave'] =[];
    	$data['razorpay'] =[];
    	$data['paypal'] =[];
    	$data['inapppurchage'] =[];
    	
    	foreach ($payment_option as $key => $value) {
    		if($value->name == 'PayTm'){
    			$data['paytm'] = $value;
    		}

			if($value->name == 'PayUMoney'){
    			$data['payumoney'] = $value;
    		}

			if($value->name == 'FlutterWave'){
    			$data['flutterwave'] = $value;
    		}

			if($value->name == 'Razorpay'){
    			$data['razorpay'] = $value;
    		}

			if($value->name == 'Paypal'){
    			$data['paypal'] = $value;
    		}

			if($value->name == 'InApp Purchage'){
    			$data['inapppurchage'] = $value;
    		}
    	}

    	$response = array('status' => 200, 'paytm' => $data['paytm'],'payumoney'=>$data['payumoney'],'flutterwave'=>$data['flutterwave'],'razorpay'=>$data['razorpay'],'paypal'=>$data['paypal'],'inapppurchage'=>$data['inapppurchage']);
    	 echo json_encode($response);
    }
}