<?php
namespace NCPC\Api\Admin;

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

/**
 * REST_API Handler
 */
class NCPC_Api_Configs extends WP_REST_Controller
{

    /**
     * [__construct description]
     */
    public function __construct()
    {
        $this->namespace = 'ncpc/v2';
        $this->rest_base = 'configs';
    }

    /**
     * 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_configs'),
                    'permission_callback' => array($this, 'get_config_permissions_check')
                ),
                array(
                    'methods' => \WP_REST_Server::CREATABLE,
                    'callback' => array($this, 'create_config_post'),
                    'permission_callback' => array($this, 'get_config_permissions_check'),
                ),
            )
        );
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . "/(?P<config_id>\d+)",
            array(
                array(
                    'methods' => \WP_REST_Server::READABLE,
                    'callback' => array($this, 'get_config_post'),
                    'permission_callback' => array($this, 'get_config_permissions_check'),
                    'args' => array(
                        'config_id' => array(
                            'type' => 'integer',
                            'required' => true,
                        )
                    ),
                ),
                array(
                    'methods' => \WP_REST_Server::EDITABLE,
                    'callback' => array($this, 'update_config_post'),
                    'permission_callback' => array($this, 'get_config_permissions_check'),
                    'args' => array(
                        'config_id' => array(
                            'type' => 'integer',
                            'required' => true,
                        )
                    ),
                ),
                array(
                    'methods' => \WP_REST_Server::DELETABLE,
                    'callback' => array($this, 'delete_config'),
                    'permission_callback' => array($this, 'get_config_permissions_check'),
                    'args' => array(
                        'config_id' => array(
                            'type' => 'integer',
                            'required' => true,
                        )
                    ),
                )
            )
        );
    }

    /**
     * Create ncpc product 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_config_post($request)
    {
        $params = json_decode($request->get_body(), true);
        $data = [
            'post_title' => $params["title"],
            'post_type' => 'ncpc-configs',
            'post_meta' => [
                "ncpc-configs-meta" => []
            ],
            'post_status' => 'publish'
        ];

        if (isset($params["productType"]) && isset($params["pricingMode"])) {
            $post_id = wp_insert_post($data);
            if ($post_id != 0) {
                if (isset($params["data"]) && !empty($params["data"])) {
                    update_post_meta($post_id, 'ncpc-configs-meta', ["productType" => $params["productType"], "pricingMode" => $params["pricingMode"], "data" => $params["data"]]);
                }
                return rest_ensure_response(["post_id" => $post_id, "message" => __("Successful Added configuration", "neon-channel-product-customizer-free")]);
            } else {
                return rest_ensure_response(["message" => __("Registration failed", "neon-channel-product-customizer-free")]);
            }
        } else {
            return rest_ensure_response(["message" => __("Missing parameters error", "neon-channel-product-customizer-free")]);
        }
    }

    /**
     * Duplicate ncpc product 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 duplicate_config_post($request)
    {
        $config_duplicated_id = $request->get_param('config_id');
        $params = json_decode($request->get_body(), true);

        if ($config_duplicated_id != 0) {
            $meta_value = get_post_meta($config_duplicated_id, 'ncpc-configs-meta', true);
            if (!empty($meta_value) && is_array($meta_value)) {
                $data = [
                    'post_title' => $params["title"],
                    'post_type' => 'ncpc-configs',
                    'post_meta' => [
                        "ncpc-configs-meta" => []
                    ],
                    'post_status' => 'publish'
                ];
                $post_id = wp_insert_post($data);
                if ($post_id != 0) {
                    update_post_meta($post_id, 'ncpc-configs-meta', $meta_value);
                    return rest_ensure_response(["post_id" => $post_id, "message" => __("Successful duplicated configuration", "neon-channel-product-customizer-free")]);

                } else {
                    return rest_ensure_response(["message" => __("Duplicate failed", "neon-channel-product-customizer-free")]);
                }

            } else {
                return rest_ensure_response(["message" => __("Duplicate failed", "neon-channel-product-customizer-free")]);
            }
        } else {
            return rest_ensure_response(["message" => __("Duplicate failed", "neon-channel-product-customizer-free")]);
        }
        if (count($posts_data) == 0) {

            if (isset($params["productType"]) && isset($params["pricingMode"])) {
                $post_id = wp_insert_post($data);
                if ($post_id != 0) {
                    wp_set_object_terms($post_id, $params["productType"], 'ncpc-proncducts-type', false);
                    wp_set_object_terms($post_id, $params["pricingMode"], 'ncpc-pricings-mode', false);
                    if (isset($params["data"]) && !empty($params["data"])) {
                        update_post_meta($post_id, 'ncpc-configs-meta', $params["data"]);
                    }

                    return rest_ensure_response(["post_id" => $post_id, "message" => __("Configuration added successfuly", "neon-channel-product-customizer-free")]);

                } else {
                    return rest_ensure_response(["message" => __("Registration failed", "neon-channel-product-customizer-free")]);
                }
            } else {
                return rest_ensure_response(["message" => __("Missing parameters error", "neon-channel-product-customizer-free")]);
            }

        } else {
            return rest_ensure_response(["message" => __("You can only create one configuration in this version of the plugin", "neon-channel-product-customizer-free")]);
        }
    }

    /**
     * Get config info for $post 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_config_post($request)
    {
        $id = $request->get_param('config_id');
        if ($id != 0) {
            $meta_value = get_post_meta($id, 'ncpc-configs-meta', true);
            $meta_value["others"] = get_option("ncpc_global_settings_others_data", []);
            $post_data = array(
                'id' => $id,
                'title' => get_the_title($id),
                'productType' => strtolower($meta_value["productType"]),
                'pricingMode' => strtolower($meta_value["pricingMode"]),
                'data' => !empty($meta_value["data"]) ? $meta_value["data"] : [],
            );

            return rest_ensure_response($post_data);

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


    }
    /**
     * Update of ncpc produit 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_config_post($request)
    {
        $params = json_decode($request->get_body(), true);
        $args = array(
            'ID' => $request->get_param('config_id'),
            'post_title' => $params["title"],
        );

        $updatePosts = wp_update_post($args);
        if ($updatePosts instanceof WP_Error) {
            return rest_ensure_response(array('success' => false, "message" => __("An error has occurred", "neon-channel-product-customizer-free")));
        } else {
            return rest_ensure_response(array('success' => true, "message" => __("Configuration edited successfully", "neon-channel-product-customizer-free")));
        }

    }

    /**
     * Remove ncpc configuration from ID in request
     * @param \WP_REST_Request $request Full details about the request.
     *
     * @return $success message if is ok and fail otherwise. 
     */
    public function delete_config($request)
    {

        $id = $request->get_param('config_id');

        if ($id != 0) {
            $success = wp_delete_post($id, true);
            if ($success != false && $success != null) {
                return rest_ensure_response(array('success' => true, "message" => __("Configuration deleted successfully", "neon-channel-product-customizer-free")));
            } else {
                return rest_ensure_response(array('success' => false, "message" => __("An error has occurred", "neon-channel-product-customizer-free")));
            }
        } else {
            return rest_ensure_response(array('success' => false, "message" => __("An error has occurred", "neon-channel-product-customizer-free")));
        }
    }

