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


if(isset($_REQUEST["funName"])) {
	$db = $conn->getConnection();
	$fun = $_REQUEST["funName"];
	switch($fun) {
        case "bulletinlist":
        case "addbulletin":
        case "updatebulletin":
        case "deletebulletin":
		case "bulletindetails":
        case "bulletinnotification":    
            $fun();
        break;	
        default:
            $conn->message(false,"PAGE NOT FOUND");exit;
        break;		 
	}
}else
{
      $conn->message(false,"PAGE NOT FOUND");exit;
}

// Bulletin  List
function bulletinlist () {
        
	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 ";

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

			$query_str.= " order by t.bulletin_id 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)
                {
                     
                    $image_url='';
                    if($res_val->image!='')
                    { 
                        $obj = new stdClass();
                        $obj->key_name=S3_BULLETIN_URL.$res_val->image ;			
                        $url=awsfileserver::getS3Url($s3,S3_BUCKET,$obj);	
                        $image_url=$url;
                    }
                    $data_arr[$skey]->image_url=$image_url;
                }
            }

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

// Add Bulletin
function addbulletin () {
	global $conn;
	try {
        
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';	
		//$pageData = $conn->loadJSON($lang);
		if(isset($_SESSION["userid"])) {
            
			$bulletin_title = escape_str($_REQUEST["bulletin_title"]);
			$bulletin_sdesc = escape_str($_REQUEST["bulletin_sdesc"]);
			$bulletin_desc = escape_str($_REQUEST["bulletin_desc"]);
        
            if(!($bulletin_title!='' && $bulletin_sdesc!='' && $bulletin_desc!='' ) ){ $conn->message(false, 'FIELDS MISSING');exit; }  
                        
            //FILTER
            $filter_role=escape_str($_REQUEST["filter_role"]);
            $filter_zone=escape_str($_REQUEST["filter_zone"]);
            $filter_region=escape_str($_REQUEST["filter_region"]);
            $filter_dealer=escape_str($_REQUEST["filter_dealer"]);
            $segment =(isset($_REQUEST["segment"]))?escape_str($_REQUEST["segment"]):0;
            
            $user_type =(isset($_REQUEST["user_type"]))?escape_str($_REQUEST["user_type"]):0;	
        
			$status = 1;      
            //FILE UPLOAD
            if(isset($_FILES['file']) && $_FILES['file']['name'])
            {
                $obj = new stdClass();
                $obj->filekey = 'file';
                $obj->size = '10'; //IN MB
                $obj->type = array('jpg','jpeg','png');	
                $conn->validateFile($obj);			
                $obj->path = "../".S3_BULLETIN_URL;
                $obj->filename = 'bulletin_'.date('Ymd')."_".uniqid();			
                $image = $conn->uploadFile($obj);

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

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

                //DELETE AFTER MOVE TO S3
                @unlink(dirname(__FILE__).'/../'.S3_BULLETIN_URL.$image);
            }else
            {
                $conn->message(false,$conn->getMessage($lang,'bulletin','error3'));	
            }
        
            $insert = "INSERT INTO ".TABLE_BULLETIN." (`user_type`,segment,`bulletin_title`, `bulletin_sdesc`, `bulletin_desc`, `image`, `filter_role`, `filter_zone`, `filter_region`, `filter_dealer`, `published_date`, `status`, `is_deleted`, `created_on`, `modified_on`) VALUES ('".$user_type."','".$segment."','".$bulletin_title."','".$bulletin_sdesc."','".$bulletin_desc."','".$image."','".$filter_role."','".$filter_zone."','".$filter_region."','".$filter_dealer."','".NOW."','".$status."','0' , '".NOW."','".NOW."')"; 
        
            $insertquery = $conn->query($insert);
            $bulletin_id = $conn->lastinsetid();
            
            sendBulletinNotification($bulletin_id);
            
            $conn->message(true,$conn->getMessage($lang,'bulletin','success1'),getBulletin ($bulletin_id));
        
		}else{
			$conn->message(false,$conn->getMessage($lang,'bulletin','error1'));
		} 
	}
	catch(PDOException $e) {
		$conn->message(false,$conn->getMessage($lang,'bulletin','error4'));
	}
}

