<?php
// cms/social-proof-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();

    // 1. Sanitizar y decodificar inputs generales (CORRECCIÓN CLAVE: htmlspecialchars_decode)
    $social_proof_badge = strip_tags(htmlspecialchars_decode($_POST['reviews-badge'] ?? ''));
    $social_proof_title_1 = strip_tags(htmlspecialchars_decode($_POST['reviews-title-1'] ?? ''));
    $social_proof_title_2 = strip_tags(htmlspecialchars_decode($_POST['reviews-title-2'] ?? ''));
    
    // Decodificar los JSON de reseñas y enlaces
    $reviews = json_decode($_POST['reviews_json'] ?? '[]', true);
    $links = json_decode($_POST['links_json'] ?? '[]', true);

    // Insertar/Actualizar en la tabla principal
    $stmt = $pdo->query("SELECT id FROM cms_social_proof ORDER BY updated_at DESC LIMIT 1");
    $currentRecord = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($currentRecord) {
        $socialProofId = $currentRecord['id'];
        $sql = "UPDATE cms_social_proof SET social_proof_badge=?, social_proof_title_1=?, social_proof_title_2=? WHERE id=?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$social_proof_badge, $social_proof_title_1, $social_proof_title_2, $socialProofId]);
    } else {
        $sql = "INSERT INTO cms_social_proof (social_proof_badge, social_proof_title_1, social_proof_title_2) VALUES (?, ?, ?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$social_proof_badge, $social_proof_title_1, $social_proof_title_2]);
        $socialProofId = $pdo->lastInsertId();
    }
    
    // Eliminar reseñas y enlaces antiguos
    if (isset($socialProofId)) {
        $stmt = $pdo->prepare("DELETE FROM cms_reviews WHERE social_proof_id = ?");
        $stmt->execute([$socialProofId]);
        $stmt = $pdo->prepare("DELETE FROM cms_external_links WHERE social_proof_id = ?");
        $stmt->execute([$socialProofId]);

        // Insertar nuevas reseñas
        $sqlReview = "INSERT INTO cms_reviews (social_proof_id, review_avatar, review_name, review_rating, review_text) VALUES (?, ?, ?, ?, ?)";
        $stmtReview = $pdo->prepare($sqlReview);
        foreach ($reviews as $review) {
            // 2. CORRECCIÓN CLAVE: Decodificar y sanitizar reseñas
            $avatar = strip_tags(htmlspecialchars_decode($review['avatar'] ?? ''));
            $name = strip_tags(htmlspecialchars_decode($review['name'] ?? ''));
            $rating = intval($review['rating'] ?? 5);
            $text = strip_tags(htmlspecialchars_decode($review['text'] ?? ''));
            if (!empty($name) || !empty($text)) {
                $stmtReview->execute([$socialProofId, $avatar, $name, $rating, $text]);
            }
        }

        // Insertar nuevos enlaces
        $sqlLink = "INSERT INTO cms_external_links (social_proof_id, link_platform, link_text, link_url) VALUES (?, ?, ?, ?)";
        $stmtLink = $pdo->prepare($sqlLink);
        foreach ($links as $link) {
            // 3. CORRECCIÓN CLAVE: Decodificar y sanitizar enlaces
            $platform = strip_tags(htmlspecialchars_decode($link['platform'] ?? ''));
            $text = strip_tags(htmlspecialchars_decode($link['text'] ?? ''));
            $url = strip_tags(htmlspecialchars_decode($link['url'] ?? ''));
            if (!empty($text) && !empty($url)) {
                $stmtLink->execute([$socialProofId, $platform, $text, $url]);
            }
        }
    }

    $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()]);
}
?>