<?php
// cms/reviews-cta-update.php
header('Content-Type: application/json');

require_once('db_connection.php');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Método No Permitido']);
    exit;
}

try {
    $pdo->beginTransaction();
    
    // 1. Sanitizar y obtener los datos del CTA (Textos)
    $badge_text = strip_tags(htmlspecialchars_decode($_POST['badge_text'] ?? ''));
    $title_1 = strip_tags(htmlspecialchars_decode($_POST['title_1'] ?? ''));
    $title_2 = strip_tags(htmlspecialchars_decode($_POST['title_2'] ?? ''));
    $description = strip_tags(htmlspecialchars_decode($_POST['description'] ?? ''));

    // 2. Actualizar la tabla principal
    $sqlHero = "UPDATE cms_reviews_cta SET 
        badge_text=?, title_1=?, title_2=?, description=?, updated_at=NOW() 
        WHERE id=1";
    
    $stmtHero = $pdo->prepare($sqlHero);
    $stmtHero->execute([
        $badge_text, $title_1, $title_2, $description
    ]);

    // 3. Manejar la lista de badges inferiores (CRUD de cms_reviews_cta_badges)
    $badges = json_decode($_POST['badges_data'] ?? '[]', true);
    $existingBadgeIds = [];

    foreach ($badges as $badge) {
        $id = intval($badge['id'] ?? 0);
        $badge_icon = strip_tags($badge['badge_icon'] ?? '');
        $badge_text = strip_tags($badge['badge_text'] ?? '');
        $sort_order = intval($badge['sort_order'] ?? 0);

        if ($id > 0) {
            // Actualizar
            $sql = "UPDATE cms_reviews_cta_badges SET 
                badge_icon=?, badge_text=?, sort_order=? 
                WHERE id=? AND cta_id=1";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$badge_icon, $badge_text, $sort_order, $id]);
            $existingBadgeIds[] = $id;
        } else {
            // Crear nuevo
            $sql = "INSERT INTO cms_reviews_cta_badges (cta_id, badge_icon, badge_text, sort_order) 
                    VALUES (1, ?, ?, ?)";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$badge_icon, $badge_text, $sort_order]);
            $existingBadgeIds[] = $pdo->lastInsertId();
        }
    }

    // 4. Eliminar badges que no fueron enviados
    if (!empty($existingBadgeIds)) {
        $placeholders = implode(',', array_fill(0, count($existingBadgeIds), '?'));
        $sqlDelete = "DELETE FROM cms_reviews_cta_badges WHERE cta_id = 1 AND id NOT IN ($placeholders)";
        $stmtDelete = $pdo->prepare($sqlDelete);
        $stmtDelete->execute($existingBadgeIds);
    } else {
        $pdo->exec("DELETE FROM cms_reviews_cta_badges WHERE cta_id = 1");
    }

    $pdo->commit();
    echo json_encode(['success' => true, 'message' => 'SiteFlow Actualizado Exitosamente']);
} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    http_response_code(500);
    error_log("Error en reviews-cta-update.php: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Error Al Guardar: ' . $e->getMessage()]);
}
?>