<?php
if(!defined('BASEPATH')) {
   die('Direct access to the script is not allowed');
}
$title .= $languageArray["tickets.title"];

if( $_SESSION["msmbilisim_userlogin"] != 1  || $user["client_type"] == 1  ){
  Header("Location:".site_url('logout'));
}
if( $settings["email_confirmation"] == 1  && $user["email_type"] == 1  ){
  Header("Location:".site_url('confirm_email'));
}
if( !route(1) ){

	
	
    $orders = $conn->prepare("SELECT * FROM ticket_subjects ORDER BY subject_id ASC");
    $orders-> execute(array( ));
    $orders = $orders->fetchAll(PDO::FETCH_ASSOC);

  $ordersList = [];

    foreach ($orders as $order) {
      $o["subject"]    = $order["subject"];
      array_push($ordersList,$o);
    }
  
	
	
	
  $tickets = $conn->prepare("SELECT * FROM tickets WHERE client_id=:c_id ORDER BY lastupdate_time DESC ");
  $tickets-> execute(array("c_id"=>$user["client_id"]));
  $tickets = $tickets->fetchAll(PDO::FETCH_ASSOC);
  $ticketList = [];
    foreach ($tickets as $ticket) {
      foreach ($ticket as $key => $value) {
        if( $key == "status" ){
          $t[$key] = $languageArray["tickets.status.".$value];
        }else{
          $t[$key] = $value;
        }
      }
      array_push($ticketList,$t);
    }

  if( $_POST ){
    foreach ($_POST as $key => $value) {
      $_SESSION["data"][$key]  = $value;
    }
    $subject  = filter_var($_POST["subject"], FILTER_SANITIZE_STRING);
    $subject  = strip_tags(htmlspecialchars($subject));
    $message  = filter_var($_POST["message"], FILTER_SANITIZE_STRING);
    $message  = strip_tags(htmlspecialchars($message));
      if( empty($subject) ){
        $error    = 1;
        $errorText= $languageArray["error.tickets.new.subject"];
      }elseif( strlen(str_replace(' ','',$message)) < 1 ){
        $error    = 1;
        $errorText= str_replace("{length}","1",$languageArray["error.tickets.new.message.length"]);
      }elseif( open_ticket($user["client_id"]) >=  $settings["tickets_per_user"] ){
        $error    = 1;
        $errorText= str_replace("{limit}",$settings["tickets_per_user"],$languageArray["error.tickets.new.limit"]);
      }else{
        $conn->beginTransaction();
        $insert = $conn->prepare("INSERT INTO tickets SET client_id=:c_id, subject=:subject, time=:time, lastupdate_time=:last_time ");
        $insert = $insert->execute(array("c_id"=>$user["client_id"],"subject"=>$subject,"time"=>date("Y.m.d H:i:s"),"last_time"=>date("Y.m.d H:i:s") ));
          if( $insert ){ $ticket_id = $conn->lastInsertId(); }
        $insert2= $conn->prepare("INSERT INTO ticket_reply SET ticket_id=:t_id, message=:message, time=:time ");
        $insert2= $insert2->execute(array("t_id"=>$ticket_id,"message"=>$message,"time"=>date("Y.m.d H:i:s")));
        
      
        $post = $conn->prepare("SELECT * FROM ticket_subjects WHERE subject=:subject and auto_reply=:auto_reply");
        $post->execute(array("subject"=>$subject,"auto_reply"=>1));
        $post = $post->fetch(PDO::FETCH_ASSOC); 
        $insert3= $conn->prepare("INSERT INTO client_report SET client_id=:c_id, action=:action, report_ip=:ip, report_date=:date ");
        $insert3= $insert3->execute(array("c_id"=>$user["client_id"],"action"=>"New support ticket created#".$ticket_id,"ip"=>GetIP(),"date"=>date("Y-m-d H:i:s") ));
		  
		  
		   if($post){

        $insert4= $conn->prepare("INSERT INTO ticket_reply SET ticket_id=:t_id, support=:support, message=:message, time=:time ");
        $insert4= $insert4->execute(array("t_id"=>$ticket_id,"support"=>2,"message"=>$post["content"],"time"=>date("Y.m.d H:i:s")));
          
        $insert5= $conn->prepare("INSERT INTO client_report SET client_id=:c_id, action=:action, report_ip=:ip, report_date=:date ");
        $insert5= $insert5->execute(array("c_id"=>$user["client_id"],"action"=>"Support request <strong>Automatic</strong> answered as. ID:".$ticket_id,"ip"=>GetIP(),"date"=>date("Y-m-d H:i:s") ));
      }
if( $settings["alert_newticket"] == 2 ){
// ticket message 

$htmlContent = "<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='UTF-8'>
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>
  <title>New Ticket Message</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      background-color: #f4f4f4;
      color: #333;
    }
    .email-container {
      width: 100%;
      max-width: 600px;
      margin: 20px auto;
      background-color: #ffffff;
      padding: 30px;
      box-sizing: border-box;
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
      border-radius: 8px;
    }
    .header-container {
      background-color: #007bff;
      padding: 20px;
      margin: -30px -30px 20px -30px;
      text-align: center;
      border-top-left-radius: 8px;
      border-top-right-radius: 8px;
    }
    .header {
      color: white;
      font-size: 22px;
      font-weight: bold;
    }
    .button {
      background-color: #007bff;
      color: white;
      text-decoration: none;
      padding: 12px 25px;
      border-radius: 5px;
      display: inline-block;
      font-size: 16px;
      text-align: center;
      width: 100%;
      box-sizing: border-box;
      margin-top: 20px;
    }
    .button:hover {
      background-color: #0056b3;
    }
    p {
      font-size: 16px;
      line-height: 1.6;
      text-align: center;
    }
    @media only screen and (max-width: 600px) {
      .button {
        padding: 15px !important;
        font-size: 18px !important;
        width: 100% !important;
      }
    }
  </style>
</head>
<body>
  <div class='email-container'>
    <div class='header-container'>
      <div class='header'>Ticket Created </div>
    </div>
    <p><strong>Hello,</strong></p>
    <p>You have received a new message in your ticket.</p>
    <p>To view the message and respond, please click the link below:</p>
    <a href='" . site_url() . "tickets/$ticket_id' class='button'>View Ticket Message</a>
    <br><br>
    <p>Thank you.</p>
  </div>
</body>
</html>";



$to = $user['email'];
$from = $settings["smtp_user"];  
$fromName = $settings["site_seo"]; 
$subject = "New Message Received In Your Support Ticket";

$headers = "MIME-Version: 1.0" . "\r\n"; 
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; 
$headers .= 'From: '.$fromName.'<'.$from.'>' . "\r\n"; 
$headers .= 'Cc: '.$from . "\r\n"; 
$headers .= 'Bcc: '.$from . "\r\n"; 
 if(mail($to, $subject, $htmlContent, $headers)){ 
}else{ 
     } 


} 
        if( $insert && $insert2 && $insert3 ):
          unset($_SESSION["data"]);
          header('Location:'.site_url('tickets/').$ticket_id);
          $conn->commit();
          
        else:
          $error    = 1;
          $errorText= $languageArray["error.tickets.new.fail"];
          $conn->rollBack();
        endif;
      }
  }

}elseif( route(1) && preg_replace('/[^0-9]/', '', route(1)) && !preg_replace('/[^a-zA-Z]/', '', route(1))  ){

if (!countRow(["table" => "tickets", "where" => ["ticket_id" => route(1) ,"client_id" => $user["client_id"] ]])):
        header("Location:" . site_url("tickets"));
        exit();
    else:

  $templateDir  = "open_ticket";



  $ticketUpdate = $conn->prepare("UPDATE tickets SET support_new=:new  WHERE client_id=:c_id && ticket_id=:t_id ");
  $ticketUpdate-> execute(array("c_id"=>$user["client_id"], "new"=>1, "t_id"=>route(1) ));
  $ticketUpdate = $ticketUpdate->fetch(PDO::FETCH_ASSOC);
  $messageList  = $conn->prepare("SELECT * FROM ticket_reply WHERE ticket_id=:t_id ");
  $messageList  -> execute(array("t_id"=>route(1)));
  $messageList  = $messageList->fetchAll(PDO::FETCH_ASSOC);


  $ticketList = $conn->prepare("SELECT * FROM tickets WHERE client_id=:c_id && ticket_id=:t_id ");
  $ticketList-> execute(array("c_id"=>$user["client_id"], "t_id"=>route(1) ));
  $ticketList = $ticketList->fetchAll(PDO::FETCH_ASSOC);
  $messageList["ticket"]  = $ticketList;

$tickets = $conn->prepare("SELECT * FROM tickets WHERE client_id=:c_id && ticket_id=:t_id");
  $tickets-> execute(array("c_id"=>$user["client_id"], "t_id"=>route(1) ));
  $tickets = $tickets->fetchAll(PDO::FETCH_ASSOC);
$ticketsList = [];

     foreach ($tickets as $ticket) {
        
$t["message"] =  $ticket["message"];
        $t["time"] =  $ticket["time"];
       $t["refill_end_date"] =  $refill_end_date;
        $t["show_refill"]  = $ticket["show_refill"];
      $t["id"]    = $ticket["order_id"];

      array_push($ticketsList,$t);
     
    }

endif;



  if( $_POST ){
    foreach ($_POST as $key => $value) {
      $_SESSION["data"][$key]  = $value;
    }
   $message  = str_replace('<script>','',$_POST["message"]);
   $message  = filter_var($message, FILTER_SANITIZE_STRING);
   $message  = strip_tags(htmlspecialchars($message));
            if( empty($message)){
        $error    = 1;
        $errorText= "Message can't be Empty";
      }elseif( strlen(str_replace(' ','',$message)) < 1 ){
        $error    = 1;
        $errorText= str_replace("{length}","1",$languageArray["error.tickets.read.message.length"]);
      }elseif( $ticketList["canmessage"] == 1 ){
        $error    = 1;
        $errorText= $languageArray["error.tickets.read.message.cant"];
      }else{
        $conn->beginTransaction();
        $update = $conn->prepare("UPDATE tickets SET lastupdate_time=:last_time, status=:status, client_new=:new WHERE ticket_id=:t_id ");
        $update = $update->execute(array("last_time"=>date("Y.m.d H:i:s"),"t_id"=>route(1),"new"=>2,"status"=>"pending" ));
        $insert = $conn->prepare("INSERT INTO ticket_reply SET ticket_id=:t_id, message=:message, time=:time ");
        $insert = $insert->execute(array("t_id"=>route(1),"message"=>$message,"time"=>date("Y.m.d H:i:s")));
        $insert3= $conn->prepare("INSERT INTO client_report SET client_id=:c_id, action=:action, report_ip=:ip, report_date=:date ");
        $insert3= $insert3->execute(array("c_id"=>$user["client_id"],"action"=>"Support request answered#".route(1),"ip"=>GetIP(),"date"=>date("Y-m-d H:i:s") ));

if( $settings["alert_newticket"] == 2 ){
    
    // 
$htmlContent = "<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='UTF-8'>
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>
  <title>New Support Ticket Message</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f4f4f4;
      text-align: center;
    }
    .email-container {
      max-width: 600px;
      margin: 20px auto;
      background: #fff;
      padding: 30px;
      border-radius: 8px;
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
    }
    .header-container {
      background: #dc3545;
      padding: 20px;
      color: #fff;
      border-radius: 8px 8px 0 0;
    }
    .header {
      font-size: 22px;
      font-weight: bold;
    }
    p {
      font-size: 16px;
      line-height: 1.6;
    }
    .button {
      background: #dc3545;
      color: #fff;
      padding: 12px 20px;
      text-decoration: none;
      border-radius: 5px;
      display: inline-block;
      margin-top: 20px;
      font-weight: bold;
    }
    .footer {
      font-size: 14px;
      margin-top: 20px;
      color: #555;
    }
  </style>
</head>
<body>
  <div class='email-container'>
    <div class='header-container'>
      <div class='header'>New Support Ticket Message</div>
    </div>
    <p>Hello,</p>
    <p>You have received a new message in your support ticket.</p>
    <p>To view the message, please click the link below:</p>
    <p><a href='" . site_url() . "/admin/tickets?search=unread/$ticket_id' class='button'>View Unread Ticket Message</a></p>
    <p class='footer'>Thank you,<br><strong>{$settings['site_name']} Team</strong></p>
  </div>
</body>
</html>";


$site_name = $settings["site_name"];
$to = $settings['admin_mail'];
$from = $settings["smtp_user"];
$fromName = $settings["site_seo"];
$subject = "New Manual Order Recieved";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: '.$fromName.'<'.$from.'>' . "\r\n";
$headers .= 'Cc: '.$from . "\r\n";
$headers .= 'Bcc: '.$from . "\r\n";

 if(mail($to, $subject, $htmlContent, $headers)){ 
}else{ 
     } 
} 
        if( $update && $insert && $insert3 ):
          unset($_SESSION["data"]);
          $conn->commit();
          header("Location:".site_url('tickets/').route(1));
        else:
          $error    = 1;
          $errorText= $languageArray["error.tickets.read.fail"];
          $conn->rollBack();
        endif;
      }
  }

}elseif( route(1) && preg_replace('/[^a-zA-Z]/', '', route(1))  ){

  header('Location:'.site_url('404'));

}

$status_list  = ["all","pending","answered","closed","paused","expired"];
$search_statu = route(1); if( !route(1) ):  $route[1] = "all";  endif;

  if( !in_array($search_statu,$status_list) ):
    $route[1]         = "all";
  endif;

  if( route(2) ):
    $page         = route(2);
  else:
    $page         = 1;
  endif;
    if( route(1) != "all" ): $search  = "&& ticket_status='".route(1)."'"; else: $search = ""; endif;
    if( !empty($_GET["search"]) ): $search.= " && ( order_url LIKE '%".$_GET["search"]."%' ||  order_id LIKE '%".$_GET["search"]."%' ) "; endif;
    $c_id       = $user["client_id"];
    $to         = 25;
    $count      = $conn->query("SELECT * FROM tickets WHERE client_id='$c_id' $search ")->rowCount();
    $pageCount  = ceil($count/$to);
      if( $page > $pageCount ): $page = 1; endif;
    $where      = ($page*$to)-$to;
    $paginationArr = ["count"=>$pageCount,"current"=>$page,"next"=>$page+1,"previous"=>$page-1];