<?php
session_start();
require_once '../../config/database.php';
require_once '../../includes/chat_helper.php';
header('Content-Type: application/json');
if (!isset($_SESSION['customer_id'])) { echo json_encode(['success'=>false,'message'=>'Unauthorized']); exit; }
$request_id = (int)($_GET['request_id'] ?? 0);
$last_id = (int)($_GET['last_id'] ?? 0);
try {
    $database = new Database(); $db = $database->getConnection(); ensureChatTables($db);
    $stmt = $db->prepare("SELECT id FROM service_requests WHERE id=:id AND customer_id=:customer_id LIMIT 1");
    $stmt->execute([':id'=>$request_id, ':customer_id'=>$_SESSION['customer_id']]);
    if (!$stmt->fetch()) { echo json_encode(['success'=>false,'message'=>'Request not found.']); exit; }
    $conversation = getOrCreateConversation($db, $request_id);
    $stmt = $db->prepare("SELECT cm.*, CONCAT(cu.first_name, ' ', cu.last_name) AS csr_name
                          FROM chat_messages cm
                          LEFT JOIN csr_users cu ON cm.sender_type='csr' AND cu.id = cm.sender_id
                          WHERE cm.conversation_id=:conversation_id AND cm.id > :last_id
                          ORDER BY cm.created_at ASC, cm.id ASC");
    $stmt->bindValue(':conversation_id', (int)$conversation['id'], PDO::PARAM_INT);
    $stmt->bindValue(':last_id', $last_id, PDO::PARAM_INT);
    $stmt->execute();
    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $db->prepare("UPDATE chat_conversations SET last_customer_read_at = NOW() WHERE id = :id")->execute([':id'=>$conversation['id']]);
    echo json_encode(['success'=>true,'messages'=>$messages]);
} catch(Exception $e) { echo json_encode(['success'=>false,'message'=>$e->getMessage()]); }
?>
