<?php
include "Connection.php";
$conn = new Connection();


if(isset($_REQUEST["funName"])) {
	$_SESSION["userid"]=23;
	$db = $conn->getConnection();
	$fun = $_REQUEST["funName"];
	switch($fun) {
        case "contentlist":
        case "addcontent":
        case "updatecontent":
        case "deletecontent":
		case "contentdetails":
       // case "bulletinnotification":    
            $fun();
        break;	
        default:
            $conn->message(false,"PAGE NOT FOUND");exit;
        break;		 
	}
}else
{
      $conn->message(false,"PAGE NOT FOUND");exit;
}

// ExpoContent List
function contentlist () {
        
	global $conn;
	try {
		
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';		
		$pn = escape_str($_REQUEST["pn"]);
		$nr = escape_str($_REQUEST["nr"]);
		$key = escape_str($_REQUEST["key"]);
		if(isset($_SESSION["userid"])) {
			//$query_str = "SELECT SQL_CALC_FOUND_ROWS t.*  FROM ".TABLE_BULLETIN." t WHERE t.is_deleted = 0 ";
			$query_str = "SELECT SQL_CALC_FOUND_ROWS p.contentid,p.model_id,p.title,p.description,p.created_on,s.filepath,s.thumbpath FROM ".TABLE_EXPLORE_CONTENT." as p INNER JOIN ".TABLE_EXPLORE_FILE." as s  on p.contentid=s.contentid WHERE p.is_deleted=0";

			// Search
			if (!empty($key)) {
				$query_str.= " and (p.title like '%$key%' ) ";
			}

			$query_str.= " order by p.contentid asc ";

			// Pagination
			if (!empty($pn) and !empty($nr)) {
				// Navigation
    			$query_str.= " limit ".(($pn - 1) *  $nr).", ".$nr;
			}
            // echo $query_str;exit;
			$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;
            $data_arr=$query->fetchAll(PDO::FETCH_OBJ);
        
            if(count($data_arr)>0)
            {
                require (dirname(__FILE__).'/awsfileserver.php'); 
                $s3=awsfileserver::connectS3();
                foreach($data_arr as $skey=>$res_val)
                {
                     
                    $data_arr[$skey]->filepath_url='';
					$data_arr[$skey]->thumbpath_url='';
					//$thumbpath_url=
                    if($res_val->filepath!='')
                    { 
                        $obj = new stdClass();
                        $obj->key_name=S3_CUS_CONTENT_URL.$res_val->filepath;			
                        $data_arr[$skey]->filepath_url=awsfileserver::getS3Url($s3,S3_BUCKET,$obj);	
                        
                    }
					if($res_val->thumbpath!='')
                    { 
                        $obj = new stdClass();
                        $obj->key_name=S3_CUS_CONTENT_URL.$res_val->thumbpath;			
                        $data_arr[$skey]->thumbpath_url=awsfileserver::getS3Url($s3,S3_BUCKET,$obj);	
                        
                    }
                    
                }
            }

			$arr['bulletin'] = $data_arr;
			if(count($arr) != 0){
				 
                $conn->message(true,$conn->getMessage($lang,'expcontent','success1'),$arr );
			}else{
				$conn->message(false,$conn->getMessage($lang,'expcontent','error2'));
			}
		}
		else{
			$conn->message(false,$conn->getMessage($lang,'expcontent','error1'));
		}
	}
	catch(PDOException $e){
		$conn->message(false,$conn->getMessage($lang,'expcontent','error4'));
	}
}

