<?php
// /IAMarketing/api-db/ia-social-post-creator-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['es_copy']) || !isset($data['en_copy'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Required Post ID or content (ES/EN) not received.']);
    exit;
}

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

try {
    // USANDO NOMBRE DE TABLA CORRECTO: ia_social_post_creator_results
    $sql = "UPDATE ia_social_post_creator_results SET 
        es_copy = ?, 
        es_hashtags = ?,
        en_copy = ?, 
        en_hashtags = ?
        WHERE id = ? AND business_info_id = ?";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        $data['es_copy'],
        $data['es_hashtags'] ?? NULL,
        $data['en_copy'], // Versi¨®n EN incluida
        $data['en_hashtags'] ?? NULL,
        $post_id,
        $business_id
    ]);
    
    if ($stmt->rowCount() > 0) {
        echo json_encode(['success' => true, 'message' => 'Publicaci¨®n individual actualizada con ¨¦xito.']);
    } else {
        echo json_encode(['success' => true, 'message' => 'Publicaci¨®n actualizada (no cambios o registro no encontrado).']);
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error while updating post: ' . $e->getMessage()]);
}
?>