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

// Validación de la estructura de datos para una OFERTA INDIVIDUAL
if (!isset($data['offer_name']) || !isset($data['promo_text_es']) || !isset($data['inputs']['mainService'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Required offer data (name, text, or inputs) not received.']);
    exit;
}

try {
    $business_id = 1; // Assuming business_info_id = 1
    
    // 1. Aplicar el límite de 5 ofertas individuales
    $limit_sql = "SELECT COUNT(id) AS count FROM ia_offers_promotions_results WHERE business_info_id = ?";
    $limit_stmt = $pdo->prepare($limit_sql);
    $limit_stmt->execute([$business_id]);
    $current_count = $limit_stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
    if ($current_count >= 5) {
        http_response_code(409); // Conflict, límite alcanzado
        echo json_encode(['success' => false, 'message' => 'Límite de 5 ofertas individuales alcanzado. Elimina una para guardar la nueva.']);
        exit;
    }
    
    // 2. Insertar el nuevo registro
    $sql = "INSERT INTO ia_offers_promotions_results (
        business_info_id, offer_name, offer_description, promo_text_es, promo_text_en, 
        service_input, objective_input
    ) VALUES (?, ?, ?, ?, ?, ?, ?)";
    
    $stmt = $pdo->prepare($sql);
    $success = $stmt->execute([
        $business_id,
        $data['offer_name'],
        $data['offer_description'],
        $data['promo_text_es'],
        $data['promo_text_en'],
        $data['inputs']['mainService'],
        $data['inputs']['offerObjective']
    ]);

    if ($success) {
        $new_id = $pdo->lastInsertId();
        echo json_encode([
            'success' => true, 
            'message' => 'Oferta individual guardada con éxito.',
            'new_offer_id' => $new_id
        ]);
    } else {
         http_response_code(500);
         echo json_encode(['success' => false, 'message' => 'Insert failed.']);
    }

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error while creating Offer Record: ' . $e->getMessage()]);
}
?>