// Add expocontent
function addcontent () {
	global $conn;
	try {
        
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';	
		//$pageData = $conn->loadJSON($lang);
		if(isset($_SESSION["userid"])) {
            
			$title	 = escape_str($_REQUEST["title"]);
			$description = escape_str($_REQUEST["description"]);
			$model_id= escape_str($_REQUEST["model_id"]);
			//$model_id= escape_str($_REQUEST["model_id"]);
        
            if(!($title!='' && $description!='' && $model_id!='') ){ $conn->message(false, 'FIELDS MISSING');exit; }  
                        
             
            //FILE UPLOAD
            if(isset($_FILES['file']) && $_FILES['file']['name'])
            {
	
				$status = 1;    
                $obj = new stdClass();
                $obj->filekey = 'file';
                $obj->size = '200'; //IN MB
                $obj->type = array('mp4');	
                $conn->validateFile($obj);			
                $obj->path = "../".S3_CUS_CONTENT_URL;
                $obj->filename = 'expcontent_'.date('Ymd')."_".uniqid();			
                $file = $conn->uploadFile($obj);
				///echo "new------".$file; 
				$filesize=$_FILES['file']['size'];

                //S3 UPLOAD
                //S3 LIB
                require_once (dirname(__FILE__).'/awsfileserver.php'); 

                //S3 OBJ
                $s3=awsfileserver::connectS3();
                awsfileserver::checkupload($s3,S3_BUCKET,S3_CUS_CONTENT_URL.$file,dirname(__FILE__)."/../".S3_CUS_CONTENT_URL.$file);

                //DELETE AFTER MOVE TO S3
                @unlink(dirname(__FILE__).'/../'.S3_CUS_CONTENT_URL.$file);
            }else
            {
                $conn->message(false,$conn->getMessage($lang,'expcontent','error5'));	
            }
			
			//FILE UPLOAD
            if(isset($_FILES['thumbimage']) && $_FILES['thumbimage']['name'])
            {
                $obj = new stdClass();
                $obj->filekey = 'thumbimage';
                $obj->size = '10'; //IN MB
                $obj->type = array('jpg','png','jpeg');	
                $conn->validateFile($obj);			
                $obj->path = "../".S3_CUS_CONTENT_URL;
                $obj->filename = 'expcontentthumb_'.date('Ymd')."_".uniqid();			
                $image = $conn->uploadFile($obj);
				

                //S3 UPLOAD
                //S3 LIB
                require_once (dirname(__FILE__).'/awsfileserver.php'); 

                //S3 OBJ
                $s3=awsfileserver::connectS3();
                awsfileserver::checkupload($s3,S3_BUCKET,S3_CUS_CONTENT_URL.$image,dirname(__FILE__)."/../".S3_CUS_CONTENT_URL.$image);

                //DELETE AFTER MOVE TO S3
                @unlink(dirname(__FILE__).'/../'.S3_CUS_CONTENT_URL.$image);
            }else
            {
                $conn->message(false,$conn->getMessage($lang,'expcontent','error3'));	
            }
        
            $insert = "INSERT INTO ".TABLE_EXPLORE_CONTENT." (`model_id`, `title`, `description`, `uploaddate`, `version`, `status`, `is_deleted`, `created_on`, `modified_on`) VALUES ('".$model_id."','".$title."','".$description."','".NOW."',1,1,0,'".NOW."','".NOW."')";        		
            $insertquery = $conn->query($insert);
            $content_id = $conn->lastinsetid();
			
			$insertfilequery = "INSERT INTO ".TABLE_EXPLORE_FILE." (`contentid`, `language_id`, `filepath`, `thumbpath`, `filetypeid`, `filetype`, `filesize`, `filequality`, `created_on`, `modified_on`) VALUES ('".$content_id."',1,'".$file."','".$image."',2,'MP4','".$filesize."','HIGH','".NOW."','".NOW."')";         
            $conn->query($insertfilequery);
            
            
            
           // sendBulletinNotification($bulletin_id);
              $conn->message(true,$conn->getMessage($lang,'expcontent','success1'),getexpodata($content_id));
        
          //  $conn->message(true,$conn->getMessage($lang,'bulletin','success1'),getBulletin ($content_id));
        
		}else{
			$conn->message(false,$conn->getMessage($lang,'expcontent','error1'));
		} 
	}
	catch(PDOException $e) {
		$conn->message(false,$conn->getMessage($lang,'expcontent','error4'));
	}
}