// Update Bulletin
function updatebulletin () {
	global $conn;
	try {
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';	
		//$pageData = $conn->loadJSON($lang);
		if(isset($_SESSION["userid"])) {
            
            $bulletin_id = escape_str($_REQUEST["bulletin_id"]);            
			$bulletin_title = escape_str($_REQUEST["bulletin_title"]);
			$bulletin_sdesc = escape_str($_REQUEST["bulletin_sdesc"]);
			$bulletin_desc = escape_str($_REQUEST["bulletin_desc"]);
            $segment =(isset($_REQUEST["segment"]))?escape_str($_REQUEST["segment"]):0;
            
            //FILTER
            $filter_role=escape_str($_REQUEST["filter_role"]);
            $filter_zone=escape_str($_REQUEST["filter_zone"]);
            $filter_region=escape_str($_REQUEST["filter_region"]);
            $filter_dealer=escape_str($_REQUEST["filter_dealer"]);
            
            if(!($bulletin_id!='' && $bulletin_title!='' && $bulletin_sdesc!='' && $bulletin_desc!='' ) ){ $conn->message(false, 'FIELDS MISSING');exit; }                
        
            $query_str = "SELECT bulletin_id FROM ".TABLE_BULLETIN." WHERE bulletin_id = '".$bulletin_id."'  AND is_deleted='0'";
            $query = $conn->query($query_str);
            $arr = $query->fetchAll(PDO::FETCH_OBJ);
        
            if(count($arr)== 1)
            {
                
                $imagecond='';
                //FILE UPLOAD
                if(isset($_FILES['file']) && $_FILES['file']['name']) {

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

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

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

                    //DELETE AFTER MOVE TO S3
                    @unlink(dirname(__FILE__).'/../'.S3_BULLETIN_URL.$image);
                    
                    
                    $imagecond="`image`='".$image."',"; 
                    
                }
        
                $update_str = "UPDATE ".TABLE_BULLETIN." SET segment='".$segment."',`bulletin_title`='".$bulletin_title."', `bulletin_sdesc`='".$bulletin_sdesc."', `bulletin_desc`='".$bulletin_desc."', ".$imagecond." `filter_role`='".$filter_role."', `filter_zone`='".$filter_zone."', `filter_region`='".$filter_region."', `filter_dealer`='".$filter_dealer."',modified_on='".NOW."' WHERE bulletin_id = '".$bulletin_id."'";

                $conn->query($update_str);
                $conn->message(true,$conn->getMessage($lang,'bulletin','success1'),getBulletin ($bulletin_id));
            }
            else
            {
                $conn->message(false,$conn->getMessage($lang,'bulletin','error2'));
            }
        }else{
			$conn->message(false,$conn->getMessage($lang,'bulletin','error1'));
		} 
	}
	catch(PDOException $e) {
		$conn->message(false,$conn->getMessage($lang,'bulletin','error4'));
	}
}

// Delete Bulletin
function deletebulletin () {
	global $conn;
	try{
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';	
        
		if(isset($_SESSION["userid"])){
			$bulletin_id = escape_str($_REQUEST["bulletin_id"]);
            
			$deletestr = "UPDATE ".TABLE_BULLETIN." SET `is_deleted` = '1' WHERE bulletin_id = '".$bulletin_id."'";
			$deletequery = $conn->query($deletestr);
			if($deletequery) {
				 $conn->message(true,$conn->getMessage($lang,'bulletin','success1'));
			}
		}else{
			$conn->message(false,$conn->getMessage($lang,'bulletin','error1'));
		}
	}catch(PDOException $e){
		echo $e->getMessage();
	}
}

function getBulletin ($bulletin_id)
{
	global $conn;
    $data_arr=array();
    
    if($bulletin_id!='')
    {
        $data_arr=$conn->getQueryValue("SELECT * FROM ".TABLE_BULLETIN."   WHERE bulletin_id = '".$bulletin_id."' LIMIT 1");
        $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)
        {
            $user_arr=array();
			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;
                        }
                    }
                    // globalfunc::sendUserNotification($data,$usertokenarr);
            
                }
                
            }
        }
    }
    
}

