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

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

/**
 * class for api routes reaching custom design settings
 */
class NCPC_Api_Custom_Design_Settings extends WP_REST_Controller
{

    /**
     * [__construct description]
     */
    public function __construct()
    {
        $this->namespace = 'ncpc/v2';
        $this->rest_base = 'configs/(?P<config_id>\d+)/settings/custom-designs';
    }
    /**
     * 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_customDesign_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 . "/link",
            array(
                array(
                    'methods' => \WP_REST_Server::EDITABLE,
                    'callback' => array($this, 'update_link_customDesign_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 . "/screen",
            array(
                array(
                    'methods' => \WP_REST_Server::EDITABLE,
                    'callback' => array($this, 'update_screen_customDesign_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 . "/visualizer",
            array(
                array(
                    'methods' => \WP_REST_Server::EDITABLE,
                    'callback' => array($this, 'update_visualizer_customDesign_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 . "/screen-review",
            array(
                array(
                    'methods' => \WP_REST_Server::EDITABLE,
                    'callback' => array($this, 'update_screenReview_customDesign_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 . "/notifications",
            array(
                array(
                    'methods' => \WP_REST_Server::EDITABLE,
                    'callback' => array($this, 'update_notifications_customDesign_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 . "/images",
            array(
                array(
                    'methods' => \WP_REST_Server::EDITABLE,
                    'callback' => array($this, 'update_images_customDesign_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_customDesign_settings'),
                    'permission_callback' => array($this, 'get_config_permissions_check'),
                    'args' => array(
                        'config_id' => array(
                            'type' => 'integer',
                            'required' => true,
                        )
                    ),
                )
            )
        );
    }

    /**
     * Get all custom design 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_customDesign_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(["message" => __("No Settings found", "neon-channel-product-customizer-free")]);
                } else {
                    if (isset($meta_value["data"]["settings"]["customDesign"])) {
                        return rest_ensure_response($meta_value["data"]["settings"]["customDesign"]);
                    }
                    return rest_ensure_response(["message" => __("No Custom Design Settings found", "neon-channel-product-customizer-free")]);
                }
            } else {
                return rest_ensure_response(["message" => __("Custom ID invalid", "neon-channel-product-customizer-free")]);
            }
        } else {
            return rest_ensure_response(["message" => __("Custom ID invalid", "neon-channel-product-customizer-free")]);
        }
    }
    /**
     * Update link options of customDesign 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_link_customDesign_settings($request)
    {
        $id = $request->get_param('config_id');
        $link_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 link in customDesign settings failed", "neon-channel-product-customizer-free")]);
                } else {
                    if ($meta_value["data"]["settings"]["customDesign"]['link'] !== $link_options) {
                        $meta_value["data"]["settings"]["customDesign"]['link'] = $link_options;
                        $response = update_post_meta($id, 'ncpc-configs-meta', $meta_value);
                        if ($response) {
                            return rest_ensure_response(["success" => true, "message" => __("Link in customDesign settings update successfully", "neon-channel-product-customizer-free")]);
                        } else {
                            return rest_ensure_response(["success" => false, "message" => __("Update link in customDesign settings failed", "neon-channel-product-customizer-free")]);
                        }
                    } else {
                        return rest_ensure_response(["success" => "same", "message" => __("No change observed on link in customDesign 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 screen options of customDesign 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_screen_customDesign_settings($request)
    {
        $id = $request->get_param('config_id');
        $screen_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 screen in customDesign settings failed", "neon-channel-product-customizer-free")]);
                } else {
                    if ($meta_value["data"]["settings"]["customDesign"]['screen'] !== $screen_options) {
                        $meta_value["data"]["settings"]["customDesign"]['screen'] = $screen_options;
                        $response = update_post_meta($id, 'ncpc-configs-meta', $meta_value);

                        if ($response) {
                            return rest_ensure_response(["success" => true, "message" => __("Screen in customDesign settings updated successfully", "neon-channel-product-customizer-free")]);
                        } else {
                            return rest_ensure_response(["success" => false, "message" => __("Update screen in customDesign settings failed", "neon-channel-product-customizer-free")]);
                        }
                    } else {
                        return rest_ensure_response(["success" => "same", "message" => __("No change observed on Screen in customDesign 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 visualizer options of customDesign 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_visualizer_customDesign_settings($request)
    {
        $id = $request->get_param('config_id');
        $visualizer_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 visualizer options in customDesign settings failed", "neon-channel-product-customizer-free")]);
                } else {
                    if ($meta_value["data"]["settings"]["customDesign"]['visualizer'] !== $visualizer_options) {
                        $meta_value["data"]["settings"]["customDesign"]['visualizer'] = $visualizer_options;
                        $response = update_post_meta($id, 'ncpc-configs-meta', $meta_value);

                        if ($response) {
                            return rest_ensure_response(["success" => true, "message" => __("Visualizer options in customDesign settings updated successfully")]);
                        } else {
                            return rest_ensure_response(["success" => false, "message" => __("Updated visualizer options in customDesign settings failed", "neon-channel-product-customizer-free")]);
                        }
                    } else {
                        return rest_ensure_response(["success" => "same", "message" => __("No change observed on visualizer options in customDesign 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 screenReview options of customDesign 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_screenReview_customDesign_settings($request)
    {
        $id = $request->get_param('config_id');
        $screenReview = 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 screenReview in customDesign settings failed", "neon-channel-product-customizer-free")]);
                } else {
                    if ($meta_value["data"]["settings"]["customDesign"]['screenReview'] !== $screenReview) {
                        $meta_value["data"]["settings"]["customDesign"]['screenReview'] = $screenReview;

                        $response = update_post_meta($id, 'ncpc-configs-meta', $meta_value);

                        if ($response) {
                            return rest_ensure_response(["success" => true, "message" => __("screenReview in customDesign settings added successfully", "neon-channel-product-customizer-free")]);
                        } else {
                            return rest_ensure_response(["success" => false, "message" => __("Update screenReview in customDesign settings failed", "neon-channel-product-customizer-free")]);
                        }
                    } else {
                        return rest_ensure_response(["success" => "same", "message" => __("No change observe on screenReview in customDesign 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 notifications options of customDesign 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_notifications_customDesign_settings($request)
    {
        $id = $request->get_param('config_id');
        $notifications = 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 notifications in customDesign settings failed", "neon-channel-product-customizer-free")]);
                } else {
                    if ($meta_value["data"]["settings"]["customDesign"]['notifications'] !== $notifications) {
                        $meta_value["data"]["settings"]["customDesign"]['notifications'] = $notifications;
                        $response = update_post_meta($id, 'ncpc-configs-meta', $meta_value);

                        if ($response) {
                            return rest_ensure_response(["success" => true, "message" => __("Notifications in customDesign settings updated successfully", "neon-channel-product-customizer-free")]);
                        } else {
                            return rest_ensure_response(["success" => false, "message" => __("Update notifications in customDesign settings failed", "neon-channel-product-customizer-free")]);
                        }
                    } else {
                        return rest_ensure_response(["success" => "same", "message" => __("No change observed notifications in customDesign 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 images options of customDesign 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_images_customDesign_settings($request)
    {
        $id = $request->get_param('config_id');
        $images = 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 images in customDesign settings failed", "neon-channel-product-customizer-free")]);
                } else {
                    if ($meta_value["data"]["settings"]["customDesign"]['images'] !== $images) {
                        $meta_value["data"]["settings"]["customDesign"]['images'] = $images;
                        $response = update_post_meta($id, 'ncpc-configs-meta', $meta_value);

                        if ($response) {
                            return rest_ensure_response(["success" => true, "message" => __("images in customDesign settings updated successfully", "neon-channel-product-customizer-free")]);
                        } else {
                            return rest_ensure_response(["success" => false, "message" => __("Update images in customDesign settings failed", "neon-channel-product-customizer-free")]);
                        }
                    } else {
                        return rest_ensure_response(["success" => "same", "message" => __("No change observed images in customDesign 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 images options of customDesign 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_customDesign_settings($request)
    {
        $id = $request->get_param('config_id');
        $product = 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" => __("Updated product in customDesign settings failed", "neon-channel-product-customizer-free")]);
                } else {
                    if ($meta_value["data"]["settings"]["customDesign"]['product'] !== $product) {
                        $meta_value["data"]["settings"]["customDesign"]['product'] = $product;
                        $response = update_post_meta($id, 'ncpc-configs-meta', $meta_value);

                        if ($response) {
                            return rest_ensure_response(["success" => false, "message" => __("product in customDesign settings added successfully", "neon-channel-product-customizer-free")]);
                        } else {
                            return rest_ensure_response(["success" => false, "message" => __("Update product in customDesign settings failed", "neon-channel-product-customizer-free")]);
                        }
                    } else {
                        return rest_ensure_response(["success" => "same", "message" => __("No change observed on product in customDesign 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;
    }
}