<?php
include "Connection.php";
require_once(dirname(__FILE__)."/_api/global.php");
$conn = new Connection();


if(isset($_REQUEST["funName"])) {
	$db = $conn->getConnection();
	$fun = $_REQUEST["funName"];
    
  
	switch($fun) {
		case "redeemlist":             
        case "approveredeem": 	 
        case "redeemapprovedlist":     
			$fun();     
		break;
        
	}
}
        
// REDEEM LIST
function redeemlist($type=0) {
	global $conn;
	try {
        $lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';
        
		$pn = $_REQUEST["pn"];
		$nr = $_REQUEST["nr"];
		$key = escape_str($_REQUEST["key"]);
      // $_SESSION["userid"]=1;  
		if(isset($_SESSION["userid"])){
            
            if($type==1)
            {
                $econd=" AND a.is_approved=1";
            }else
            {
                $econd=" AND a.is_approved=0";
            }
        
            $query_str = "SELECT SQL_CALC_FOUND_ROWS a.*,u.`fname`,u.`lname`,u.`emailid`,u.`mobileno`,u.`dealer_code`  FROM ".TABLE_USER_WALLET_APPROVE." a  JOIN ".TABLE_USER." u ON a.smpin=u.smpin AND (u.role>7 AND u.role!=14) WHERE u.is_deleted = 0 ".$econd;
        
			if (!empty($key)) {
				$query_str .= " and ((a.smpin like '%".$key."%') or (u.fname like '%".$key."%') or (u.lname like '%".$key."%') )  ";
			}
			if (!empty($pn) and !empty($nr)) {
				// Navigation
    			$query_str .= " limit " .  (($pn - 1) *  $nr) . ", " . $nr;
			}
        
			$query = $conn->query($query_str);

			// Total records
			$rows_query = $conn->query("select FOUND_ROWS() as total_records");
			$rows_result = $rows_query->fetchAll(PDO::FETCH_OBJ);
			$total_records = $rows_result[0]->total_records;

			$arr['total_records'] = $total_records;
            $userlist=$query->fetchAll(PDO::FETCH_OBJ);
            $dealer_column=array('dealer_name','city','zone');
            if(count($userlist)>0)
            {
                foreach($userlist as $mkey=>$res)
                {        
                    //GET DEALER DETAILS
                    $check_dealer_str = "SELECT   `dealer_name`, `city`,  `zone` FROM `".DMS_DEALER."` WHERE 	dealer_code='".$res->dealer_code."'  LIMIT 1";  
                    $check_result_arr=$conn->getQueryValue($check_dealer_str); 
                    
                    $userlist[$mkey]->dealer=new stdClass();
                    if(count($check_result_arr)>0)
                    {
                        $userlist[$mkey]->dealer=$check_result_arr[0];
                    }else
                    {
                        foreach($dealer_column as $col)
                        {
                            $userlist[$mkey]->dealer->$col='';
                        }
                    } 
                }
            }
            
			$arr['users'] = $userlist;
			if(count($arr) != 0) {
				$conn->message(true,$conn->getMessage($lang,'redeem','success1'),$arr );
			}else {
				$conn->message(false,$conn->getMessage($lang,'redeem','error2'));
			}
		}else {
			$conn->message(false,$conn->getMessage($lang,'redeem','error1'));
		}
	}
	catch(PDOException $e) {
		$conn->message(false,$conn->getMessage($lang,'redeem','error4'));
	}	
}

function redeemapprovedlist() {
    redeemlist(1); //approved list
}

