<?php

require_once '../element/connection.php';

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false]);
    exit();
}

$ticket_id = intval($_GET['ticket_id']);
$last_id = intval($_GET['last_id']);
$user_id = $_SESSION['user_id'];

// Verify ticket belongs to user
$check_query = "SELECT id FROM support_tickets WHERE id = '$ticket_id' AND user_id = '$user_id'";
$check_result = mysqli_query($conn, $check_query);

if (mysqli_num_rows($check_result) == 0) {
    echo json_encode(['success' => false]);
    exit();
}

// Get new messages
$query = "SELECT m.*, 
                 GROUP_CONCAT(a.file_name) as attachments,
                 GROUP_CONCAT(a.file_path) as file_paths
          FROM support_messages m
          LEFT JOIN support_attachments a ON m.id = a.message_id
          WHERE m.ticket_id = '$ticket_id' AND m.id > '$last_id'
          GROUP BY m.id
          ORDER BY m.created_at ASC";
$result = mysqli_query($conn, $query);

$messages = [];
while ($row = mysqli_fetch_assoc($result)) {
    $attachments = $row['attachments'] ? explode(',', $row['attachments']) : [];
    $paths = $row['file_paths'] ? explode(',', $row['file_paths']) : [];
    
    $messages[] = [
        'id' => $row['id'],
        'ticket_id' => $row['ticket_id'],
        'sender_type' => $row['sender_type'],
        'message' => $row['message'],
        'status' => $row['status'],
        'created_at' => $row['created_at'],
        'time_formatted' => date('h:i A', strtotime($row['created_at'])),
        'attachments' => $attachments,
        'file_paths' => $paths
    ];
    
    // Mark admin messages as delivered
    if ($row['sender_type'] == 'admin' && $row['status'] == 'sent') {
        mysqli_query($conn, "UPDATE support_messages SET status = 'delivered' WHERE id = '{$row['id']}'");
    }
}

// Check if admin is typing
$is_typing = false;
if (isset($_SESSION['typing_admin_' . $ticket_id])) {
    $typing_data = $_SESSION['typing_admin_' . $ticket_id];
    if ($typing_data['typing'] && (time() - $typing_data['timestamp']) < 3) {
        $is_typing = true;
    }
}

// Check if admin is online (active in last 30 seconds)
$admin_online = false;
if (isset($_SESSION['admin_last_seen'])) {
    $admin_online = (time() - $_SESSION['admin_last_seen']) < 30;
}

echo json_encode([
    'success' => true,
    'messages' => $messages,
    'is_typing' => $is_typing,
    'admin_online' => $admin_online
]);
?>