<?php
// File: modules/insert-gtm-script.php

if ( ! defined('ABSPATH') ) { exit; }

require_once plugin_dir_path(__FILE__) . '../includes/sac-utils.php';

// REST API to insert GTM code
add_action('rest_api_init', function () {
    register_rest_route('myaio/v1', '/insert-gtm-script', [
        'methods'             => WP_REST_Server::CREATABLE, // POST
        'callback'            => 'myaio_sac_insert_gtm_script',
        // keep output unchanged (Unauthorized handled in callback)
        'permission_callback' => 'myaio_sac_rest_permission_check',
    ]);
});

function myaio_sac_insert_gtm_script( WP_REST_Request $request ) {

    // ✅ Consistent auth across all modules (same output)
    $auth = function_exists('myaio_sac_require_api_key_or_401') ? myaio_sac_require_api_key_or_401($request) : null;
    if ($auth !== true) {
        return $auth instanceof WP_REST_Response ? $auth : new WP_REST_Response(['error' => 'Unauthorized'], 401);
    }

    // Support JSON body + params
    $json = $request->get_json_params();
    $get_param = function($key) use ($request, $json) {
        if (is_array($json) && array_key_exists($key, $json)) return $json[$key];
        return $request->get_param($key);
    };

    $position = sanitize_text_field( (string) $get_param('position') ); // 'header' or 'footer'
    $script   = (string) $get_param('script');

    if ( ! in_array($position, ['header', 'footer'], true) || trim($script) === '' ) {
        return new WP_REST_Response(['error' => 'Invalid position or script'], 400);
    }

    $option_name = ($position === 'header') ? 'myaio_sac_gtm_header_script' : 'myaio_sac_gtm_footer_script';

    // Allow script tags only (same behavior)
    $allowed_tags = [
        'script' => [
            'type'  => true,
            'src'   => true,
            'async' => true,
            'defer' => true,
            'id'    => true,
        ],
    ];

    $safe_script = wp_kses($script, $allowed_tags);

    update_option($option_name, $safe_script);

    return rest_ensure_response([
        'success' => true,
        'message' => "Script successfully saved to $position.",
    ]);
}