// Update updatecontent
function updatecontent () {
	global $conn;
	try {
		//$_SESSION["userid"]=12;
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';	
		//$pageData = $conn->loadJSON($lang);
		if(isset($_SESSION["userid"])) {
            
            $title	 = escape_str($_REQUEST["title"]);
			$description = escape_str($_REQUEST["description"]);
			//$model_id= escape_str($_REQUEST["model_id"]);
			$contentid = escape_str($_REQUEST["contentid"]);
            //echo "t--------".$title.'d----------'.$description.'c----------'.$contentid; exit;
            if(($title=='' && $description=='' && $contentid=='')){ $conn->message(false, 'FIELDS MISSING');exit; }                
        
            //$query_str = "SELECT bulletin_id FROM ".TABLE_BULLETIN." WHERE bulletin_id = '".$bulletin_id."'  AND is_deleted='0'";
			$query_str = "SELECT p.contentid,p.model_id,p.title,p.description,p.created_on,s.filepath,s.thumbpath FROM ".TABLE_EXPLORE_CONTENT." as p INNER JOIN ".TABLE_EXPLORE_FILE." as s  on p.contentid=s.contentid WHERE p.contentid='".$contentid."' AND p.is_deleted='0'  LIMIT 1";
            $query = $conn->query($query_str);
            $arr = $query->fetchAll(PDO::FETCH_OBJ);
			//print_r($arr); die;
            if(count($arr)== 1)
            {
                
                $filecond='';
				$imagecond='';
                //FILE UPLOAD
                if(isset($_FILES['file']) && $_FILES['file']['name']) {

                    $obj = new stdClass();
                    $obj->filekey = 'file';
                    $obj->size = '200'; //IN MB
                    $obj->type = array('mp4');	
                    $conn->validateFile($obj);			
                    $obj->path = "../".S3_CUS_CONTENT_URL;
                    $obj->filename = 'expcontent_'.date('Ymd')."_".uniqid();			
                    $image = $conn->uploadFile($obj);
					$filesize=$_FILES['file']['size'];

                    //S3 UPLOAD
                    //S3 LIB
                    require_once (dirname(__FILE__).'/awsfileserver.php'); 

                    //S3 OBJ
                    $s3=awsfileserver::connectS3();
                    awsfileserver::checkupload($s3,S3_BUCKET,S3_CUS_CONTENT_URL.$image,dirname(__FILE__)."/../".S3_CUS_CONTENT_URL.$image);

                    //DELETE AFTER MOVE TO S3
                    @unlink(dirname(__FILE__).'/../'.S3_CUS_CONTENT_URL.$image);
                    
                    
                    $filecond=",`filepath`='".$image."',`filesize`='".$filesize."'"; 
                    
                }
				
				
                //FILE UPLOAD
                if(isset($_FILES['thumbimage']) && $_FILES['thumbimage']['name']) {

                    $obj = new stdClass();
                    $obj->filekey = 'thumbimage';
                    $obj->size = '10'; //IN MB
                    $obj->type = array('jpg','jpeg','png');	
                    $conn->validateFile($obj);			
                    $obj->path = "../".S3_CUS_CONTENT_URL;
                    $obj->filename = 'expcontent_'.date('Ymd')."_".uniqid();			
                    $image = $conn->uploadFile($obj);
					//$filesize=$_FILES['file']['size'];

                    //S3 UPLOAD
                    //S3 LIB
                    require_once (dirname(__FILE__).'/awsfileserver.php'); 

                    //S3 OBJ
                    $s3=awsfileserver::connectS3();
                    awsfileserver::checkupload($s3,S3_BUCKET,S3_CUS_CONTENT_URL.$image,dirname(__FILE__)."/../".S3_CUS_CONTENT_URL.$image);

                    //DELETE AFTER MOVE TO S3
                    @unlink(dirname(__FILE__).'/../'.S3_CUS_CONTENT_URL.$image);
                    
                    
                    $imagecond=",`thumbpath`='".$image."'"; 
                    
                }
        
               $update_str = "UPDATE ".TABLE_EXPLORE_CONTENT." SET `title`='".$title."',`description`='".$description."',modified_on='".NOW."' WHERE contentid = '".$contentid."'";
                $conn->query($update_str);
				
				$update_filestr = "UPDATE ".TABLE_EXPLORE_FILE." SET  modified_on='".NOW."'".$imagecond.$filecond."  WHERE contentid = '".$contentid."'";

                $conn->query($update_filestr);
                $conn->message(true,$conn->getMessage($lang,'expcontent','success1'),getexpodata($contentid));
            }
            else
            {
                $conn->message(false,$conn->getMessage($lang,'expcontent','error2'));
            }
        }else{
			$conn->message(false,$conn->getMessage($lang,'expcontent','error1'));
		} 
	}
	catch(PDOException $e) {
		$conn->message(false,$conn->getMessage($lang,'expcontent','error4'));
	}
}

