<?php
session_start();
require_once '../config/database.php';
require_once '../config/pusher.php'; // If using Pusher
secureSessionStart();
requireLogin();

$conn = getConnection();
$admin_id = $_SESSION['admin_user'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $ticket_id = intval($_POST['ticket_id']);
    $message = mysqli_real_escape_string($conn, $_POST['message']);
    
    $query = "INSERT INTO support_messages (ticket_id, sender_type, sender_id, message, status, created_at) 
              VALUES ('$ticket_id', 'admin', '$admin_id', '$message', 'sent', NOW())";
    
    if (mysqli_query($conn, $query)) {
        $message_id = mysqli_insert_id($conn);
        
        // Update ticket
        mysqli_query($conn, "UPDATE support_tickets SET updated_at = NOW() WHERE id = '$ticket_id'");
        
        // Get message details
        $result = mysqli_query($conn, "SELECT * FROM support_messages WHERE id = '$message_id'");
        $message_data = mysqli_fetch_assoc($result);
        
        $response = [
            'success' => true,
            'message' => [
                'id' => $message_id,
                'ticket_id' => $ticket_id,
                'message' => $message,
                'sender_type' => 'admin',
                'created_at' => $message_data['created_at'],
                'time_formatted' => date('h:i A', strtotime($message_data['created_at']))
            ]
        ];
        
        // Trigger Pusher event if using
        if (isset($pusher)) {
            $pusher->trigger('ticket-' . $ticket_id, 'new-message', $response['message']);
        }
        
        echo json_encode($response);
    } else {
        echo json_encode(['success' => false, 'error' => mysqli_error($conn)]);
    }
}
?>