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

    $differentiators_page_enabled = isset($_POST['differentiators_page_enabled']) ? 1 : 0;
    $process_page_enabled = isset($_POST['process_page_enabled']) ? 1 : 0;
    $coverage_page_enabled = isset($_POST['coverage_page_enabled']) ? 1 : 0;
    $services_page_enabled = isset($_POST['services_page_enabled']) ? 1 : 0;
    $results_page_enabled = isset($_POST['results_page_enabled']) ? 1 : 0;
    $reviews_page_enabled = isset($_POST['reviews_page_enabled']) ? 1 : 0;
    $cta_page_enabled = isset($_POST['cta_page_enabled']) ? 1 : 0;
    $hours_page_enabled = isset($_POST['hours_page_enabled']) ? 1 : 0;
    $exit_intent_enabled = isset($_POST['exit_intent_enabled']) ? 1 : 0;

    $stmt = $pdo->query("SELECT id FROM business_info ORDER BY updated_at DESC LIMIT 1");
    $currentRecord = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($currentRecord) {
        $id = $currentRecord['id'];
        $sql = "UPDATE sections_enabled SET 
            differentiators_page_enabled=?, process_page_enabled=?, coverage_page_enabled=?,
            services_page_enabled=?, results_page_enabled=?, reviews_page_enabled=?,
            cta_page_enabled=?, hours_page_enabled=?, exit_intent_enabled=?
            WHERE business_info_id=?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            $differentiators_page_enabled, $process_page_enabled, $coverage_page_enabled,
            $services_page_enabled, $results_page_enabled, $reviews_page_enabled,
            $cta_page_enabled, $hours_page_enabled, $exit_intent_enabled, $id
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'No se encontro un registro de informacion del negocio']);
        exit;
    }

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