<?php
namespace NCPC\Api\Admin\Settings;

use WP_Error;
use WP_Post;
use WP_Query;
use WP_REST_Controller;

/**
 * class for api routes reaching generals settings
 */
class NCPC_Api_General_Settings extends WP_REST_Controller
{

    /**
     * [__construct description]
     */
    public function __construct()
    {
        $this->namespace = 'ncpc/v2';
        $this->rest_base = 'configs/(?P<config_id>\d+)/settings/generals';
    }
    /**
     * Register the routes
     *
     * @return void
     */
    public function register_routes()
    {
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base,
            array(
                array(
                    'methods' => \WP_REST_Server::READABLE,
                    'callback' => array($this, 'get_generals_settings'),
                    'permission_callback' => array($this, 'get_config_permissions_check'),
                    'args' => array(
                        'config_id' => array(
                            'type' => 'integer',
                            'required' => true,
                        )
                    ),
                )
            )
        );
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . "/customizer",
            array(
                array(
                    'methods' => \WP_REST_Server::EDITABLE,
                    'callback' => array($this, 'update_customizer_options_generals_settings'),
                    'permission_callback' => array($this, 'get_config_permissions_check'),
                    'args' => array(
                        'config_id' => array(
                            'type' => 'integer',
                            'required' => true,
                        )
                    ),
                )
            )
        );
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . "/mobile",
            array(
                array(
                    'methods' => \WP_REST_Server::EDITABLE,
                    'callback' => array($this, 'update_mobile_options_generals_settings'),
                    'permission_callback' => array($this, 'get_config_permissions_check'),
                    'args' => array(
                        'config_id' => array(
                            'type' => 'integer',
                            'required' => true,
                        )
                    ),
                )
            )
        );
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . "/product",
            array(
                array(
                    'methods' => \WP_REST_Server::EDITABLE,
                    'callback' => array($this, 'update_product_options_generals_settings'),
                    'permission_callback' => array($this, 'get_config_permissions_check'),
                    'args' => array(
                        'config_id' => array(
                            'type' => 'integer',
                            'required' => true,
                        )
                    ),
                )
            )
        );
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . "/mode",
            array(
                array(
                    'methods' => \WP_REST_Server::EDITABLE,
                    'callback' => array($this, 'update_mode_options_generals_settings'),
                    'permission_callback' => array($this, 'get_config_permissions_check'),
                    'args' => array(
                        'config_id' => array(
                            'type' => 'integer',
                            'required' => true,
                        )
                    ),
                )
            )
        );
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . "/output-file",
            array(
                array(
                    'methods' => \WP_REST_Server::EDITABLE,
                    'callback' => array($this, 'update_output_file_options_generals_settings'),
                    'permission_callback' => array($this, 'get_config_permissions_check'),
                    'args' => array(
                        'config_id' => array(
                            'type' => 'integer',
                            'required' => true,
                        )
                    ),
                )
            )
        );
    }

    /**
     * Get all generals settings
     * @param \WP_REST_Request $request Full details about the request.
     * @return \WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
     */
    public function get_generals_settings($request)
    {
        $id = $request->get_param('config_id');
        if ($id != 0) {
            $post = get_post($id);
            if ($post) {
                $meta_value = get_post_meta($id, 'ncpc-configs-meta', true);
                if (empty($meta_value)) {
                    return rest_ensure_response(["success" => false, "message" => __("No Settings found", "neon-channel-product-customizer-free")]);
                } else {
                    if (isset($meta_value["data"]["settings"]["generals"])) {
                        return rest_ensure_response($meta_value["data"]["settings"]["generals"]);
                    }
                    return rest_ensure_response(["success" => false, "message" => __("No generals Settings found", "neon-channel-product-customizer-free")]);
                }
            } else {
                return rest_ensure_response(["success" => false, "message" => __("Custom ID invalid", "neon-channel-product-customizer-free")]);
            }
        } else {
            return rest_ensure_response(["success" => false, "message" => __("Custom ID invalid", "neon-channel-product-customizer-free")]);
        }
    }
    /**
     * Update customizer options of generals settings 
     * @param \WP_REST_Request $request Full details about the request.
     * @return \WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
     */
    public function update_customizer_options_generals_settings($request)
    {
        $id = $request->get_param('config_id');
        $customizer_options = json_decode($request->get_body(), true);
        if ($id != 0) {
            $post = get_post($id);
            if ($post) {
                $meta_value = get_post_meta($id, 'ncpc-configs-meta', true);
                if (empty($meta_value)) {
                    return rest_ensure_response(["success" => false, "message" => __("Update customizer options in generals settings failed", "neon-channel-product-customizer-free")]);
                } else {
                    if ($meta_value["data"]["settings"]["generals"]['customizer'] !== $customizer_options) {
                        $meta_value["data"]["settings"]["generals"]['customizer'] = $customizer_options;
                        $response = update_post_meta($id, 'ncpc-configs-meta', $meta_value);

                        if ($response) {
                            return rest_ensure_response(["success" => true, "message" => __("Customizer options in generals settings updated successfully")]);
                        } else {
                            return rest_ensure_response(["success" => false, "message" => __("Update customizer options in generals settings failed", "neon-channel-product-customizer-free")]);
                        }
                    } else {
                        return rest_ensure_response(["success" => "same", "message" => __("No change observed on customizer options in generals settings", "neon-channel-product-customizer-free")]);
                    }
                }
            } else {
                return rest_ensure_response(["success" => false, "message" => __("Custom ID invalid", "neon-channel-product-customizer-free")]);
            }
        } else {
            return rest_ensure_response(["success" => false, "message" => __("Custom ID invalid", "neon-channel-product-customizer-free")]);
        }
    }
    /**
     * Update mobile options of generals settings 
     * @param \WP_REST_Request $request Full details about the request.
     * @return \WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
     */
    public function update_mobile_options_generals_settings($request)
    {
        $id = $request->get_param('config_id');
        $mobile_options = json_decode($request->get_body(), true);
        if ($id != 0) {
            $post = get_post($id);
            if ($post) {
                $meta_value = get_post_meta($id, 'ncpc-configs-meta', true);
                if (empty($meta_value)) {
                    return rest_ensure_response(["success" => false, "message" => __("Update mobile options in generals settings failed", "neon-channel-product-customizer-free")]);
                } else {
                    if ($meta_value["data"]["settings"]["generals"]['mobile'] !== $mobile_options) {
                        $meta_value["data"]["settings"]["generals"]['mobile'] = $mobile_options;
                        $response = update_post_meta($id, 'ncpc-configs-meta', $meta_value);

                        if ($response) {
                            return rest_ensure_response(["success" => true, "message" => __("Mobile options in generals settings updated successfully", "neon-channel-product-customizer-free")]);
                        } else {
                            return rest_ensure_response(["success" => false, "message" => __("Update mobile options in generals settings failed", "neon-channel-product-customizer-free")]);
                        }
                    } else {
                        return rest_ensure_response(["success" => "same", "message" => __("No change observed on mobile options in generals settings failed", "neon-channel-product-customizer-free")]);
                    }
                }
            } else {
                return rest_ensure_response(["success" => false, "message" => __("Custom ID invalid", "neon-channel-product-customizer-free")]);
            }
        } else {
            return rest_ensure_response(["success" => false, "message" => __("Custom ID invalid", "neon-channel-product-customizer-free")]);
        }
    }
    /**
     * Update product options of generals settings 
     * @param \WP_REST_Request $request Full details about the request.
     * @return \WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
     */
    public function update_product_options_generals_settings($request)
    {
        $id = $request->get_param('config_id');
        $product_options = json_decode($request->get_body(), true);
        if ($id != 0) {
            $post = get_post($id);
            if ($post) {
                $meta_value = get_post_meta($id, 'ncpc-configs-meta', true);
                if (empty($meta_value)) {
                    return rest_ensure_response(["success" => false, "message" => __("Update product options in generals settings failed", "neon-channel-product-customizer-free")]);
                } else {
                    if ($meta_value["data"]["settings"]["generals"]['product'] !== $product_options) {
                        $meta_value["data"]["settings"]["generals"]['product'] = $product_options;
                        $response = update_post_meta($id, 'ncpc-configs-meta', $meta_value);

                        if ($response) {
                            return rest_ensure_response(["success" => true, "message" => __("Product options in generals settings added successfully", "neon-channel-product-customizer-free")]);
                        } else {
                            return rest_ensure_response(["success" => false, "message" => __("Update product options in generals settings failed", "neon-channel-product-customizer-free")]);
                        }
                    } else {
                        return rest_ensure_response(["success" => "same", "message" => __("No change observed product options in generals settings", "neon-channel-product-customizer-free")]);
                    }
                }
            } else {
                return rest_ensure_response(["success" => false, "message" => __("Custom ID invalid", "neon-channel-product-customizer-free")]);
            }
        } else {
            return rest_ensure_response(["success" => false, "message" => __("Custom ID invalid", "neon-channel-product-customizer-free")]);
        }
    }
    /**
     * Update mode options of generals settings 
     * @param \WP_REST_Request $request Full details about the request.
     * @return \WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
     */
    public function update_mode_options_generals_settings($request)
    {
        $id = $request->get_param('config_id');
        $mode_options = json_decode($request->get_body(), true);
        if ($id != 0) {
            $post = get_post($id);
            if ($post) {
                $meta_value = get_post_meta($id, 'ncpc-configs-meta', true);
                if (empty($meta_value)) {
                    return rest_ensure_response(["success" => false, "message" => __("Update mode options in generals settings failed", "neon-channel-product-customizer-free")]);
                } else {
                    if ($meta_value["data"]["settings"]["generals"]['mode'] !== $mode_options) {
                        $meta_value["data"]["settings"]["generals"]['mode'] = $mode_options;
                        $response = update_post_meta($id, 'ncpc-configs-meta', $meta_value);

                        if ($response) {
                            return rest_ensure_response(["success" => true, "message" => __("Mode options in generals settings added successfully", "neon-channel-product-customizer-free")]);
                        } else {
                            return rest_ensure_response(["success" => false, "message" => __("Update mode options in generals settings failed", "neon-channel-product-customizer-free")]);
                        }
                    } else {
                        return rest_ensure_response(["success" => "same", "message" => __("No change observed mode options in generals settings", "neon-channel-product-customizer-free")]);
                    }
                }
            } else {
                return rest_ensure_response(["success" => false, "message" => __("Custom ID invalid", "neon-channel-product-customizer-free")]);
            }
        } else {
            return rest_ensure_response(["success" => false, "message" => __("Custom ID invalid", "neon-channel-product-customizer-free")]);
        }
    }
    /**
     * Update request a quote options of generals settings 
     * @param \WP_REST_Request $request Full details about the request.
     * @return \WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
     */
    public function update_request_quote_options_generals_settings($request)
    {
        $id = $request->get_param('config_id');
        $requestQuote = json_decode($request->get_body(), true);
        if ($id != 0) {
            $post = get_post($id);
            if ($post) {
                $meta_value = get_post_meta($id, 'ncpc-configs-meta', true);
                if (empty($meta_value)) {
                    return rest_ensure_response(["success" => false, "message" => __("Update request a quote options in generals settings failed", "neon-channel-product-customizer-free")]);
                } else {
                    if ($meta_value["data"]["settings"]["generals"]['requestQuote'] !== $requestQuote) {
                        $meta_value["data"]["settings"]["generals"]['requestQuote'] = $requestQuote;
                        $response = update_post_meta($id, 'ncpc-configs-meta', $meta_value);

                        if ($response) {
                            return rest_ensure_response(["success" => true, "message" => __("Request a quote options in generals settings added successfully", "neon-channel-product-customizer-free")]);
                        } else {
                            return rest_ensure_response(["success" => false, "message" => __("Update request a quote options in generals settings failed", "neon-channel-product-customizer-free")]);
                        }
                    } else {
                        return rest_ensure_response(["success" => "same", "message" => __("No change observed request a quote options in generals settings", "neon-channel-product-customizer-free")]);
                    }
                }
            } else {
                return rest_ensure_response(["success" => false, "message" => __("Custom ID invalid", "neon-channel-product-customizer-free")]);
            }
        } else {
            return rest_ensure_response(["success" => false, "message" => __("Custom ID invalid", "neon-channel-product-customizer-free")]);
        }
    }

    /**
     * Update output file options of generals settings 
     * @param \WP_REST_Request $request Full details about the request.
     * @return \WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
     */
    public function update_output_file_options_generals_settings($request)
    {
        $id = $request->get_param('config_id');
        $output_file_options = json_decode($request->get_body(), true);
        if ($id != 0) {
            $post = get_post($id);
            if ($post) {
                $meta_value = get_post_meta($id, 'ncpc-configs-meta', true);
                if (empty($meta_value)) {
                    return rest_ensure_response(["success" => false, "message" => __("Update output file options in generals settings failed", "neon-channel-product-customizer-free")]);
                } else {
                    if ($meta_value["data"]["settings"]["generals"]['output'] !== $output_file_options) {
                        $meta_value["data"]["settings"]["generals"]['output'] = $output_file_options;
                        $response = update_post_meta($id, 'ncpc-configs-meta', $meta_value);

                        if ($response) {
                            return rest_ensure_response(["success" => true, "message" => __("Output file options in generals settings updated successfully", "neon-channel-product-customizer-free")]);
                        } else {
                            return rest_ensure_response(["success" => false, "message" => __("Update output file options in generals settings failed", "neon-channel-product-customizer-free")]);
                        }
                    } else {
                        return rest_ensure_response(["success" => "same", "message" => __("No change observed output file options in generals settings", "neon-channel-product-customizer-free")]);
                    }
                }
            } else {
                return rest_ensure_response(["success" => false, "message" => __("Custom ID invalid", "neon-channel-product-customizer-free")]);
            }
        } else {
            return rest_ensure_response(["success" => false, "message" => __("Custom ID invalid", "neon-channel-product-customizer-free")]);
        }
    }
    /**
     * Checks if a given request has access to read the items.
     *
     * @param  \WP_REST_Request $request Full details about the request.
     *
     * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
     */
    public function get_config_permissions_check($request)
    {
        if (!is_user_logged_in()) {
            return new WP_Error(
                'rest_forbidden',
                esc_html__("You must be logged in to access this resource.", "neon-channel-product-customizer-free"),
                array('status' => rest_authorization_required_code())
            );
        }

        $method = $request->get_method();

        if ($method === 'GET') {
            if (!current_user_can('manage_product_terms')) {
                return new WP_Error(
                    'rest_forbidden',
                    esc_html__("You do not have permission to read.", "neon-channel-product-customizer-free"),
                    array('status' => 403)
                );
            }
        } elseif ($method === 'POST') {
            if (!current_user_can('manage_product_terms')) {
                return new WP_Error(
                    'rest_forbidden',
                    esc_html__('You do not have permission to create.', "neon-channel-product-customizer-free"),
                    array('status' => 403)
                );
            }
        } elseif ($method === 'PUT' || $method === 'PATCH') {
            if (!current_user_can('manage_product_terms')) {
                return new WP_Error(
                    'rest_forbidden',
                    esc_html__("You do not have permission to edit.", "neon-channel-product-customizer-free"),
                    array('status' => 403)
                );
            }
        } elseif ($method === 'DELETE') {
            if (!current_user_can('manage_product_terms')) {
                return new WP_Error(
                    'rest_forbidden',
                    esc_html__("You don't have permission to delete.", "neon-channel-product-customizer-free"),
                    array('status' => 403)
                );
            }
        }

        return true;
    }
}