<?php
// /IAMarketing/api-db/ia-offers-promotions-update.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;
}

$data = json_decode(file_get_contents('php://input'), true);

if (!isset($data['id']) || !isset($data['offer_name']) || !isset($data['promo_text_es'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Required offer ID or content not received.']);
    exit;
}

$offer_id = $data['id'];
$business_id = 1;

try {
    $sql = "UPDATE ia_offers_promotions_results SET 
        offer_name = ?, 
        offer_description = ?,
        promo_text_es = ?, 
        promo_text_en = ?
        WHERE id = ? AND business_info_id = ?";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        $data['offer_name'],
        $data['offer_description'],
        $data['promo_text_es'],
        $data['promo_text_en'],
        $offer_id,
        $business_id
    ]);
    
    if ($stmt->rowCount() > 0) {
        echo json_encode(['success' => true, 'message' => 'Oferta individual actualizada con éxito.']);
    } else {
        echo json_encode(['success' => true, 'message' => 'Oferta actualizada (no cambios o registro no encontrado).']);
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error while updating Offer Record: ' . $e->getMessage()]);
}
?>