<?php
// File: modules/add-footer-links.php

defined('ABSPATH') || exit;

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

add_action('rest_api_init', function () {
    register_rest_route('myaio/v1', '/add-footer-links', [
        'methods'             => WP_REST_Server::CREATABLE,
        'callback'            => 'myaio_sac_add_multiple_footer_links',
        'permission_callback' => 'myaio_sac_rest_permission_check',
        'args'                => [

            // ADD THESE (important for POST endpoints)
            'key' => [
                'required' => false,
                'type'     => 'string',
            ],
            'api_key' => [
                'required' => false,
                'type'     => 'string',
            ],

            'links' => [
                'required'          => true,
                'type'              => 'array',
                'validate_callback' => function ($value) {
                    return is_array($value);
                },
            ],
        ],
    ]);
});

if (!function_exists('myaio_sac_add_multiple_footer_links')) {
    function myaio_sac_add_multiple_footer_links(WP_REST_Request $request) {

        $incoming_links = $request->get_param('links');

        if (!is_array($incoming_links)) {
            return new WP_Error(
                'invalid_data',
                'The `links` parameter must be an array of objects with `url` and `text`.',
                ['status' => 400]
            );
        }

        $stored_links = get_option('myaio_sac_footer_links', []);
        if (!is_array($stored_links)) $stored_links = [];

        $added_links = [];

        foreach ($incoming_links as $link) {
            if (!is_array($link)) continue;

            $url  = esc_url_raw($link['url'] ?? '');
            $text = sanitize_text_field($link['text'] ?? '');

            if (empty($url) || empty($text)) continue;

            $stored_links[] = [
                'url'  => $url,
                'text' => $text,
            ];

            $added_links[] = [
                'url'  => $url,
                'text' => $text,
            ];
        }

        update_option('myaio_sac_footer_links', $stored_links, false);

        return new WP_REST_Response([
            'success'     => true,
            'message'     => 'Footer links added successfully.',
            'added_count' => count($added_links),
            'added_links' => $added_links
        ], 200);
    }
}