<?php
if(!defined('BASEPATH')) {
   die('Direct access to the script is not allowed');
}
$title .= $languageArray["tickets.title"];
if( ($_SESSION["msmbilisim_userlogin"] ?? 0) != 1  || ($user["client_type"] ?? 0) == 1  ){
  Header("Location:".site_url('logout'));
}
if( $settings["email_confirmation"] == 1  && ($user["email_verified"] ?? 1) == 0  ){
  Header("Location:".site_url('verify_otp'));
}
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 (isset($settings["ticket_res"]) && $settings["ticket_res"] == 2) {
    // Checking if the client has made their first deposit
    $firstDeposit = $conn->prepare("
        SELECT COUNT(*) as deposit_count 
        FROM payments 
        WHERE client_id = :client_id
    ");
    $firstDeposit->execute(['client_id' => $user["client_id"]]);
    $depositData = $firstDeposit->fetch(PDO::FETCH_ASSOC);

    // If no deposit has been made, ticket creation is not allowed
    if ($depositData['deposit_count'] == 0) {
        $error = 1;
        $errorText = "You need to make your first deposit before creating a ticket.";

        // Display error message with enhanced styling
        echo '
        <div style="
            display: flex; 
            justify-content: center; 
            align-items: center; 
            background-color: #f8d7da; 
            color: #721c24; 
            padding: 20px; 
            border-radius: 10px; 
            border: 1px solid #f5c6cb; 
            margin: 30px auto; 
            font-family: \'Roboto\', Arial, sans-serif; 
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); 
            max-width: 500px; 
            text-align: center;
        ">
            <div style="width: 100%;">
                <strong style="font-size: 18px; display: block; margin-bottom: 10px;">⚠️ Error</strong>
                <p style="font-size: 16px; line-height: 1.5; margin: 0;">
                    You need to make your first deposit before creating a ticket.
                </p>
                <a href="' . site_url() . 'addfunds" style="
                    display: inline-block; 
                    margin-top: 15px; 
                    padding: 10px 20px; 
                    background-color: #f44336; 
                    color: #ffffff; 
                    text-decoration: none; 
                    font-size: 14px; 
                    font-weight: bold; 
                    border-radius: 5px; 
                    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); 
                    transition: background-color 0.3s ease;
                " onmouseover="this.style.backgroundColor=\'#d32f2f\'" onmouseout="this.style.backgroundColor=\'#f44336\'">
                    Make a Deposit
                </a>
            </div>
        </div>';

        exit();
    }
}

  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) {
    $htmlContent = '
    <html>
        <head>
            <style>
                body {
                    font-family: "Trebuchet MS", Helvetica, sans-serif;
                    color: #444;
                    background-color: #f9f9f9;
                    margin: 0;
                    padding: 0;
                }
                .container {
                    max-width: 700px;
                    margin: 30px auto;
                    background: #ffffff;
                    padding: 30px;
                    border-radius: 10px;
                    box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
                }
                .header {
                    text-align: center;
                    background: #6c63ff;
                    color: #ffffff;
                    padding: 20px;
                    border-radius: 10px 10px 0 0;
                    font-size: 28px;
                    font-weight: bold;
                }
                .content {
                    font-size: 18px;
                    line-height: 1.8;
                    color: #555;
                    margin: 20px 0;
                }
                .content p {
                    margin: 15px 0;
                }
                .content .details {
                    background: #f9f9f9;
                    padding: 15px;
                    border: 1px solid #ddd;
                    border-radius: 5px;
                    margin: 20px 0;
                }
                .button {
                    display: inline-block;
                    text-align: center;
                    background: #6c63ff;
                    color: #ffffff;
                    text-decoration: none;
                    font-size: 18px;
                    font-weight: bold;
                    padding: 15px 30px;
                    border-radius: 5px;
                    margin: 20px 0;
                    transition: 0.3s;
                }
                .button:hover {
                    background: #5a55e3;
                }
                .footer {
                    margin-top: 30px;
                    text-align: center;
                    font-size: 14px;
                    color: #999;
                    border-top: 1px solid #ddd;
                    padding-top: 15px;
                }
                .footer a {
                    color: #6c63ff;
                    text-decoration: none;
                }
                .footer a:hover {
                    text-decoration: underline;
                }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    New Ticket Notification
                </div>
                <div class="content">
                    <p>Hello <strong>Admin</strong>,</p>
                    <p>You have received a new message in a support ticket on <strong>' . htmlspecialchars($settings["site_name"]) . '</strong>.</p>
                    <p><strong>Ticket Subject:</strong> ' . htmlspecialchars($subject) . '</p>
                    <div class="details">
                        <p><strong>Message:</strong></p>
                        <p>' . nl2br(htmlspecialchars($message)) . '</p>
                    </div>
                    <p>Please click the button below to view the ticket details and respond:</p>
                    <a href="' . site_url() . 'admin/tickets/read/' . $ticket_id . '" class="button">View Ticket</a>
                    <p>If you need further assistance, feel free to contact our technical support team.</p>
                </div>
                <div class="footer">
                    <p>&copy; ' . date("Y") . ' ' . htmlspecialchars($settings["site_name"]) . '. All rights reserved.</p>
                    <p>For inquiries, visit <a href="' . htmlspecialchars($settings["support_url"]) . '">Support Center</a>.</p>
                </div>
            </div>
        </body>
    </html>';

    $to = $settings["admin_mail"]; 
    $from = $settings["smtp_user"];  
    $fromName = $settings["site_seo"]; 
    $subjectEmail = "New Ticket Message"; 
    $headers = "MIME-Version: 1.0" . "\r\n"; 
    $headers .= "Content-type: text/html; charset=UTF-8" . "\r\n"; 
    $headers .= 'From: ' . $fromName . '<' . $from . '>' . "\r\n"; 

    if (mail($to, $subjectEmail, $htmlContent, $headers)) { 
        // Email sent successfully
    } else {
        // Email sending failed
    }
}
        if( $insert && $insert2 && $insert3 ):
          unset($_SESSION["data"]);
          $conn->commit();
          header('Location:'.site_url('tickets/').$ticket_id);
          exit();
        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) ));
  $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->fetch(PDO::FETCH_ASSOC);
  $messageList["ticket"]  = $ticketList;
  // Set canmessage flag: 2 = can message, 1 = ticket closed
  if ($ticketList && ($ticketList["status"] == "closed" || $ticketList["status"] == "expired" || $ticketList["status"] == "paused")) {
    $messageList["ticket"]["canmessage"] = 1;
  } else {
    $messageList["ticket"]["canmessage"] = 2;
  }

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["status"] ?? '') == "closed" ){
        $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_newmessage"] == 2) {
    $htmlContent = '
    <html>
        <head>
            <style>
                body {
                    font-family: "Arial", sans-serif;
                    background-color: #f4f4f4;
                    margin: 0;
                    padding: 0;
                }
                .email-container {
                    max-width: 600px;
                    margin: 30px auto;
                    background-color: #ffffff;
                    border: 1px solid #e0e0e0;
                    border-radius: 10px;
                    box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
                    overflow: hidden;
                }
                .email-header {
                    background-color: #007BFF;
                    color: #ffffff;
                    text-align: center;
                    padding: 20px 0;
                    font-size: 24px;
                    font-weight: bold;
                }
                .email-body {
                    padding: 20px;
                    color: #333333;
                    font-size: 16px;
                    line-height: 1.6;
                }
                .email-body p {
                    margin: 10px 0;
                }
                .email-footer {
                    background-color: #f9f9f9;
                    text-align: center;
                    padding: 15px;
                    font-size: 14px;
                    color: #666666;
                    border-top: 1px solid #e0e0e0;
                }
                .button {
                    display: inline-block;
                    background-color: #007BFF;
                    color: #ffffff;
                    padding: 12px 20px;
                    text-decoration: none;
                    border-radius: 5px;
                    font-size: 16px;
                    margin-top: 15px;
                }
                .button:hover {
                    background-color: #0056b3;
                }
            </style>
        </head>
        <body>
            <div class="email-container">
                <div class="email-header">
                    New Message Alert for Admin
                </div>
                <div class="email-body">
                    <p>Dear Admin,</p>
                    <p>A new message has been received in the support ticket system.</p>
                    <p>User: <strong>' . htmlspecialchars($user["username"]) . '</strong></p>
                    <p>Email: <strong>' . htmlspecialchars($user["email"]) . '</strong></p>
                    <p>Click the button below to view the ticket details:</p>
                    <a href="' . site_url() . 'admin/tickets/read/' . $ticket_id . '" class="button">View Ticket</a>
                    <p>For further assistance, contact the support team.</p>
                    <p>Best regards,</p>
                    <p>' . htmlspecialchars($settings["site_name"]) . ' Support Team</p>
                </div>
                <div class="email-footer">
                    &copy; ' . date("Y") . ' ' . htmlspecialchars($settings["site_name"]) . '. All rights reserved.
                    <br>
                    <a href="' . htmlspecialchars($settings["support_url"]) . '" style="color: #007BFF;">Visit Support Center</a>
                </div>
            </div>
        </body>
    </html>';

    $to = $settings['admin_mail']; // Admin email
    $from = $settings["smtp_user"];
    $fromName = $settings["site_seo"];
    $subject = "Admin Alert: New Message Notification";
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type: text/html; charset=UTF-8" . "\r\n";
    $headers .= 'From: ' . $fromName . '<' . $from . '>' . "\r\n";
 
    if (mail($to, $subject, $htmlContent, $headers)) {
        // Email sent successfully
    } else {
        // Email sending failed
    }
}
        if( $update && $insert && $insert3 ):
          unset($_SESSION["data"]);
          $conn->commit();
          header("Location:".site_url('tickets/').route(1));
          exit();
        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'));
  exit();

}

$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];