<?php session_start();
require_once('../../../config/config.php');
require_once (dirname(__FILE__).'/../../../clean_input.php');
	check_input(); 
include("../../common_pages/paging_crm.php");
include("../../common_pages/common_functions.php");
require_once('constants.php');
refresh_access();
if($_SESSION['admin_code']<=0)
	die("Error : Seesion timeout, Please re Login");
if($_SESSION['is_panel_access']<=0)	
	die("Error : Access Denied");
require_once("../../common_pages/enc.php");
$converter = new Encryption($_SESSION['unique_enc_id']);
?>
<?php 

if (isset($_REQUEST))

{
	 
		
	// print_r($_REQUEST);
	switch($_REQUEST['task'])
	{

		case'GeneralDetails':
		{
		
			//print_r($_REQUEST);
			
			$searchtext = mysql_real_escape_string($_REQUEST['searchtext']);
			//$prtstatus = $_REQUEST['status'];
			//$prtcat = $_REQUEST['instructions'];
			$searchtext = trim($searchtext);
			$where = '';			
			$fields = array('remarks','text_message','admin_name');

			if(!empty($searchtext))
			{
				foreach($fields as $field)
				{
				
					if($where=="")
						$where = ' AND ( ';
					else
						$where .= ' OR ';
					$where .= $field." LIKE '%".$searchtext."%' ";
				}
				$where .=')';
			}
					
				
			 
			
			/*if($_REQUEST['s_mtype']<>"")
			{
				 $where .= " and mtype='".$_REQUEST['s_mtype']."'";
			}	
				
			if($_REQUEST['s_team']<>"")
			{
				 $where .= " and team='".$_REQUEST['s_mtype']."'";
			}	
			if($_REQUEST['s_se']>0)
			{
				 $where .= " and sale_employee_code<=0 ";
			}
			if($_REQUEST['s_sale_employee_code']>0)
			{
				 $where .= " and  sale_employee_code='".$_REQUEST['s_sale_employee_code']."'";
			}
			if($_REQUEST['s_status_c']>0)
			{
				 $where .= " and  customer_calling_status='".$_REQUEST['s_status_c']."'";
			}
			if($_REQUEST['s_sms']<>"")
			{
				 $where .= " and  sms='".$_REQUEST['s_sms']."'";
			}	
*/
			
		  		



			

			$q = "SELECT * FROM sms_record  WHERE  1  $where  order by code desc";
			$qr = mysql_query($q) or die('Error: '.mysql_error());
			
			?> 
            
 			<table id="datatable1" class="table display responsive nowrap" width="100%">
              
            <thead>
             
            <tr>
              <th></th>
               <th>Sent Date/Time</th> 	 	 	 
               <th>Schdule Date/Time</th> 	 	 	 
               <th>Sent To</th>
               <th>Total Message</th>               
               <th>Template	</th> 	 	 	
               <th>User</th> 
              <th></th> 	
              
               
            </tr> </thead><tbody>
            <?php	
			//print_r($p);
        	$i = 1;
			if($p['Page']!="1")
				$i = $p['Page'] * $p['Per_Page'] - $p['Per_Page']+ 1;//$i = $p[current] * $p[perPage] - $p[perPage]+ 1;
            
			while ($rows=mysql_fetch_array($qr))
            {             	
			?>
            <tr <?php	if(($i%2)==0) echo 'class="alt_new"';?>>
             <td><?=$i;?></td>
             <!--<td><span onclick="move_order('<?=$rows['code']; ?>','main_result_div','<?=$p['Page'];?>','0','<?=TABLE_NAME;?>');" class="link_a" title="Click Here to Move Up" ><img src="../../images/up_arrow.png" border="0" align="absmiddle" /></span>
	                               <span onclick="move_order('<?=$rows['code']; ?>','main_result_div','<?=$p['Page'];?>','1','<?=TABLE_NAME;?>');" class="link_a"   title="Click Here to Move down" ><img src="../../images/down_arrow.png" border="0" align="absmiddle" /></span></td>-->
             
			  <td><?=date("d-M-y h:ia",strtotime($rows['date_time'])); ?></td> 
              <td><?=date("d-M-y h:ia",strtotime($rows['sms_schedule_time'])); ?></td> 
              <td><?=$rows['remarks']; ?></td>
              <td><?=$rows['total_sms']; ?></td> 
              <td><textarea style="width:200px; height:auto;    "><?=$rows['text_message']; ?></textarea></td> 
              
              <td><?=$rows['admin_name']; ?>
              <?php
			  if($rows['is_canceled']==1)
			  {	echo '<span class="text-danger"><BR/>Canceled By : '.$rows['canceled_user_name'];
			  	echo '<BR/>@ : '.date("d-M-y h:ia",strtotime($rows['canceled_date_time'])).'</span>';
			  }
			  
              ?>
              </td> 
               
              
                
                <td class="controler">
              <?php
			  if($rows['is_canceled']==0)
			  {
			  ?> <!--<span onclick="add_edit('<?=$rows['code']; ?>','main_result_div','<?=$p['Page'];?>');" class="  btn-info btn-icon rounded-circle btn-sm  " title="Edit"><div><i class="fa fa-edit"></i></div></span>--> 
              
              <?php 
			  }
			 // echo $rows['sms_schedule_time'].' > '.date("Y-m-d H:i:s",strtotime("-10 Minutes"));
			  if($rows['sms_schedule_time']>date("Y-m-d H:i:s",strtotime("-10 Minutes")) and $rows['is_canceled']==0) {
			   ?> 
                 <span onclick="delete_row('<?=$rows['code']; ?>','main_result_div','<?=$p['Page'];?>');" class="  btn-danger btn-icon rounded-circle btn-sm  " title="Cancel"><div><i class="fa fa-close"></i></div></span>
                 
              
                
              
              <?php  } ?>
               
              
              </td> 
              
            </tr>
            <?php
			$i++;
			}
       ?>
         
       </tbody>
          </table>
           
 <?php //paging_new('',$p); ?>
		 

    <?php			

    #-------------> Pagination Finish			

		

		
		}

		break;

		 
		case 'add_edit':
		{
		    $i =3;
			$key = array_keys($_REQUEST);	
			$n = count($_REQUEST);					
			while($i<=($n))
			{
				
				$s = $s."&".$key[$i]."=".$_REQUEST[$key[$i]]."";
				$i++;
			}
			require_once("index.class.php");
			$objpl=new General();
			$objpl->add_edit(fetch_details(TABLE_NAME,'code',$_REQUEST['id']),$_REQUEST);	
		}
		break;
		 
		case 'save_key':
		{
			 
			
			 	
				$data=$_POST;
				   $data['agree'] = $_REQUEST['agree'];
				 
				 	if(count($data['status'])<=0)
					{		
						 echo '1|0|Error : Please select to Whom you want to send SMS?!!';
						 return;
					}
				
				   if(trim($data['template'])=='')
					{		
						 echo '1|0|Error : Please enter a SMS Template!!';
						 return;
					}
				    if(trim($data['ttime'])=='')
					{		
						 echo '1|0|Error : Please select Time!!';
						 return;
					}
					if(trim($data['send_sms_to'])=='')
					{		
						 echo '1|0|Error : Please Select to whom you want to send SMS?!';
						 return;
					}
				   
				   if($data['send_sms_to']=='Status')
				   {
				   
						if(count($data['status'])<=0)
						{		
							 echo '1|0|Error : Please select Status want to send SMS!';
							 return;
						}
						$data['eno_status']= array();
				   }
				  
				  if($data['send_sms_to']=='ENO')
				  {
				   
						if(count($data['eno_status'])<=0)
						{		
							 echo '1|0|Error : Please select to With ENO / Without ENO!';
							 
							
					 
							 return;
						}
						$data['status']= array();
						
						
						if($data['eno_status'][0]=='Without ENO' or $data['eno_status'][1]=='Without ENO')
						{
						
						
							$template = $data['template'];
							$a = explode("[ORDER_NO]",$template);
							if(count($a)>1)
							{
								echo '1|0|Error : Can not use [ORDER_NO] for Without ENNO!';
								return;
							}
							$a = explode("[WBNO]",$template);
							if(count($a)>1)
							{
								echo '1|0|Error : Can not use [WBNO] for Without ENNO!';
								return;
							}
							$a = explode("[AMOUNT]",$template);
							if(count($a)>1)
							{
								echo '1|0|Error : Can not use [AMOUNT] for Without ENNO!';
								return;
							}	
						
						} 
						
						
				  }
				  	
					/**/
				 
				/*if(!check_duplicate(TABLE_NAME,'heading',trim($data['heading']),$data['id'],'code'," and is_deleted=0 "))
				{		
					 echo '1|0|Error : Title already exist!!';
					 return;
				}*/
				 
				 
				 //and last_payment_date<='".$ro['draw_date']."'  and b.code IN (".implode(",",$policy_code).")
			  if(count($data['status'])>0)	 
			  {
			  	 
				 
				 	$s_name = array();
					$s2 = "select * from booking_status where code IN (".implode(",",$data['status']).")";
					$r2 = mysql_query($s2);
					while($r4 = mysql_fetch_assoc($r2))
					{
						$s_name[] = $r4['name'];
					}
					$remarks='Status : '.implode(", ",$s_name); 
									
									 
			  }
			   if(count($data['eno_status'])>0)	 
			  {
			  	 
				 $remarks='ENO : '.implode(", ",$data['eno_status']);
				  						
									 
			  }
			  $data['dtime'] = date("Y-m-d",strtotime($data['schudle_time'])).' '.$data['ttime'];
			  $t = date("Y-m-d H:i:s",strtotime("-1 Hours",strtotime($data['dtime'])));
			  
			  if($t<=date("Y-m-d H:i:s"))
			  {
			  
			  	 	 echo '1|0|Error : Date/Time must be 1 Hour later from now!!';//.$t.' - '.date("Y-m-d H:i:s");
					 return;
					 
			  }
			  
			  
			 		/* echo '1|0|<PRE>';
				     print_r($data);echo '</PRE>';  
				     die(); 
			  */
			  
			  if($data['send_sms_to']=='Status')
			  {
				   		
				  $q = "SELECT b.*,ss.name as status_name FROM customer_booking b,booking_status ss where payment_status=2 and booking_status_code IN (".implode(",",$data['status']).")  
				 and not customer_code IN (select code from customer where sms=0 and  customer_calling_status='0' ) and booking_status_code=ss.code order by booking_status_code  
				 ";
			 
			 }
			 if($data['send_sms_to']=='ENO')
			 {
				  
				  if(count($data['eno_status'])==2)
				  {
					  $q = "SELECT * FROM customer  where sms=1 and is_deleted=0 order by code";
				  }
				  elseif($data['eno_status'][0]=='Without ENO' or $data['eno_status'][1]=='Without ENO' )
				  {
				  		$q = "SELECT * FROM customer  where sms=1 and not code IN (SELECT distinct(customer_code) as customer_code FROM customer_booking b where payment_status=2  and 
							(
								wc_no like 'A%' OR 
								wc_no like 'B%' OR 
								wc_no like 'C%' OR 
								wc_no like 'D%' OR 
								wc_no like 'E%' OR 
								wc_no like 'F%' OR 
								wc_no like 'G%' OR 
								wc_no like 'H%' OR 
								wc_no like 'I%' OR 
								wc_no like 'J%' OR 
								wc_no like 'K%' OR 
								wc_no like 'L%' OR 
								wc_no like 'M%' OR 
								wc_no like 'N%' OR 
								wc_no like 'O%' OR 
								wc_no like 'P%' OR 
								wc_no like 'Q%' OR 
								wc_no like 'R%' OR 
								wc_no like 'S%' OR 
								wc_no like 'T%' OR 
								wc_no like 'U%' OR 
								wc_no like 'V%' OR 
								wc_no like 'W%' OR 
								wc_no like 'X%' OR 
								wc_no like 'Y%' OR 
								wc_no like 'Z%' ) 
							
							   order by code ) order by code";
				  }
				  elseif($data['eno_status'][0]=='With ENO')
				  {
				  		
						$q = "SELECT b.* FROM customer_booking b where payment_status=2 and not customer_code IN (select code from customer where sms=0 and  customer_calling_status='0' ) and 
							(
								wc_no like 'A%' OR 
								wc_no like 'B%' OR 
								wc_no like 'C%' OR 
								wc_no like 'D%' OR 
								wc_no like 'E%' OR 
								wc_no like 'F%' OR 
								wc_no like 'G%' OR 
								wc_no like 'H%' OR 
								wc_no like 'I%' OR 
								wc_no like 'J%' OR 
								wc_no like 'K%' OR 
								wc_no like 'L%' OR 
								wc_no like 'M%' OR 
								wc_no like 'N%' OR 
								wc_no like 'O%' OR 
								wc_no like 'P%' OR 
								wc_no like 'Q%' OR 
								wc_no like 'R%' OR 
								wc_no like 'S%' OR 
								wc_no like 'T%' OR 
								wc_no like 'U%' OR 
								wc_no like 'V%' OR 
								wc_no like 'W%' OR 
								wc_no like 'X%' OR 
								wc_no like 'Y%' OR 
								wc_no like 'Z%' ) 
							
							   order by code   ";
				   
				  }
				  
			 
			 }
			 	$r = mysql_query($q);
			 	$x = mysql_num_rows($r);
				
				
				
				if($data['agree']<=0) 
				{
					echo '1|99|<label><input name="agree" id="agree" type="checkbox" value="1" /><span> Please Confirm that, You are going to send above template to <B>'.$x.' Customers</b></span></label>';
					//echo '<PRE>';
				   // print_r($data);echo '</PRE>';  
				    //die();	
					return;
				} 
				
				$lastDate = (date('d') > 10 ? date('30-m-Y') : date('10-m-Y'));
				
				// FORE TESTING PURPOSE ONLY BY : KANTSVERMA
				/* $template = $data['template'];
				$template = str_replace("[NAME]",$rro['bookfor_name'],$template);
				$template = str_replace("[ORDER_NO]",$rro['order_no'],$template);
				$template= str_replace("[WBNO]",$rro['wc_no'],$template);
				$template = str_replace("[AMOUNT]",$rro['total_amount'],$template);
				$template = str_replace("[MONTH]",date("M"),$template);
				$template = str_replace("[DATE]",$lastDate,$template);
				$sender_id=$data['sender_id'];
				$send = sms_jshine2('22168775','9814454439',$template,1,$sender_id);						
				//$send1 = sms_jshine2('31655546','9592434000',$template,1,$sender_id);						
				//$send2 = sms_jshine2('34158364','9877635008',$template,1,$sender_id); */				
				
				//print_r($send);
 				$s = "INSERT INTO  sms_record ";
				$s .= "SET  admin_id='".$_SESSION['admin_code']."'";
				$s .= ",admin_name='".$_SESSION['admin_name']."'";	
				
				$s .= ",remarks='".$remarks."'";
				$s .= ",total_sms='".$x."'"; 	
				$s .= ",sender_id='".$data['sender_id']."'";				
				$s .= ",sms_schedule_time='".date("Y-m-d H:i:s",strtotime($data['dtime']))."'";	
				$s .= ",date_time='".date("Y-m-d H:i:s")."'";					
				$s .= ",text_message='".mysql_real_escape_string(trim($data['template']))."'";
				//echo '0|0|'.$s;die();
				 mysql_query($s);
				 $data['unique_code'] = mysql_insert_id();
				 

				
				 $i = 0;
				 while($rro =mysql_fetch_assoc($r))
				 {
				  		
						if($rro['bookfor_name']=='')
							$rro['bookfor_name'] = $rro['name'];
						if($rro['bookfor_mobile']=='')
							$rro['bookfor_mobile'] = $rro['mobile'];	
						if($rro['customer_code']=='')
							$rro['customer_code'] = $rro['code'];	
						
						$template = $data['template'];
						$template = str_replace("[NAME]",$rro['bookfor_name'],$template);
						$template = str_replace("[ORDER_NO]",$rro['order_no'],$template);
						$template= str_replace("[WBNO]",$rro['wc_no'],$template);
						$template = str_replace("[AMOUNT]",$rro['total_amount'],$template);
						$template = str_replace("[MONTH]",date("M"),$template);
						$template = str_replace("[DATE]",$lastDate,$template);
						$sender_id=$data['sender_id'];
						// saved message on table for cron sms
						$s = "INSERT INTO  sms_details ";
						$s .= "SET mobile_no='".$rro['bookfor_mobile']."'";
						$s .= ",type='".$_SESSION['admin_code']."'";
						$s .= ",m_code='".($rro['customer_code'])."'";	
						$s .= ",sent_flag='0'";		
						$s .= ",sender_id='".$data['sender_id']."'";
						$s .= ",unique_code='".$data['unique_code']."'";				
						$s .= ",sent_date_time='".date("Y-m-d H:i:s",strtotime($data['dtime']))."'";					
						$s .= ",text_message='".mysql_real_escape_string(trim($template))."'";
						//echo '0|0|'.$s;die();
						if(mysql_query($s))
						{
							$i++;
						}
				 }
				//echo '1|1|Temp =>  '.$template;					 
				echo '1|1|SMS Successfully Submited for '.$i.' out of '.$x.' Customers';					 
					
		}
		break;
		
		case 'delete_row':
		{
			//print_r($_REQUEST);
			if($_REQUEST['id']>0)
			{
				$sql = "Select *    FROM   sms_record where code = '".$_REQUEST['id']."'";
				$res = mysql_query($sql);
				$rows = mysql_fetch_assoc($res);
							
								
				 // echo $rows['sms_schedule_time'].' > '.date("Y-m-d H:i:s",strtotime("-10 Minutes"));
			 	 if($rows['sms_schedule_time']>date("Y-m-d H:i:s",strtotime("-10 Minutes")) and $rows['is_canceled']==0)  
			  
				 { 
					 $sql = "update sms_record SET is_canceled=1
					 	,canceled_date_time='".date("Y-m-d H:i:s")."'
						,canceled_user_id='".$_SESSION['admin_code']."'
						,canceled_user_name='".$_SESSION['admin_name']."'
					  WHERE code='".$_REQUEST['id']."' ";
					if(mysql_query($sql))
					{	
					
						$s = "delete from sms_details where sent_flag=0 and unique_code='".$rows['code']."'";
						mysql_query($s);
						create_log(TABLE_NAME,$_REQUEST,'code');	
						echo '1|1|Record Deleted';
						return true;
					}
					else
					{	echo '0|0|Error : while deleting this record!!';	
						return true;
					}
				 }
			 }
					echo '0|0|Error : Can\'t Delete record!!';
		}
		break;
		
		
	};	

}

?>

