<?php

namespace HulkPlugins\ElementorPro\Forms\AdvancedFields\Routes;

use Elementor\Plugin;
use HulkPlugins\ElementorPro\Forms\AdvancedFields\Models\SettingsModel;
use WP_REST_Request;
use WP_REST_Server;
use const HulkPlugins\ElementorPro\Forms\AdvancedFields\GROUP;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

class SettingsRoute {

	public function __construct() {

		register_rest_route(
			GROUP . '/v1',
			'/save-settings',
			[
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => [ $this, 'save_settings' ],
				'permission_callback' => function () {
					return current_user_can( 'manage_options' );
				},
			]
		);
	}

	public function save_settings( WP_REST_Request $request ) {
		$params = $request->get_params();
		$settingsModel = SettingsModel::getInstance();
		$settingsModel->updateSettings( $params );
		// Check if Elementor is loaded
		if ( did_action( 'elementor/loaded' ) ) {
			// Clear Elementor cache
			Plugin::instance()->files_manager->clear_cache();
		}
		return rest_ensure_response( esc_attr__( 'Settings Saved.', 'advanced-fields-for-elementor-forms' ) );
	}
}
