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

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

/**
 * class for api routes reaching language images settings
 */
class NCPC_Api_Language_Images_Settings extends WP_REST_Controller
{

    /**
     * [__construct description]
     */
    public function __construct()
    {
        $this->namespace = 'ncpc/v2';
        $this->rest_base = 'configs/(?P<config_id>\d+)/settings/language-images';
    }
    /**
     * 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_language_images_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 . "/main",
            array(
                array(
                    'methods' => \WP_REST_Server::EDITABLE,
                    'callback' => array($this, 'update_main_options_language_images_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 . "/custom-design",
            array(
                array(
                    'methods' => \WP_REST_Server::EDITABLE,
                    'callback' => array($this, 'update_custom_design_options_language_images_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_options_language_images_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_language_images_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 . "/icons",
            array(
                array(
                    'methods' => \WP_REST_Server::EDITABLE,
                    'callback' => array($this, 'update_icons_language_images_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 . "/icons/upload",
            array(
                array(
                    'methods' => \WP_REST_Server::CREATABLE,
                    'callback' => array($this, 'upload_icon_file_convert'),
                    '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 . "/icons/delete",
            array(
                array(
                    'methods' => \WP_REST_Server::EDITABLE,
                    'callback' => array($this, 'delete_icon_file_convert'),
                    'permission_callback' => array($this, 'get_config_permissions_check'),
                    'args' => array(
                        'config_id' => array(
                            'type' => 'integer',
                            'required' => true,
                        )
                    ),
                )
            )
        );
    }

    /**
     * Get all language images 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_language_images_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"]["languageImages"])) {
                        return rest_ensure_response(["settings" => $meta_value["data"]["settings"]["languageImages"], "pricings" => $meta_value["data"]["requiredOptions"]["priceOptions"]]);
                    }
                    return rest_ensure_response(["success" => false, "message" => __("No language images 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 main options of language images 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_main_options_language_images_settings($request)
    {
        $id = $request->get_param('config_id');
        $main_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 main options in settings failed", "neon-channel-product-customizer-free")]);
                } else {
                    if ($meta_value["data"]["settings"]["languageImages"]['main'] !== $main_options) {

                        $meta_value["data"]["settings"]["languageImages"]['main'] = $main_options;
                        $response = update_post_meta($id, 'ncpc-configs-meta', $meta_value);

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

                        if ($response) {
                            return rest_ensure_response(["success" => true, "message" => __("Custom design options in language images settings updated successfully", "neon-channel-product-customizer-free")]);
                        } else {
                            return rest_ensure_response(["success" => false, "message" => __("Update custom design options in language images settings failed", "neon-channel-product-customizer-free")]);
                        }

                    } else {
                        return rest_ensure_response(["success" => "same", "message" => __("No change observed custom design options in language images 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 of language images 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_options_language_images_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 language images settings failed", "neon-channel-product-customizer-free")]);
                } else {
                    if ($meta_value["data"]["settings"]["languageImages"]['visualizer'] !== $visualizer_options) {
                        $meta_value["data"]["settings"]["languageImages"]['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 language images settings updated successfully", "neon-channel-product-customizer-free")]);
                        } else {
                            return rest_ensure_response(["success" => false, "message" => __("Update visualizer options in language images settings failed", "neon-channel-product-customizer-free")]);
                        }
                    } else {
                        return rest_ensure_response(["success" => "same", "message" => __("No change observed visualizer options in language images 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 images of language images 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_language_images_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 language images settings failed", "neon-channel-product-customizer-free")]);
                } else {
                    if ($meta_value["data"]["settings"]["languageImages"]['images'] !== $images) {
                        $meta_value["data"]["settings"]["languageImages"]['images'] = $images;
                        $response = update_post_meta($id, 'ncpc-configs-meta', $meta_value);

                        if ($response) {
                            return rest_ensure_response(["success" => true, "message" => __("Images in language images settings updated successfully", "neon-channel-product-customizer-free")]);
                        } else {
                            return rest_ensure_response(["success" => false, "message" => __("Update images in language images settings failed", "neon-channel-product-customizer-free")]);
                        }
                    } else {
                        return rest_ensure_response(["success" => "same", "message" => __("No change observed images in language images 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")]);
        }
    }
    /**
     * Upload icon convert file
     * @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 upload_icon_file_convert($request)
    {
        $data = json_decode($request->get_body(), true);
        $success = ncpc_pro_save_convert_icon($data["svgData"]);
        if ($success) {
            return rest_ensure_response(["success" => true, "url" => $success, "message" => __("Icon uploaded successfully", "neon-channel-product-customizer-free")]);
        } else {
            return rest_ensure_response(["success" => false, "message" => __("Icon upload failed", "neon-channel-product-customizer-free")]);
        }

    }
    /**
     * Delete icon convert file
     * @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 delete_icon_file_convert($request)
    {
        $data = json_decode($request->get_body(), true);
        $success = ncpc_pro_delete_convert_icon($data["url"]);
        if ($success) {
            return rest_ensure_response(["success" => true, "message" => __("Icon deleted successfully", "neon-channel-product-customizer-free")]);
        } else {
            return rest_ensure_response(["success" => false, "message" => __("Icon delete failed", "neon-channel-product-customizer-free")]);
        }

    }
    /**
     * Update icons of language images 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_icons_language_images_settings($request)
    {
        $id = $request->get_param('config_id');
        $icons = 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 icons in language images settings failed", "neon-channel-product-customizer-free")]);
                } else {
                    if ($meta_value["data"]["settings"]["languageImages"]['icons'] !== $icons) {
                        $meta_value["data"]["settings"]["languageImages"]['icons'] = $icons;
                        $response = update_post_meta($id, 'ncpc-configs-meta', $meta_value);

                        if ($response) {
                            return rest_ensure_response(["success" => true, "message" => __("Icons in language images settings updated successfully", "neon-channel-product-customizer-free")]);
                        } else {
                            return rest_ensure_response(["success" => false, "message" => __("Update icons in language images settings failed", "neon-channel-product-customizer-free")]);
                        }
                    } else {
                        return rest_ensure_response(["success" => "same", "message" => __("No change observed icons in language images 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")]);
        }
    }
    /**
     * 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;
    }

}