<?php
// cms/offer-read.php
header('Content-Type: application/json');

require_once('db_connection.php');

try {
    $data = [
        'offer' => [],
        'business' => []
    ];

    // 1. Obtener datos de la oferta
    $stmtOffer = $pdo->query("SELECT * FROM cms_offer_page ORDER BY updated_at DESC LIMIT 1");
    $offerData = $stmtOffer->fetch(PDO::FETCH_ASSOC);

    // 2. Obtener datos del negocio (para el logo)
    $stmtBusiness = $pdo->query("SELECT logo_url FROM business_info LIMIT 1");
    $businessData = $stmtBusiness->fetch(PDO::FETCH_ASSOC);
    
    // Asignación robusta para business data
    if ($businessData === false) {
        // Mantenemos el fallback del logo si la tabla business_info falla o est\u00e1 vac\u00eda, ya que es un elemento visual cr\u00edtico.
        $data['business'] = ['logo_url' => 'img/default-logo.png']; 
    } else {
        $data['business'] = $businessData;
    }

    // Asignación robusta para offer data
    if ($offerData === false) {

        $data['offer'] = []; 
    } else {
        $data['offer'] = $offerData;
    }

    // JSON_UNESCAPED_UNICODE ayuda a prevenir problemas con caracteres de codificación
    echo json_encode(['success' => true, 'data' => $data], JSON_UNESCAPED_UNICODE);
} catch (PDOException $e) {
    http_response_code(500);
    error_log("PDO Error in offer-read.php: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Error de Base de Datos Al Cargar Oferta.']);
} catch (Exception $e) {
    http_response_code(500);
    error_log("General Error in offer-read.php: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Error de Servidor Al Cargar Oferta.']);
}
?>