<?php
// cms/confirmation-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 DECODIFICAR inputs generales (para evitar &amp;)
    $header_badge = strip_tags(htmlspecialchars_decode($_POST['header-badge'] ?? ''));
    $header_title_1 = strip_tags(htmlspecialchars_decode($_POST['header-title-1'] ?? ''));
    $header_title_2 = strip_tags(htmlspecialchars_decode($_POST['header-title-2'] ?? ''));
    $header_description = strip_tags(htmlspecialchars_decode($_POST['header-description'] ?? ''));
    $process_badge = strip_tags(htmlspecialchars_decode($_POST['process-badge'] ?? ''));
    $social_text = strip_tags(htmlspecialchars_decode($_POST['social-text'] ?? ''));
    
    // 2. Decodificar los pasos (repeater)
    $steps = json_decode($_POST['steps_json'] ?? '[]', true);

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

    $sql = "UPDATE cms_confirmation SET header_badge=?, header_title_1=?, header_title_2=?, header_description=?, process_badge=?, social_text=? WHERE id=?";
    $stmt = $pdo->prepare($sql);
    
    if ($currentRecord) {
        $confirmationId = $currentRecord['id'];
        $stmt->execute([$header_badge, $header_title_1, $header_title_2, $header_description, $process_badge, $social_text, $confirmationId]);
    } else {
        // Asumiendo que el ID 1 se usa como default si no existe
        $sqlInsert = "INSERT INTO cms_confirmation (id, header_badge, header_title_1, header_title_2, header_description, process_badge, social_text) VALUES (1, ?, ?, ?, ?, ?, ?)";
        $stmtInsert = $pdo->prepare($sqlInsert);
        $stmtInsert->execute([$header_badge, $header_title_1, $header_title_2, $header_description, $process_badge, $social_text]);
        $confirmationId = 1;
    }
    
    // 3. Eliminar y reinsertar pasos
    if (isset($confirmationId)) {
        $stmtDelete = $pdo->prepare("DELETE FROM cms_confirmation_steps WHERE confirmation_id = ?");
        $stmtDelete->execute([$confirmationId]);

        $sqlStep = "INSERT INTO cms_confirmation_steps (confirmation_id, step_icon, step_title, step_description) VALUES (?, ?, ?, ?)";
        $stmtStep = $pdo->prepare($sqlStep);
        
        foreach ($steps as $step) {
            // Decodificar también los pasos del repeater
            $step_icon = strip_tags(htmlspecialchars_decode($step['icon'] ?? ''));
            $step_title = strip_tags(htmlspecialchars_decode($step['title'] ?? ''));
            $step_description = strip_tags(htmlspecialchars_decode($step['description'] ?? ''));

            if (!empty($step_title)) {
                $stmtStep->execute([$confirmationId, $step_icon, $step_title, $step_description]);
            }
        }
    }

    $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 Al Guardar: ' . $e->getMessage()]);
}
?>