    /**
     * Get all ncpc produits configurations with or no per_page,page param in api url
     *
     * @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_configs($request)
    {
        $args = array(
            'post_type' => 'ncpc-configs',
            'post_status' => 'publish',
            'numberposts' => -1
        );

        //displays 10 results per page if per_page is not specified
        $per_page = $request->get_param('per_page');
        if (!empty($per_page)) {
            $args['posts_per_page'] = absint($per_page);
        } else {
            $per_page = 5;
            $args['posts_per_page'] = 5;
        }

        // Make Pagination
        $page = $request->get_param('page');
        if (!empty($page)) {
            $args['paged'] = absint($page);
        }

        // Make search 
        $search_query = $request->get_param('search');
        if (!empty($search_query)) {
            $args['s'] = sanitize_text_field($search_query);
        }

        // Get custom post types using WP_Query
        $query = new WP_Query($args);
        $total_posts = $query->found_posts;
        $total_pages = ceil($total_posts / $per_page);
        // Check the results and return the response
        $posts_data = array(
            "totalConfigsFound" => $total_posts,
            "totalPages" => $total_pages,
            "data" => [],
        );

        // Check the results and return the response
        if ($query->have_posts()) {

            while ($query->have_posts()) {
                $query->the_post();
                $id = get_the_ID();
                $meta_value = get_post_meta($id, 'ncpc-configs-meta', true);

                $post_data = array(
                    'id' => $id,
                    'title' => get_the_title(),
                    'productType' => strtolower($meta_value["productType"]),
                    'pricingMode' => strtolower($meta_value["pricingMode"])
                );

                array_push($posts_data["data"], $post_data);

            }

            return rest_ensure_response($posts_data);

        } else {
            return rest_ensure_response($posts_data);
        }
    }
    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;
    }

    /**
     * Retrieves the query params for the items collection.
     *
     * @return array Collection parameters.
     */
    public function get_collection_params()
    {
        return [];
    }
}