// REDEEM LIST
function approveredeem () {
	global $conn;
	try {
		//print_r($_REQUEST);
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';
		if(isset($_SESSION["userid"]))
        {
            $rid_arr=array();
            
            $rid = escape_str($_REQUEST["id"]);	
            if($rid!='')
            {
                $rid_arr=@explode(',',$rid);
                
                foreach($rid_arr as $ids)
                {
                    if($ids!='')
                    {
                        if(!is_numeric($ids)){  $conn->message(false,$conn->getMessage($lang,'redeem','error3'));   }
                    }
                }
            }
            
        
            //VALIDATION CHECK
            if(!(  $rid!='' &&   count($rid_arr)>0 ))
            {
                $conn->message(false,$conn->getMessage($lang,'redeem','error3'));
            }   
            
            $check_count_str = "SELECT  COUNT(id) as tcount FROM `".TABLE_USER_WALLET_APPROVE."` WHERE is_approved=0 AND id IN(".@implode(',',$rid_arr).") LIMIT 1";  
            $check_result_arr=$conn->getQueryValue($check_count_str); 
            
            if(count($rid_arr)!= $check_result_arr[0]->tcount)
            {
                $conn->message(false,$conn->getMessage($lang,'redeem','error3'));
            }
            
            $get_approval_str = "SELECT a.*,u.userid FROM `".TABLE_USER_WALLET_APPROVE."` a JOIN ".TABLE_USER." u ON a.smpin=u.smpin AND (u.role>7 AND u.role!=14) WHERE u.is_deleted = 0 AND a.is_approved=0 AND a.id IN(".@implode(',',$rid_arr).") ";  
            $get_approval_arr=$conn->getQueryValue($get_approval_str); 
            
            $smpin_arr=array();
            if(count($get_approval_arr)>0)
            {
                foreach($get_approval_arr as $res)
                {
                    $conn->executeQuery("UPDATE ".TABLE_USER_WALLET_APPROVE." SET is_approved='1',approved_id='".$_SESSION["userid"]."',modified_on='".NOW."' WHERE id='".$res->id."'");
                    $smpin_arr[]=$res->smpin;
                    
                    $lvl_points=$res->lvl_points;
                    $token=TIMETOKEN.$res->userid;
                            
                    $conn->executeQuery("INSERT INTO ".TABLE_USER_WALLET_HISTORY."( `smpin`, `type`, `type_id`, `description`, `lvl_points`, `amount`, `transaction_type`, `created_on`, `modified_on`) VALUES ('".$res->smpin."','redeem','".$token."','REDEEM POINTS','".$lvl_points."','".$res->amount."' ,'C','".NOW."','".NOW."')");
                    //UPDATE POINT IN USER
                    $conn->executeQuery("UPDATE  ".TABLE_USER_WALLET." SET amount=amount+".$res->amount." WHERE smpin='".$res->smpin."' ");                    
                   
                }
                //TRIGGER NOTIFICATION
                sendapprovalNotification($smpin_arr);
            }
        
            $conn->message(true,$conn->getMessage($lang,'redeem','success1')); 
		}else{
			$conn->message(false,$conn->getMessage($lang,'redeem','error1'));
		} 
	}
	catch(PDOException $e) {
		$conn->message(false,$conn->getMessage($lang,'redeem','error4'));
	}
}
        

function sendapprovalNotification ($smpin_arr=array() )
{
    
    global $conn;        
        
    if(count($smpin_arr)>0)
    {
        $nobj=new stdClass();
        $notificationtitle='Redemptions point added in wallet';
        $notificationtext='Redemptions point approved and amount is added to wallet';
        $notificationtype='7';
        $notificationdata=json_encode(new stdClass());
        
        $smpin_quotes = array_map("quotes_array", $smpin_arr); 

        //CHECK USER EXIST FOR NOTIFICATION 
		$check_user_str = " SELECT userid FROM ".TABLE_USER." WHERE   status='1' AND is_deleted='0' AND smpin IN (".@implode(',',$smpin_quotes).") AND role>7 AND role!=14";
        $check_user_arr = $conn->getQueryValue($check_user_str);  
        $user_arr=array();    
        if(count($check_user_arr)>0)
        {
			foreach ($check_user_arr as $res_user)
            {
                $user_arr[]=$res_user->userid;
            }
			 
            //INSERT NOTITFICATION
            $conn->executeQuery("INSERT INTO `".TABLE_NOTIFICATION."` (  `notificationtitle`, `notificationtext`, `notificationdata`, `notificationtype`,  `status`, `publisheddate`, `created_on`, `modified_on`) VALUES ('".$notificationtitle."','".escape_str($notificationtext)."','".$notificationdata."','".$notificationtype."' ,'1','".NOW."','".NOW."','".NOW."')");

            $notificationid=$conn->lastinsetid();
            $data=array('notification_id'=>$notificationid,'title'=>$assessment_arr[0]->assessmentname,'message'=>$notificationtext,'notificationtype'=>$notificationtype,'notificationdata'=>$notificationdata,'created_date'=>NOW);

            if(count($user_arr)>0)
            {
                $ins_arr=array();
                foreach($user_arr as $res)
                {
                    $ins_arr[]=" ('".$notificationid."', '".$res."', '0', '".NOW."')";
                }
                
                $insert_chunk=array_chunk($ins_arr, 1000);
                foreach($insert_chunk as $chunk_ins)
                {
                    $conn->executeQuery("INSERT INTO ".TABLE_NOTIFICATION_USER."(`notificationid`, `userid`, `status`,  `created_on`) VALUES ".@implode(',',$chunk_ins)."  ON DUPLICATE KEY UPDATE `status` =0");
                }
                
                
                $usertokenarr['ios']=array();
                $usertokenarr['android']=array();
                $user_device_str = "SELECT ud.devicetype,ud.token FROM `".TABLE_USER_DEVICES."` as ud JOIN (SELECT userid FROM ".TABLE_NOTIFICATION_USER." WHERE notificationid='".$notificationid."')  as u ON ud.userid=u.userid  WHERE ud.is_deleted='0' AND (devicetype='ios' OR devicetype='android')  AND token!=''";
                $user_device_arr = $conn->getQueryValue($user_device_str);
                if(count($user_device_arr)>0)                            
                {

                    foreach($user_device_arr as $res_user)
					{
						if(strtolower($res_user->devicetype)=='ios')
						{
							$usertokenarr['ios'][]=$res_user->token;
						}else if(strtolower($res_user->devicetype)=='android')
						{
							$usertokenarr['android'][]=$res_user->token;
						}
					}

                    // $conn->sendUserNotification($data,$usertokenarr);
                }
                
            }
        }
    }
}
?>