<?php
include("../db.php");
$ch=$_REQUEST["type"];

if($ch=="log"){
	/*
	$where="";
	header( 'Content-Type: text/json' );
	if(isset($_REQUEST["class"]))$where=" AND YEAR(dtime)=".date('Y',strtotime($_REQUEST['date']))." and  MONTH(dtime)=".date('m',strtotime($_REQUEST['date']))." and DAY(dtime)=".date('d',strtotime($_REQUEST['date']))."";
	$sql_limit="SELECT * FROM sms where school_id='".$_SESSION["admin"]["school_id"]."' and session='".$_SESSION["admin"]["session"]."' $where";
	*/
	$where="";
	if(isset($_REQUEST["date"]))$where=" AND YEAR(dtime)=".date('Y',strtotime($_REQUEST['date']))." and  MONTH(dtime)=".date('m',strtotime($_REQUEST['date']))." and DAY(dtime)=".date('d',strtotime($_REQUEST['date']))."";
	$sql_limit="select * from sms where school_id='".$_SESSION["admin"]["school_id"]."' AND session='".$_SESSION["admin"]["session"]."' AND (dtime >= DATE_SUB(CURDATE(), INTERVAL 10 DAY)) $where order by dtime ";
	$aryList=$db->getRows($sql_limit);
	
	$aryPgAct=array("page_id"=>"idCard","action"=>"add");
	if(is_array($aryList) && count($aryList)>0)
	{
	   $i=0;
	   //$aryData='{ "aaData": [ 
		//';
		$aryData=array();
		foreach($aryList as $iList)
		{  
			$i++;
			$Mob=$db->getVal("select name from student where mobile in ('".substr($iList['mobile'],0,12)."','".substr($iList['mobile'],2,12)."')");
			if($Mob=="")$Mob=substr($iList['mobile'],0,12);
			$msg=POST(htmlspecialchars(preg_replace( "/\r|\n/", "",$iList['msg'])));
			$msg=str_replace(array("	","\n", "\r", "<br/>", "\r\n", "'", "&nbsp;&nbsp;", '', $msg)); 
			$aryData["aaData"][]=array(
									$i,
									$Mob,
									$iList['dtime'],
									preg_replace( "/\r|\n/", "",$iList['msg']),
									//POST($iList['status'])
									'Message Submitted'
									); 
			/*
			$aryData.='["'.$i.'",';
			$aryData.='"'.POST(substr($iList['mobile'],0,10)).'",';
			$aryData.='"'.POST($iList['dtime']).'",';
			$aryData.='"'.$msg.'"';
			//$aryData.='"'.POST($iList['status']).'"';
			$aryData.=']';
			if($i!=count($aryList))$aryData.=",";*/
		 }
		 //$aryData.="] }";	
		 echo json_encode($aryData);	
	}
	else{
		echo $db->getLastQuery().$db->getErMsg();
	}
}

elseif($ch=="getcontent"){
    $content = $db->getVal("SELECT content FROM `template` WHERE templateid='$_POST[templateid]'");
    echo $content;
}

elseif($ch=="get_student_list"){
    $classAry = $_POST['classAry'];
    if(count($classAry) > 0){
    echo "
                    <table class='table'>
                    <tr>
                        <th><input type='checkbox' checked='checked' id='checkall' onchange='checkStudents()'  /> Check All </th>
                        <th>Adm. No.</th>
                        <th>Name</th>
                        <th>Class/Sec</th>
                    </tr>
    ";
    $i = 1;
    foreach($classAry as $class){
        $cls = $class['class'];
        $secAry = $class['section'];
        $wheresection = '';
        $sections = '';
 
            $allstudents = $db->getRows("select * from student where class='$cls' and school_id='".$_SESSION["admin"]["school_id"]."' AND session='".$_SESSION["admin"]["session"]."' and status='1' ");
            
            foreach($allstudents as $student){
                if(count($secAry) > 0){
                    if (in_array("$student[section]", $secAry)){

                ?>
                    <tr>
                        <td><input type="checkbox" checked="checked" name="cat[]" class="check-students" value="<?php echo $student['idno']; ?>" /> <?php echo $i; ?> </td>
                        <td><?php echo $student['admissionno']; ?></td>
                        <td><?php echo $student['name']; ?></td>
                        <td><?php echo $cls."/".$student['section']; ?></td>
                    </tr>
                 <?php                        

                    }
                } else {
                ?>
                    <tr>
                        <td><input type="checkbox" checked="checked" name="cat[]" class="check-students" value="<?php echo $student['idno']; ?>" /> <?php echo $i; ?> </td>
                        <td><?php echo $student['admissionno']; ?></td>
                        <td><?php echo $student['name']; ?></td>
                        <td><?php echo $cls."/".$student['section']; ?></td>
                    </tr> 
                 <?php
                }
                 $i++;
            }
             
            
        // }
    }
    echo "</table>";
    }
}