// GET BULLETIN DETAILS
function bulletindetails (){
	global $conn;
	try {
		//print_r($_REQUEST);
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';
		if(isset($_SESSION["userid"]))
        {
            $bulletin_id = escape_str($_REQUEST["bulletin_id"]);
        
            //VALIDATION CHECK
            if(!($bulletin_id!=''  )) $conn->message(false,$conn->getMessage($lang,'bulletin','error2'));
            
            $query_str = "SELECT `id`, `rolename`  FROM ".TABLE_ROLE." WHERE status=1 ";        
            $role_arr = $conn->getQueryValue($query_str);
            if(count($role_arr)>0)
            {
                foreach($role_arr as $res)
                {
                    $data_role[$res->id]=$res;
                }
            }
        
            $check_bulletin_str = "SELECT * FROM `".TABLE_BULLETIN."` WHERE bulletin_id='".$bulletin_id."' AND status='1'  LIMIT 1";  
            $check_bulletin_arr=$conn->getQueryValue($check_bulletin_str);
            if(!(count($check_bulletin_arr)>0))
            {
                $conn->message(false,$conn->getMessage($lang,'bulletin','error3'));
            }       
            
             
            
            $check_bulletin_arr[0]->filter_role=($check_bulletin_arr[0]->filter_role!='')?@explode(',',$check_bulletin_arr[0]->filter_role):array();
            $check_bulletin_arr[0]->filter_role_name=array();
            $role_data=array();
            if(count($check_bulletin_arr[0]->filter_role)>0)
            {
                foreach($check_bulletin_arr[0]->filter_role as $data)
                {
                    $role_data[]=$data_role[$data];
                }
                $check_bulletin_arr[0]->filter_role_name=$role_data;
            }

            $filter_zone_arr=array();
            $check_bulletin_arr[0]->filter_zone=($check_bulletin_arr[0]->filter_zone!='')?@explode(',',$check_bulletin_arr[0]->filter_zone):array();
            if(count($check_bulletin_arr[0]->filter_zone)>0)
            {
                foreach($check_bulletin_arr[0]->filter_zone as $res_zone)
                {
                    $filter_zone_arr[]=array('zone'=>$res_zone);
                }
                $check_bulletin_arr[0]->filter_zone=$filter_zone_arr;
            }


            $filter_region_arr=array();
            $check_bulletin_arr[0]->filter_region=($check_bulletin_arr[0]->filter_region!='')?@explode(',',$check_bulletin_arr[0]->filter_region):array();
            if(count($check_bulletin_arr[0]->filter_region)>0)
            {
                foreach($check_bulletin_arr[0]->filter_region as $res_region)
                {
                    $filter_region_arr[]=array('city'=>$res_region);
                }
                $check_bulletin_arr[0]->filter_region=$filter_region_arr;
            }

            $filter_dealer_arr=array();
            $check_bulletin_arr[0]->filter_dealer=($check_bulletin_arr[0]->filter_dealer!='')?@explode(',',$check_bulletin_arr[0]->filter_dealer):array();
            if(count($check_bulletin_arr[0]->filter_dealer)>0)
            {
                $dealer_quotes = array_map("quotes_array", $check_bulletin_arr[0]->filter_dealer);  

                $query_str = "SELECT `dealer_code`, `dealer_name` FROM ".DMS_DEALER." WHERE status='1' AND is_deleted='0' AND dealer_code IN (".@implode(',',$dealer_quotes).") GROUP BY dealer_code ";
                $query = $conn->query($query_str);
                $deal_arr = $query->fetchAll(PDO::FETCH_OBJ);

                $check_bulletin_arr[0]->filter_dealer=$deal_arr;
            }
			
			//IMAGE URL
			require (dirname(__FILE__).'/awsfileserver.php'); 
			$s3=awsfileserver::connectS3();
			
			$check_bulletin_arr[0]->image_url='';
			if($check_bulletin_arr[0]->image!='')
			{
				$obj = new stdClass();
				$obj->key_name=S3_BULLETIN_URL.$res_val->image ;			
				$url=awsfileserver::getS3Url($s3,S3_BUCKET,$obj);	
				$check_bulletin_arr[0]->image_url=$url;
			}
			 
			
        
            $arr=$check_bulletin_arr[0];
            $conn->message(true,$conn->getMessage($lang,'bulletin','success1'),$arr); 
		}else{
			$conn->message(false,$conn->getMessage($lang,'bulletin','error1'));
		} 
	}
	catch(PDOException $e) {
		$conn->message(false,$conn->getMessage($lang,'bulletin','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); 
}

?>