<?php
// /IAMarketing/api-db/ia-social-post-creator-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 un POST INDIVIDUAL
if (!isset($data['post_type']) || !isset($data['es_copy']) || !isset($data['en_copy']) || !isset($data['inputs']['product_service_description_simplified'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Required post data (type, copy, or inputs) not received for individual post save.']);
    exit;
}

try {
    $business_id = 1; // Assuming business_info_id = 1
    
    // 1. Aplicar el límite (Máximo 5 posts guardados)
    // USANDO NOMBRE DE TABLA CORRECTO: ia_social_post_creator_results
    $limit_sql = "SELECT COUNT(id) AS count FROM ia_social_post_creator_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 publicaciones individuales alcanzado. Elimina una para guardar la nueva.']);
        exit;
    }

    // 2. Insertar el nuevo registro de post individual en la tabla correcta
    $sql = "INSERT INTO ia_social_post_creator_results (
        business_info_id, post_type, es_copy, es_hashtags, en_copy, en_hashtags,
        product_service_input, client_description_input
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
    
    $stmt = $pdo->prepare($sql);
    $success = $stmt->execute([
        $business_id,
        $data['post_type'],
        $data['es_copy'],
        $data['es_hashtags'] ?? NULL, // Se asume que viene como string JSON
        $data['en_copy'], // Versión EN incluida
        $data['en_hashtags'] ?? NULL, // Se asume que viene como string JSON
        $data['inputs']['product_service_description_simplified'],
        $data['inputs']['client_description_simplified']
    ]);

    if ($success) {
        $new_id = $pdo->lastInsertId();
        echo json_encode([
            'success' => true, 
            'message' => 'Publicación individual guardada con éxito.',
            'new_post_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 post: ' . $e->getMessage()]);
}
?>