elseif($ch=="routenotification"){

    $route   =   $_REQUEST['route'];
    $msg  =   $_REQUEST['msg'];

    error_reporting(-1);
    ini_set('display_errors', 'On');

    require_once  __DIR__.'/../api_new/firebase/firebase.php';
    require_once  __DIR__.'/../api_new/firebase/push.php';

    $firebase = new Firebase();
    $push = new Push();

    $result_arr = array();

    $set_title ='Route Message';

    $i=0;

    $fb_token="";
    $target_user_name="";
    $user_image = "";
        
    foreach($route as $rt){
        $idno = $db->getRows("select * from student where school_id='".$_SESSION["admin"]["school_id"]."' and location='$rt' and  session='".$_SESSION["admin"]["session"]."' and status = 1");
        foreach($idno  as $stu)
        {
            $sidno      =  $stu['idno'];

            $tokenlist=$db->getRow("SELECT name,photo,fcm_token from student where idno='$sidno' and status='1' ");
    
            $fb_token = $tokenlist["fcm_token"];
	        $target_user_name = $tokenlist["name"];
	        $user_image = $tokenlist["photo"];
    
            $sdetail = $db->getRow("select class, section from student where idno='$sidno' and session='".$_SESSION["admin"]["session"]."' ");
        
            $insertAry = array(
                "uid"       =>  $sidno,
                "class"     =>  $sdetail['class'],
                "section"   =>  $sdetail['section'],
                "content"   =>  $msg,
                "type"      =>  "Route Message",
                "session"   =>  $_SESSION["admin"]["session"]
            );
    
            $flgIn=$db->insertAry("tbl_notification",   $insertAry);
        
            $payload = array();
    
            $payload['target_name'] = $target_user_name;
            $payload['stu_id'] = $sidno;
    
            // whether to include to image or not
            $include_image = TRUE;
    
            $push->setTitle($set_title);
            $push->setMessage($msg);
            if ($include_image) {
                //$push->setImage('https://api.androidhive.info/images/minion.jpg');
                $push->setImage('0');
            } else {
                $push->setImage('');
            }
            $push->setIsBackground(FALSE);
            $push->setPayload($payload);
    
     
            $json = '';
            $response = '';

            $json = $push->getPush();

                $fields = array(
                    'to' => $fb_token,
                    'data' => $json,
                );

                $SERVER_KEY=$db->getVal("select firebase_server_key from tbl_info where id='1'");    
        
                // Set POST variables
                $url = 'https://fcm.googleapis.com/fcm/send';
         
                $headers = array(
                    'Authorization: key=' . $SERVER_KEY,
                    'Content-Type: application/json'
                );
                // Open connection
                $ch = curl_init();
         
                // Set the url, number of POST vars, POST data
                curl_setopt($ch, CURLOPT_URL, $url);
         
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         
                // Disabling SSL Certificate support temporarly
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
         
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
         
                // Execute post
                $result = curl_exec($ch);
                if ($result === FALSE) {
                    die('Curl failed: ' . curl_error($ch));
                }
         
                // Close connection
                curl_close($ch);    
        
        
        
           $i++; 
        }

    }

// 	echo $status;
}

elseif($ch=="studentnotification"){

    $student   =   $_REQUEST['student'];
    $msg  =   $_REQUEST['msg'];

    error_reporting(-1);
    ini_set('display_errors', 'On');

    require_once  __DIR__.'/../api_new/firebase/firebase.php';
    require_once  __DIR__.'/../api_new/firebase/push.php';

    $firebase = new Firebase();
    $push = new Push();

    $result_arr = array();

    $set_title ='Student Message';

    $i=0;

    $fb_token="";
    $target_user_name="";
    $user_image = "";
        
    foreach($student as $rt){
        
        $idno = $db->getRows("select * from student where school_id='".$_SESSION["admin"]["school_id"]."' and idno='$rt' and  session='".$_SESSION["admin"]["session"]."' and status = 1");
        foreach($idno  as $stu)
        {
           
            $sidno      =  $stu['idno'];

            $tokenlist=$db->getRow("SELECT name,photo,fcm_token from student where idno='$sidno' and status='1' ");
    
            $fb_token = $tokenlist["fcm_token"];
	        $target_user_name = $tokenlist["name"];
	        $user_image = $tokenlist["photo"];
    
            $sdetail = $db->getRow("select class, section from student where idno='$sidno' and session='".$_SESSION["admin"]["session"]."' ");
        
            $insertAry = array(
                "uid"       =>  $sidno,
                "class"     =>  $sdetail['class'],
                "section"   =>  $sdetail['section'],
                "content"   =>  $msg,
                "type"      =>  "Student Message",
                "session"   =>  $_SESSION["admin"]["session"]
            );
    
            $flgIn=$db->insertAry("tbl_notification",   $insertAry);
        
            $payload = array();
    
            $payload['target_name'] = $target_user_name;
            $payload['stu_id'] = $sidno;
    
            // whether to include to image or not
            $include_image = TRUE;
    
            $push->setTitle($set_title);
            $push->setMessage($msg);
            if ($include_image) {
                //$push->setImage('https://api.androidhive.info/images/minion.jpg');
                $push->setImage('0');
            } else {
                $push->setImage('');
            }
            $push->setIsBackground(FALSE);
            $push->setPayload($payload);
    
     
            $json = '';
            $response = '';

            $json = $push->getPush();

                $fields = array(
                    'to' => $fb_token,
                    'data' => $json,
                );

                $SERVER_KEY=$db->getVal("select firebase_server_key from tbl_info where id='1'");    
        
                // Set POST variables
                $url = 'https://fcm.googleapis.com/fcm/send';
         
                $headers = array(
                    'Authorization: key=' . $SERVER_KEY,
                    'Content-Type: application/json'
                );
                // Open connection
                $ch = curl_init();
         
                // Set the url, number of POST vars, POST data
                curl_setopt($ch, CURLOPT_URL, $url);
         
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         
                // Disabling SSL Certificate support temporarly
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
         
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
         
                // Execute post
                $result = curl_exec($ch);
                if ($result === FALSE) {
                    die('Curl failed: ' . curl_error($ch));
                }
         
                // Close connection
                curl_close($ch);    
        
        
        
           $i++; 
        }

    }

// 	echo $status;
}

