<?php
// cms/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 {
    // Iniciar transacción
    $pdo->beginTransaction();

    // Sanitizar y validar inputs generales
    $cta_badge = htmlspecialchars(strip_tags($_POST['cta-badge'] ?? ''));
    $cta_title_1 = htmlspecialchars(strip_tags($_POST['cta-title-1'] ?? ''));
    $cta_title_2 = htmlspecialchars(strip_tags($_POST['cta-title-2'] ?? ''));
    $cta_description = htmlspecialchars(strip_tags($_POST['cta-description'] ?? ''));
    $cta_main_button_text = htmlspecialchars(strip_tags($_POST['cta-main-button-text'] ?? ''));
    $cta_main_button_subtext = htmlspecialchars(strip_tags($_POST['cta-main-button-subtext'] ?? ''));
    $cta_card_phone1_text = htmlspecialchars(strip_tags($_POST['cta-card-phone1-text'] ?? ''));
    $cta_card_phone2_text = htmlspecialchars(strip_tags($_POST['cta-card-phone2-text'] ?? ''));
    $cta_card_email_text = htmlspecialchars(strip_tags($_POST['cta-card-email-text'] ?? ''));

    $badges = json_decode($_POST['badges_json'] ?? '[]', true);
    
    // Insertar/Actualizar en la tabla principal
    $stmt = $pdo->query("SELECT id FROM cms_cta ORDER BY updated_at DESC LIMIT 1");
    $currentRecord = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($currentRecord) {
        $ctaId = $currentRecord['id'];
        $sql = "UPDATE cms_cta SET cta_badge=?, cta_title_1=?, cta_title_2=?, cta_description=?, cta_main_button_text=?, cta_main_button_subtext=?, cta_card_phone1_text=?, cta_card_phone2_text=?, cta_card_email_text=? WHERE id=?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$cta_badge, $cta_title_1, $cta_title_2, $cta_description, $cta_main_button_text, $cta_main_button_subtext, $cta_card_phone1_text, $cta_card_phone2_text, $cta_card_email_text, $ctaId]);
    } else {
        $sql = "INSERT INTO cms_cta (cta_badge, cta_title_1, cta_title_2, cta_description, cta_main_button_text, cta_main_button_subtext, cta_card_phone1_text, cta_card_phone2_text, cta_card_email_text) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$cta_badge, $cta_title_1, $cta_title_2, $cta_description, $cta_main_button_text, $cta_main_button_subtext, $cta_card_phone1_text, $cta_card_phone2_text, $cta_card_email_text]);
        $ctaId = $pdo->lastInsertId();
    }
    
    // Eliminar insignias antiguas
    if (isset($ctaId)) {
        $stmt = $pdo->prepare("DELETE FROM cms_cta_badges WHERE cta_id = ?");
        $stmt->execute([$ctaId]);

        // Insertar nuevas insignias
        $sqlBadge = "INSERT INTO cms_cta_badges (cta_id, badge_icon, badge_text) VALUES (?, ?, ?)";
        $stmtBadge = $pdo->prepare($sqlBadge);
        foreach ($badges as $badge) {
            $icon = htmlspecialchars(strip_tags($badge['icon'] ?? ''));
            $text = htmlspecialchars(strip_tags($badge['text'] ?? ''));
            if (!empty($text)) {
                $stmtBadge->execute([$ctaId, $icon, $text]);
            }
        }
    }

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