<?php

class Otp {

	private $table        = 'otps' ;

	public $otpid         = '' ;
	public $where         = '' ;

	// for insert or update
	public  $type         = '' ;
	public  $field        = [] ;

	public function __construct( $otpid = '' ){
		$this->otpid      = $otpid ;
	}

	public function allowOtp( $mobile ){
		$query         = new Database( $this->table ) ;
		$query->filter = 'otpid' ;
		$query->where  = "ip_address = '".$_SERVER["REMOTE_ADDR"]."' AND created_at > '".date('Y-m-d H:i:s', strtotime('-1 minute'))."' AND send_to = '".$mobile."'" ;
		$query->limit  = '1' ;
		$select = $query->select() ;
		if ( $select['status'] == '200' ){
			return json_return( '301' ) ;
		}else{
			return json_return( '200' ) ;
		}
	}

	public function check( $otpid, $refertype, $referid, $otp ){
		if ( $otp == '' ) return json_return( '300' ) ;

		$query         = new Database( $this->table ) ;
		$query->filter = 'count, code, created_at' ;
		$query->where  = "otpid = '".$otpid."' AND refertype = '".$refertype."' AND referid = '".$referid."'" ;
		$query->limit  = '1' ;
		$select 	   = $query->select() ;

		if ( $select['status'] == '200' ){

			$data  		  = $select['data']['0'] ;

			// update count
			$count 		  = ( $data['count'] + 1 ) ;
			$query->field = [ 'count' => $count ] ;
			$query->save() ;

			if ( $count > 3 ) return json_return( '302' ) ;

			if ( $data['created_at'] < date('Y-m-d H:i:s', strtotime('-1 minute')) ) return json_return( '292' ) ;

			if ( $data['code'] != $otp ) {
				$count++ ;
				if ( $count > 3 ) return json_return( '302' ) ;
				return json_return( '283' ) ;
			}

			return json_return( '200' ) ;
			
		}
		return json_return( '291' ) ;
	}

	public function save(){
		$save 			  = new Database( $this->table ) ;
		$save->type       = 'insert' ;
		$save->field 	  = $this->field ;
		if ( $save->save() ){
			return json_return( '200', [ 'id' => $save->id ] ) ;
		}
		return json_return( '205' ) ;
	}

}

?>