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

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

/**
 * class for api routes reaching backboard colors
 */
class NCPC_Api_Backboards_Colors extends WP_REST_Controller
{
    /**
     * [__construct description]
     */
    public function __construct()
    {
        $this->namespace = 'ncpc/v2';
        $this->rest_base = 'configs/(?P<config_id>\d+)/backboard-colors';
    }
    /**
     * 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_all_backboard_colors'),
                    'permission_callback' => array($this, 'get_config_permissions_check'),
                    'args' => array(
                        'config_id' => array(
                            'type' => 'integer',
                            'required' => true,
                        )
                    ),
                ),
                array(
                    'methods' => \WP_REST_Server::CREATABLE,
                    'callback' => array($this, 'create_backboards_setting'),
                    '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 . "/new",
            array(
                array(
                    'methods' => \WP_REST_Server::CREATABLE,
                    'callback' => array($this, 'add_backboard_color_to_backboard_colors_setting'),
                    '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 . "/(?P<backboard_color_id>\d+)",
            array(
                array(
                    'methods' => \WP_REST_Server::READABLE,
                    'callback' => array($this, 'get_backboard_color_info'),
                    'permission_callback' => array($this, 'get_config_permissions_check'),
                    'args' => array(
                        'config_id' => array(
                            'type' => 'integer',
                            'required' => true,
                        ),
                        'backboard_color_id' => array(
                            'type' => 'integer',
                            'required' => true
                        )
                    ),
                ),
                array(
                    'methods' => \WP_REST_Server::EDITABLE,
                    'callback' => array($this, 'update_backboard_color_in_backboard_colors_setting'),
                    'permission_callback' => array($this, 'get_config_permissions_check'),
                    'args' => array(
                        'config_id' => array(
                            'type' => 'integer',
                            'required' => true,
                        ),
                        'backboard_color_id' => array(
                            'type' => 'integer',
                            'required' => true
                        )
                    ),
                ),
                array(
                    'methods' => \WP_REST_Server::DELETABLE,
                    'callback' => array($this, 'delete_backboard_color_in_backboard_colors_setting'),
                    'permission_callback' => array($this, 'get_config_permissions_check'),
                    'args' => array(
                        'config_id' => array(
                            'type' => 'integer',
                            'required' => true,
                        ),
                        'backboard_color_id' => array(
                            'type' => 'integer',
                            'required' => true
                        )
                    ),
                )
            )
        );

    }

    /**
     * Create if a backboard configuration doesn't exit and update if it exists in an NCPC configuration
     * @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 create_backboards_setting($request)
    {
        $id = $request->get_param('config_id');
        $backboard_setting = 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)) {
                    $meta_value = array();
                }
                $meta_value["data"]["additionalOptions"]["backboardColorsOptions"]['label'] = $backboard_setting["label"];
                $meta_value["data"]["additionalOptions"]["backboardColorsOptions"]['description'] = $backboard_setting["description"];

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

                if ($response) {
                    return rest_ensure_response(["success" => true, "message" => __("Backboard Color settings updated successfully")]);
                } else {
                    return rest_ensure_response(["message" => "backboard colors operation fail"]);
                }

            } else {
                return rest_ensure_response(["message" => "Custom ID invalid"]);

            }
        } else {
            return rest_ensure_response(["message" => "Custom ID invalid"]);
        }
    }
    /**
     * Get all backboard colors of ncpc configuration ID
     * @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_all_backboard_colors($request)
    {
        $id = $request->get_param('config_id');
        if ($id != 0) {
            $meta_value = get_post_meta($id, 'ncpc-configs-meta', true);

            if (!empty($meta_value)) {

                if (isset($meta_value["data"]["additionalOptions"]["backboardColorsOptions"])) {
                    $backboard_colors_options = $meta_value["data"]["additionalOptions"]["backboardColorsOptions"];
                    return rest_ensure_response(["backboardColorsSettings" => $backboard_colors_options, "backboards" => $meta_value["data"]["additionalOptions"]["backboardOptions"]["backboards"]]);
                }
                return rest_ensure_response(["message" => "No data found"]);
            } else {
                return rest_ensure_response(["message" => "No data found"]);
            }
        } else {
            return rest_ensure_response(["message" => "Custom ID invalid"]);
        }

    }

    /**
     * Get a backboard color with ID of ncpc configuration ID
     * @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_backboard_color_info($request)
    {
        $id = $request->get_param('config_id');
        $backboard_color_id = $request->get_param('backboard_color_id');
        if ($id != 0) {
            $meta_value = get_post_meta($id, 'ncpc-configs-meta', true);

            if (!empty($meta_value)) {

                if (isset($meta_value["data"]["additionalOptions"]["backboardColorsOptions"])) {
                    $backboard_colors = $meta_value["data"]["additionalOptions"]["backboardColorsOptions"]["backboardColors"];
                    if (isset($backboard_colors[$backboard_color_id])) {
                        return rest_ensure_response($backboard_colors[$backboard_color_id]);
                    }
                    return rest_ensure_response(array("message" => __("No backboard found", "neon-channel-product-customizer-free")));
                } else {
                    return rest_ensure_response(array("message" => __("No backboard found", "neon-channel-product-customizer-free")));
                }

            } else {
                return rest_ensure_response(["message" => __("No data found", "neon-channel-product-customizer-free")]);
            }
        } else {
            return rest_ensure_response(["message" => __("Custom ID invalid", "neon-channel-product-customizer-free")]);
        }

    }

    /**
     * Add backboard in backboard configuration
     * @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 add_backboard_color_to_backboard_colors_setting($request)
    {

        $id = $request->get_param('config_id');
        $backboard_color = 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)) {
                    $meta_value["data"]["additionalOptions"]["backboardColorsOptions"][0] = $backboard_color;
                } else {
                    if (isset($meta_value["data"]["additionalOptions"]["backboardColorsOptions"]["backboardColors"])) {
                        $backboard_colors = $meta_value["data"]["additionalOptions"]["backboardColorsOptions"]["backboardColors"];
                        array_push($backboard_colors, $backboard_color);
                        $meta_value["data"]["additionalOptions"]["backboardColorsOptions"]["backboardColors"] = $backboard_colors;
                    } else {
                        $meta_value["data"]["additionalOptions"]["backboardColorsOptions"]["backboardColors"][0] = $backboard_color;
                    }
                }

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

                if ($response) {
                    return rest_ensure_response(["success" => true, "message" => __("Backboard color added successfully", "neon-channel-product-customizer-free")]);
                } else {
                    return rest_ensure_response(["message" => __("Add backboard color failed", "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 a backboard in the backboard configuration
     * @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_backboard_color_in_backboard_colors_setting($request)
    {
        $id = $request->get_param('config_id');
        $backboard_color_id = $request->get_param('backboard_color_id');

        $backboard_color = 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)) {

                    if (isset($meta_value["data"]["additionalOptions"]["backboardColorsOptions"]["backboardColors"][$backboard_color_id])) {
                        if ($meta_value["data"]["additionalOptions"]["backboardColorsOptions"]["backboardColors"][$backboard_color_id] != $backboard_color) {
                            $meta_value["data"]["additionalOptions"]["backboardColorsOptions"]["backboardColors"][$backboard_color_id] = $backboard_color;
                            $response = update_post_meta($id, 'ncpc-configs-meta', $meta_value);
                            if ($response) {
                                return rest_ensure_response(["success" => true, "message" => __("Backboard Color updated successfully", "neon-channel-product-customizer-free")]);
                            } else {
                                return rest_ensure_response(["message" => __("update backboard color failed", "neon-channel-product-customizer-free")]);
                            }
                        } else {
                            return rest_ensure_response(["success" => "same", "message" => __("No change observed in backboard color", "neon-channel-product-customizer-free")]);
                        }
                    } else {
                        return rest_ensure_response(["message" => __("No backboard color setting found", "neon-channel-product-customizer-free")]);
                    }

                } else {
                    return rest_ensure_response(["message" => __("No backboard color setting 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")]);
        }
    }

    /**
     * Delete a backboard in the backboard configuration
     * @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_backboard_color_in_backboard_colors_setting($request)
    {
        $id = $request->get_param('config_id');
        $backboard_color_id = $request->get_param('backboard_color_id');
        if ($id != 0) {
            $post = get_post($id);
            if ($post) {
                $meta_value = get_post_meta($id, 'ncpc-configs-meta', true);
                if (!empty($meta_value["data"]["additionalOptions"]["backboardColorsOptions"])) {

                    if (isset($meta_value["data"]["additionalOptions"]["backboardColorsOptions"]["backboardColors"][$backboard_color_id])) {
                        array_splice($meta_value["data"]["additionalOptions"]["backboardColorsOptions"]["backboardColors"], $backboard_color_id, 1);
                    }

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

                    if ($response) {
                        return rest_ensure_response(["success" => true, "message" => __("Backboard Color deleted successfully", "neon-channel-product-customizer-free")]);
                    } else {
                        return rest_ensure_response(["message" => __("delete backboard color failed", "neon-channel-product-customizer-free")]);
                    }
                } else {
                    return rest_ensure_response(["message" => __("No backboard setting 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")]);
        }
    }

    /**
     * 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;
    }
}