<?php
if (file_exists('../../../'.$_REQUEST['tenant'].'/config.php')) {
require_once('../../../'.$_REQUEST['tenant'].'/config.php');
}
if (file_exists('/config.php')) {
require_once('/config.php');
}

// Retrieve client ID from `subscription_params` in client's database
$client_id_query = mysqli_query($con, "SELECT client_id FROM subscription_params LIMIT 1");
$client_data = mysqli_fetch_assoc($client_id_query);
$client_id = $client_data['client_id'] ?? 0;

if (!$client_id || !isset($_GET['last_checked_reply_id'])) {
echo json_encode([
"new_replies" => false,
"debugData" => "Missing client_id or last_checked_reply_id parameter."
]);
exit();
}

// Sanitize and parse last checked reply ID
$last_checked_reply_id = mysqli_real_escape_string($admin_con, $_GET['last_checked_reply_id']);

// Find new replies for tickets with status 'In Progress' for this client
$query = "
SELECT support_ticket_replies.id AS reply_id, support_ticket_replies.ticket_id
FROM support_ticket_replies
JOIN support_tickets ON support_tickets.id = support_ticket_replies.ticket_id
WHERE support_tickets.client_id = $client_id
AND support_tickets.status = 'In Progress'
AND support_ticket_replies.id > '$last_checked_reply_id'
";
$result = mysqli_query($admin_con, $query);

// Check if the query failed and capture the error
if (!$result) {
echo json_encode([
"new_replies" => false,
"debugData" => [
"error" => mysqli_error($admin_con),
"query" => $query,
"client_id" => $client_id,
"last_checked_reply_id" => $last_checked_reply_id
]
]);
exit();
}

// Initialize arrays for response
$reply_ids = [];
$ticket_ids = [];
while ($reply = mysqli_fetch_assoc($result)) {
$reply_ids[] = $reply['reply_id'];
$ticket_ids[] = $reply['ticket_id'];
}

echo json_encode([
"new_replies" => !empty($reply_ids),
"reply_ids" => $reply_ids,
"ticket_ids" => $ticket_ids,
"debugData" => [
"client_id" => $client_id,
"last_checked_reply_id" => $last_checked_reply_id,
"query" => $query,
"result_count" => count($reply_ids)
]
]);