<?php
/* 
----------------------------------------------------------
  MODULE :  AJAX ADD TIKET HISTORY LINE 
  V1.0 / 2018
  AUTHOR : SGHAIER MAHMOUD  
----------------------------------------------------------
*/

require_once(__DIR__.'/../ssinclude/app-init.php');
require_once(__DIR__.'/../ssinclude/app-session.php');

header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
//header('Content-Type: application/json');

$id = verif_posted("id");
$description = verif_posted("description");
$user_id = getSessionData($sessionId, 'USER_ID');

// decrypt id
if ( !empty($id) && !empty($description) )
{  
	$id = decrypt_data($id);
	if ( is_numeric($id) ) { 
    // db update 
	try
     {
      // insert history line 
      $sql="insert into tickets_history (message,created_by,ticket_fk)  VALUES (?,?,?) ";
      $affectedrows  = $db->prepare($sql)->execute([$description,$user_id,$id]);
			if ( isset($affectedrows) )
				{
          $last_id =   $db->lastInsertId();
          $sql=" SELECT tickets_history.* , concat(users.first_name,' ',users.last_name) as user_name  
          FROM tickets_history INNER JOIN users on tickets_history.created_by = users.user_id
          WHERE ticket_history_id  = $last_id   " ;
          //echo  $sql;
          $rs = $db->query( $sql )->fetchAll(PDO::FETCH_ASSOC);
          //var_dump ( $rs) ;
          $rs[0]['message'] = nl2br(htmlspecialchars($rs[0]['message'] ));
          $resultJSON = json_encode( $rs);
          // update status
          $sql="update tickets set status_fk = 2 where ticket_id  = $id ";
          $affectedrows_update  = $db->exec($sql);
          // output 
          echo ('[ { "success" : 1 , "data" :  '.$resultJSON.' } ]'); // true
				}           
			}
	catch (PDOException $e)
	  {
      $message =  $e->getMessage();
      echo ('{ "success" : 0 , "message" : "'.$message.'" }'); // false error 
	  }
   }   
}
		
require_once(__DIR__.'/../ssinclude/app-close.php');?>