<?php

namespace WooSwatches;

defined('ABSPATH') || exit;

class Ajax {

    public function __construct() {
        add_action( 'wp_ajax_gs_swatches_ajax_handler', array( $this, 'ajax_handler' ) );
    }

    public function ajax_handler() {
		check_ajax_referer( 'gs_variation_swatches' );	
		
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( __( 'You do not have permission to perform this action.', 'gs-woo-variation' ), 403 );
		}

		if ( ! empty( $_POST['route'] ) ) {
			$route_handler = 'handle_' . sanitize_key( $_POST['route'] );
			if ( is_callable( get_class( $this ), $route_handler ) ) {
				$this->$route_handler();
			}
		}

		wp_send_json_error( array( 'message' => __( 'Something is wrong, no route found', 'gs-woo-variation' ), ), 400 );
	}

	public function handle_save_settings() {
		$settings = plugin()->modules->save_settings( $_POST['settings'] );
		if ( ! empty( $settings ) ) {
			wp_send_json_success(
				array(
					'message' => __( 'Settings Updated', 'gs-woo-variation' ),
					'data'    => $settings,
				)
			);
		}
		wp_send_json_error( __( 'Something is wrong, please try again!', 'gs-woo-variation' ) );
	}

	public function handle_get_module_settings() {
		$settings = plugin()->modules->get_module_settings( $_POST['module_name'] );
		wp_send_json_success( array( 'data' => $settings ) );
	}
	
}