elseif($ch=="classnotification"){

    $classs   =   $_REQUEST['classs'];
    $msg  =   $_REQUEST['msg'];

    error_reporting(-1);
    ini_set('display_errors', 'On');

    require_once  __DIR__.'/../api_new/firebase/firebase.php';
    require_once  __DIR__.'/../api_new/firebase/push.php';

    $firebase = new Firebase();
    $push = new Push();

    $result_arr = array();

    $set_title ='Class Message';

    $i=0;

    $fb_token="";
    $target_user_name="";
    $user_image = "";
        
    foreach($classs as $rt){
         echo "select * from student left join class as cl on student.class=cl.class  where student.school_id='".$_SESSION["admin"]["school_id"]."' and cl.id='$rt' and  student.session='".$_SESSION["admin"]["session"]."' and student.status = 1";
        $idno = $db->getRows("select * from student left join class as cl on student.class=cl.class  where student.school_id='".$_SESSION["admin"]["school_id"]."' and cl.id='$rt' and  student.session='".$_SESSION["admin"]["session"]."' and student.status = 1");
        foreach($idno  as $stu)
        {
           
            $sidno      =  $stu['idno'];

            $tokenlist=$db->getRow("SELECT name,photo,fcm_token from student where idno='$sidno' and status='1' ");
    
            $fb_token = $tokenlist["fcm_token"];
	        $target_user_name = $tokenlist["name"];
	        $user_image = $tokenlist["photo"];
   
            $sdetail = $db->getRow("select class, section from student where idno='$sidno' and session='".$_SESSION["admin"]["session"]."' ");
        
            $insertAry = array(
                "uid"       =>  $sidno,
                "class"     =>  $sdetail['class'],
                "section"   =>  $sdetail['section'],
                "content"   =>  $msg,
                "type"      =>  "Class Message",
                "session"   =>  $_SESSION["admin"]["session"]
            );
    
            $flgIn=$db->insertAry("tbl_notification",   $insertAry);
        
            $payload = array();
    
            $payload['target_name'] = $target_user_name;
            $payload['stu_id'] = $sidno;
    
            // whether to include to image or not
            $include_image = TRUE;
    
            $push->setTitle($set_title);
            $push->setMessage($msg);
            if ($include_image) {
                //$push->setImage('https://api.androidhive.info/images/minion.jpg');
                $push->setImage('0');
            } else {
                $push->setImage('');
            }
            $push->setIsBackground(FALSE);
            $push->setPayload($payload);
    
     
            $json = '';
            $response = '';

            $json = $push->getPush();

                $fields = array(
                    'to' => $fb_token,
                    'data' => $json,
                );

                $SERVER_KEY=$db->getVal("select firebase_server_key from tbl_info where id='1'");    
        
                // Set POST variables
                $url = 'https://fcm.googleapis.com/fcm/send';
         
                $headers = array(
                    'Authorization: key=' . $SERVER_KEY,
                    'Content-Type: application/json'
                );
                // Open connection
                $ch = curl_init();
         
                // Set the url, number of POST vars, POST data
                curl_setopt($ch, CURLOPT_URL, $url);
         
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         
                // Disabling SSL Certificate support temporarly
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
         
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
         
                // Execute post
                $result = curl_exec($ch);
                if ($result === FALSE) {
                    die('Curl failed: ' . curl_error($ch));
                }
         
                // Close connection
                curl_close($ch);    
        
        
        
           $i++; 
        }

    }

// 	echo $status;
}

?>