<?php
// cms/form-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
    $form_badge = htmlspecialchars(strip_tags($_POST['form-badge'] ?? ''));
    $form_title_1 = htmlspecialchars(strip_tags($_POST['form-title-1'] ?? ''));
    $form_title_2 = htmlspecialchars(strip_tags($_POST['form-title-2'] ?? ''));
    $form_description = htmlspecialchars(strip_tags($_POST['form-description'] ?? ''));
    $form_container_title = htmlspecialchars(strip_tags($_POST['form-container-title'] ?? ''));
    $form_container_subtitle = htmlspecialchars(strip_tags($_POST['form-container-subtitle'] ?? ''));
    
    $benefits = json_decode($_POST['benefits_json'] ?? '[]', true);

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

    if ($currentRecord) {
        $formId = $currentRecord['id'];
        $sql = "UPDATE cms_form SET form_badge=?, form_title_1=?, form_title_2=?, form_description=?, form_container_title=?, form_container_subtitle=? WHERE id=?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$form_badge, $form_title_1, $form_title_2, $form_description, $form_container_title, $form_container_subtitle, $formId]);
    } else {
        $sql = "INSERT INTO cms_form (form_badge, form_title_1, form_title_2, form_description, form_container_title, form_container_subtitle) VALUES (?, ?, ?, ?, ?, ?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$form_badge, $form_title_1, $form_title_2, $form_description, $form_container_title, $form_container_subtitle]);
        $formId = $pdo->lastInsertId();
    }
    
    // Eliminar beneficios antiguos
    if (isset($formId)) {
        $stmt = $pdo->prepare("DELETE FROM cms_form_benefits WHERE form_id = ?");
        $stmt->execute([$formId]);

        // Insertar nuevos beneficios
        $sqlBenefit = "INSERT INTO cms_form_benefits (form_id, benefit_title, benefit_description) VALUES (?, ?, ?)";
        $stmtBenefit = $pdo->prepare($sqlBenefit);
        foreach ($benefits as $benefit) {
            $title = htmlspecialchars(strip_tags($benefit['title'] ?? ''));
            $description = htmlspecialchars(strip_tags($benefit['description'] ?? ''));
            if (!empty($title) || !empty($description)) {
                $stmtBenefit->execute([$formId, $title, $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: ' . $e->getMessage()]);
}
?>