// Delete deletecontent
function deletecontent () {
	global $conn;
	try{
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';	
        
		if(isset($_SESSION["userid"])){
			//$bulletin_id = escape_str($_REQUEST["bulletin_id"]);
			$contentid= escape_str($_REQUEST["contentid"]);
            
			$deletestr = "UPDATE ".TABLE_EXPLORE_CONTENT." SET `is_deleted` = '1' WHERE contentid = '".$contentid."'";
			$deletequery = $conn->query($deletestr);
			
			
            $query_str = "SELECT * FROM ".TABLE_EXPLORE_FILE." WHERE contentid = '".$contentid."'  LIMIT 1";
            $query = $conn->query($query_str);
            $arr = $query->fetchAll(PDO::FETCH_OBJ);
			//print_r($arr);
			 
			if(count($arr))
			{
				//S3 UPLOAD
				//S3 LIB
				require (dirname(__FILE__).'/awsfileserver.php'); 
				//S3 OBJ
				$s3=awsfileserver::connectS3();
				//if($arr[0]->filepath!='')
				//awsfileserver::deleteobject($s3,S3_BUCKET,S3_CUS_CONTENT_URL.$arr[0]->filepath);
				//if($arr[0]->thumbpath!='')
				//awsfileserver::deleteobject($s3,S3_BUCKET,S3_CUS_CONTENT_URL.$arr[0]->thumbpath);
			 
			}
			
			if($deletequery) {
				 $conn->message(true,$conn->getMessage($lang,'expcontent','success1'));
			}
		}else{
			$conn->message(false,$conn->getMessage($lang,'expcontent','error1'));
		}
	}catch(PDOException $e){
		echo $e->getMessage();
	}
}

function getexpodata($content_id)
{
	global $conn;
    $data_arr=array();
    
    if($content_id!='')
    {
		$query_str = "SELECT p.contentid,p.model_id,p.title,p.description,p.created_on,s.filepath,s.thumbpath FROM ".TABLE_EXPLORE_CONTENT." as p INNER JOIN ".TABLE_EXPLORE_FILE." as s  on p.contentid=s.contentid WHERE p.contentid='".$content_id."' LIMIT 1";
        $data_arr=$conn->getQueryValue($query_str);
        $data_arr=(count($data_arr)>0)?$data_arr[0]:array();
    }
    return $data_arr;
}



function sendBulletinNotification ($id)
{
    global $conn;        
    $query_str = "SELECT * FROM `".TABLE_BULLETIN."` WHERE bulletin_id='".$id."'   LIMIT 1"; 
    $query_arr=$conn->getQueryValue($query_str);

    if(count($query_arr)>0)
    {
        $obj=new stdClass();
        $obj->id=$query_arr[0]->bulletin_id;
        $obj->bulletin_id=$query_arr[0]->bulletin_id;

        $notificationdata= json_encode($obj);
        $notificationtype='4';
        
        $notificationtext="New Bulletin - `".$query_arr[0]->bulletin_title."` published ";            
        //ROLE
        if($query_arr[0]->filter_role!='')
        {
            $role_arr=@explode(',',$query_arr[0]->filter_role); 
            if(count($role_arr)>0)
            {
                $user_cond.=" AND role IN (".$query_arr[0]->filter_role.")";
            }                
        }
        //ZONE
        if($query_arr[0]->filter_zone!='')
        {
            $zone_arr=@explode(',',$query_arr[0]->filter_zone); 
            if(count($zone_arr)>0)
            {
                $zone_quotes = array_map("quotes_array", $zone_arr);                   
                $user_cond.=" AND dealer_code IN (SELECT dealer_code FROM ".DMS_DEALER." WHERE zone IN (".@implode(',',$zone_quotes)."))";
            }
        }
        //REGION
        if($query_arr[0]->filter_region!='')
        {
            $region_arr=@explode(',',$query_arr[0]->filter_region);
            if(count($region_arr)>0)
            {
                $region_quotes = array_map("quotes_array", $region_arr);
                $user_cond.=" AND dealer_code IN (SELECT dealer_code FROM ".DMS_DEALER." WHERE city IN (".@implode(',',$region_quotes)."))";
            }
        }
        //DEALER
        if($query_arr[0]->filter_dealer!='')
        { 
            $dealer_arr=@explode(',',$query_arr[0]->filter_dealer);
            if(count($dealer_arr)>0)
            {
                $dealer_quotes = array_map("quotes_array", $dealer_arr);
                $user_cond.=" AND dealer_code IN (".@implode(',',$dealer_quotes).")";
            }
        }
        //$user_cond.=($query_arr[0]->user_type=='0')?" AND role>7 AND role<14":" AND role=15";      
        
        switch ($query_arr[0]->segment)
        {
            case '1':$user_cond.=' AND (segment=0 OR segment=1)';
                break;
            case '2':$user_cond.=' AND (segment=0 OR segment=2)';
                break;
            default: $user_cond.=' AND segment=0';break;
        }
        
        //CHECK USER EXIST FOR NOTIFICATION 
		$check_user_str = " SELECT userid FROM ".TABLE_USER." WHERE role>2 AND status='1' AND is_deleted='0' ".$user_cond;
        $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 ('".escape_str($query_arr[0]->bulletin_title)."','".escape_str($notificationtext)."','".$notificationdata."','".$notificationtype."' ,'1','".NOW."','".NOW."','".NOW."')");

            $notificationid=$conn->lastinsetid();
            $data=array('notification_id'=>$notificationid,'title'=>$query_arr[0]->bulletin_title,'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);
                }
                
            }
        }
    }
    
}

