<?php
// /IAMarketing/api-db/ia-first-contact-message-fetch.php
ob_start();
require_once __DIR__ . '/../client-information.php'; 
ob_clean();

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

if (!isset($pdo)) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database connection error.']);
    exit;
}

$business_id = 1;

try {
    // Select all fields needed for the panel, ordered by creation date
    $sql = "SELECT id, message_es, message_en, context_input, created_at FROM ia_first_contact_message_results WHERE business_info_id = ? ORDER BY created_at DESC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$business_id]);
    $messages_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode(['success' => true, 'messages' => $messages_data, 'message' => 'Messages fetched successfully.'], JSON_UNESCAPED_UNICODE);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error while fetching messages: ' . $e->getMessage()]);
}
?>