<?php
session_start();
include "../../connect/db.php";
csrf_verify();

$chap = $_SESSION['chap'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $replyMessage = mysqli_real_escape_string($mysqli, $_POST['replyMessage']);
    $ticketidx = mysqli_real_escape_string($mysqli, $_POST['ticketidx']);

    // Fetch existing ticket details
    $query = "SELECT * FROM support_tickets WHERE ticket_id = ?";
    $stmt = $mysqli->prepare($query);
    $stmt->bind_param('s', $ticketidx);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        
        // Insert the reply as a new entry in the support_tickets table
        $query = "INSERT INTO support_tickets (user, department, message, ticket_id, created_at, name) 
                  VALUES (?, ?, ?, ?, NOW(), ?)";
        $stmt = $mysqli->prepare($query);
        $stmt->bind_param('sssss', $row['user'], $row['department'], $replyMessage, $ticketidx, $row['name']);
        
        if ($stmt->execute()) {
            // Optionally update the status or other fields if needed
            echo "success";
        } else {
            echo "error";
        }
    } else {
        echo "error";
    }
}
?>
