<?php
	include('lock.php');
	include('smtp/PHPMailerAutoload.php');
	
	if(isset($_POST['taskadd']))
	{
	
	$task_title=$_POST['task_title'];
	$task_detail=addslashes($_POST['task_detail']);
	$task_userid=$_POST['task_userid'];
	$task_priority=$_POST['task_priority'];
	$task_enddate=$_POST['task_enddate'];
	$task_endtime=$_POST['task_endtime'];
	$task_type=$_POST['task_type'];
	
	$cdate=date('Y-m-d H:i:s');
	$cby=$_SESSION['user_id'];
	
	
	//////// IMAGE UPLOAD SECTION 
	$category_img = $_FILES["category_img"]["name"];
	if($category_img)
	{
	$randomno	=  rand(9999, 999999);
	$target_dir = "./task-image/";
	$categoryimg =$randomno.'-'.$category_img;
	$target_categoryimg = $target_dir . basename($categoryimg);

	if(move_uploaded_file($_FILES["category_img"]["tmp_name"], $target_categoryimg)){
    $categoryimgdata=$categoryimg;
	}
	else
	{
	$categoryimgdata='';
	}	
	}
	else{
    $categoryimgdata=$_POST['category_img_old'];	
	}
	
	
	
	
	
	@$task_id=$_POST['task_id'];
	if($task_id > 0)
	{
	$tasktype='edit';
	$sql ="UPDATE `task_master` SET `task_title`='$task_title',`task_detail`='$task_detail',`task_userid`='$task_userid',`task_priority`='$task_priority',`task_file`='$categoryimgdata' , `task_enddate`='$task_enddate', `task_type`='$task_type', `task_endtime`='$task_endtime' WHERE task_id='$task_id'";	
	}
	else
	{
	$tasktype='add';
	$sql ="INSERT INTO `task_master`(`task_title`, `task_detail`, `task_userid`, `task_priority`,`task_ctime`, `task_cby`,`task_file`,`task_enddate`,`task_type`,`task_endtime`) 
	VALUES ('$task_title','$task_detail','$task_userid','$task_priority','$cdate','$cby','$categoryimgdata','$task_enddate','$task_type','$task_endtime')";	
	}
    mysqli_query($con, $sql);	
	}
	
////// MAIL FORMAT //////
$taskuserqry=mysqli_query($con,"select * from user_master where user_id='$task_userid'");
$taskuserdata=mysqli_fetch_array($taskuserqry);
$taskusername=$taskuserdata['user_name'];
$taskuseremail=$taskuserdata['user_email'];
$taskusermobile='91'.$taskuserdata['user_mobile'];

$message  ='
<p>Dear <strong>'.$taskusername.',</strong> </p>
<p>A new task has been assigned to you. Please find the details below:</p>
<p><strong>Task Name : </strong> '.$task_title.' </p>
<p><strong>Task Priority : </strong> '.$task_priority.'</p>
<p><strong>Task Type : </strong> '.$task_type.'</p>
<p><strong>Task Deadline : </strong> '.date('d-M-Y',strtotime($task_enddate)).'  '.date('h:i A',strtotime($task_endtime)).' </p>
<p>Kindly review the task and ensure it is completed within the given deadline.</p>

<p><br>Best Regards,,</p>
<p><strong>'.$user_name.'</strong></p>
<p><strong> SNA Associates </strong></p>
';

//$message;
if($tasktype=='add')
{
$subject ='New Task Assigned: '.$task_title;
}
else{
$subject ='Task Edit : '.$task_title;
}
$mail = new PHPMailer();
$mail->SMTPDebug  = false;
$mail->isSMTP();
$mail->SMTPAuth   = true;
$mail->Host       = "smtp.gmail.com";
$mail->Port       = 587; // TLS port
$mail->SMTPSecure = 'tls';
$mail->Username   = "notifications@snassociates.org.in";
$mail->Password   = "unjn wqld wlut cmzm"; // ❗ normal password नहीं चलेगा
$mail->isHTML(true);
$mail->CharSet = 'UTF-8';
$mail->setFrom("notifications@snassociates.org.in", "SNA Associates");
$mail->Subject = $subject;
$mail->Body    = $message;
$mail->addAddress($taskuseremail);
// Optional
$mail->SMTPOptions = [
    'ssl' => [
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => false
    ]
];

if(!$mail->send()){
    //echo "Mail Error: " . $mail->ErrorInfo;
}else{
    //echo "Mail Sent Successfully";
}

///////// MAIL FORMAT END ////////////

//////// LOGS CREATE START
if($tasktype=='add')
{
$taskgetquery1="select task_id from task_master where task_cby='$cby' order by task_id desc limit 1";
$taskgetres1=mysqli_query($con, $taskgetquery1);
$taskgetdata1=mysqli_fetch_assoc($taskgetres1);
$logs_taskid = $taskgetdata1['task_id'];

$logsql ="INSERT INTO `task_log`(`logs_taskid`, `logs_remark`, `logs_ctime`, `logs_cby`) 
	VALUES ('$logs_taskid','Task has been created successfully.','$cdate','$cby')";	
$logsqlres = mysqli_query($con, $logsql);

//////// WHATSAPP START 
$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://graph.facebook.com/v25.0/1055933904270012/messages',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>'{
    "messaging_product": "whatsapp",
    "to": "' . $taskusermobile . '",
    "type": "template",
    "template": {
      "name": "task_assign",
      "language": {
        "code": "en"
      },
      "components": [
        {
          "type": "body",
          "parameters": [
            { "type": "text", "text": "' . $taskusername . '" },
            { "type": "text", "text": "' . $task_title . '" },
            { "type": "text", "text": "' . $task_priority . '" },
            { "type": "text", "text": "' . date('d-M-Y',strtotime($task_enddate)) . ' ' . date('h:i A',strtotime($task_endtime)) . '" },
            { "type": "text", "text": "' . $user_name . '" }
          ]
        }
      ]
    }
  }',
  CURLOPT_HTTPHEADER => array(
    'Content-Type: application/json',
    'Authorization: Bearer EAAUbmsNmsz0BRBkTX5GXg7EUzuO5ha43QBF32AnfcX7SGpuFiNit6zENz3wjh33kDRyrAdjn7AAc3gNpacBiFnmgKukurRhqeqN8ZA4UfmIz8zoGi0ICZBHeMNEQ66Ci3HWnaKHvItwmc7kvcfM9hMhSICU2MlqEkiMRZA9CO28HSpyNQpE5NLAUIcndgZDZD'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
//echo $response;
//////// WHATSAPP END 
	
}
//////// LOGS CREATE END
	
echo '<script> window.location="task-list"; </script>';
?>