// GET content DETAILS
function contentdetails (){
	global $conn;
	try {
		//print_r($_REQUEST);
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';
		if(isset($_SESSION["userid"]))
        {
            $contentid = escape_str($_REQUEST["contentid"]);
        
            //VALIDATION CHECK
            if(!($contentid!=''  )) $conn->message(false,$conn->getMessage($lang,'expcontent','error2'));
            
            $query_str = "SELECT p.contentid,p.model_id,p.title,p.description,p.created_on,s.filepath,s.thumbpath FROM ".TABLE_EXPLORE_CONTENT." as p INNER JOIN ".TABLE_EXPLORE_FILE." as s  on p.contentid=s.contentid WHERE p.contentid='".$contentid."' AND p.status='1'  LIMIT 1";
			 $query = $conn->query($query_str);
            $expocontent_arr = $query->fetchAll(PDO::FETCH_OBJ);
				
			
            if(!(count($expocontent_arr)>0))
            {
                $conn->message(false,$conn->getMessage($lang,'expcontent','error3'));
            }       
            
			   
			   if(count($expocontent_arr)>0)
            {
                require (dirname(__FILE__).'/awsfileserver.php'); 
                $s3=awsfileserver::connectS3();
                foreach($expocontent_arr as $skey=>$res_val)
                {
                     
                    $expocontent_arr[$skey]->filepath_url='';
					$expocontent_arr[$skey]->thumbpath_url='';
					
                    if($res_val->filepath!='')
                    { 
                        $obj = new stdClass();
                        $obj->key_name=S3_CUS_CONTENT_URL.$res_val->filepath;			
                        $expocontent_arr[$skey]->filepath_url=awsfileserver::getS3Url($s3,S3_BUCKET,$obj);	
                        
                    }
					if($res_val->thumbpath!='')
                    { 
                        $obj = new stdClass();
                        $obj->key_name=S3_CUS_CONTENT_URL.$res_val->thumbpath;			
                        $expocontent_arr[$skey]->thumbpath_url=awsfileserver::getS3Url($s3,S3_BUCKET,$obj);	
                        
                    }
                    
                }
            }
			   
			   $arr=$expocontent_arr;
			
        
            
            $conn->message(true,$conn->getMessage($lang,'expcontent','success1'),$arr); 
		}else{
			$conn->message(false,$conn->getMessage($lang,'expcontent','error1'));
		} 
	}
	catch(PDOException $e) {
		$conn->message(false,$conn->getMessage($lang,'expcontent','error4'));
	}
}
function bulletinnotification()
{
    global $conn;
    $lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';
    $bulletin_id = escape_str($_REQUEST["bulletin_id"]);
    sendBulletinNotification($bulletin_id);
    $conn->message(true,$conn->getMessage($lang,'bulletin','success1'),$arr); 
}

?>