<?php
/**
 * fetch_messages.php - Get messages for a ticket
 */

require_once '../config.php';

header('Content-Type: application/json');

if (!isset($_SESSION['customer_id'])) {
    echo json_encode(['success' => false, 'message' => 'Not logged in']);
    exit;
}

$ticket_id = (int)($_GET['ticket_id'] ?? 0);
$last_id = (int)($_GET['last_id'] ?? 0);
$customer_id = $_SESSION['customer_id'];

// Verify ticket ownership
$stmt = $conn->prepare("SELECT id, subject, status FROM support_tickets WHERE id = ? AND customer_id = ?");
$stmt->bind_param("ii", $ticket_id, $customer_id);
$stmt->execute();
$ticket = $stmt->get_result()->fetch_assoc();

if (!$ticket) {
    echo json_encode(['success' => false, 'message' => 'Ticket not found']);
    exit;
}

// Mark admin messages as read (customer has seen them)
$conn->query("UPDATE support_messages SET is_read = 1 WHERE ticket_id = $ticket_id AND sender_type = 'admin'");

// Get messages
$query = "
    SELECT id, sender_type as sender, message, image as attachment, 
           DATE_FORMAT(created_at, '%H:%i') as time,
           DATE_FORMAT(created_at, '%Y-%m-%d %H:%i:%s') as full_time
    FROM support_messages
    WHERE ticket_id = ?
    ORDER BY id ASC
";

if ($last_id > 0) {
    $query = "
        SELECT id, sender_type as sender, message, image as attachment, 
               DATE_FORMAT(created_at, '%H:%i') as time,
               DATE_FORMAT(created_at, '%Y-%m-%d %H:%i:%s') as full_time
        FROM support_messages
        WHERE ticket_id = ? AND id > ?
        ORDER BY id ASC
    ";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("ii", $ticket_id, $last_id);
} else {
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $ticket_id);
}

$stmt->execute();
$result = $stmt->get_result();

$messages = [];
while ($row = $result->fetch_assoc()) {
    // Add full path for attachments
    if ($row['attachment']) {
        $row['attachment'] = '/admin7/uploads/tickets/' . $row['attachment'];
    }
    $messages[] = $row;
}

echo json_encode([
    'success' => true,
    'messages' => $messages,
    'ticket' => [
        'id' => $ticket['id'],
        'subject' => $ticket['subject'],
        'status' => $ticket['status']
    ]
]);