<?php
namespace NCPC\Api\Globals_Settings;

use DateTime;
use DateTimeZone;
use WP_Error;
use WP_Post;
use WP_Query;
use WP_REST_Controller;

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

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

    /**
     * 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_data'),
                    'permission_callback' => array($this, 'get_config_permissions_check'),
                )
            )
        );
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . "/config-page",
            array(
                array(
                    'methods' => \WP_REST_Server::CREATABLE,
                    'callback' => array($this, 'save_config_page'),
                    'permission_callback' => array($this, 'get_config_permissions_check'),
                )
            )
        );
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . "/pages",
            array(
                array(
                    'methods' => \WP_REST_Server::CREATABLE,
                    'callback' => array($this, 'create_new_page'),
                    'permission_callback' => array($this, 'get_config_permissions_check'),
                )
            )
        );
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . "/others",
            array(
                array(
                    'methods' => \WP_REST_Server::CREATABLE,
                    'callback' => array($this, 'save_other_data'),
                    'permission_callback' => array($this, 'get_config_permissions_check'),
                )
            )
        );
    }

    /**
     * Get global Settings Data
     * @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_data($request)
    {
        $product = get_option("ncpc_product_free", false);
        if ($product == false) {
            $product = get_option("ncpc_free_license", false);
            if ($product !== false) {
                update_option("ncpc_product_free", $product);
                delete_option("ncpc_free_license");
            }
        }
        $config_page = get_option("ncpc_config_page");
        $othersData = get_option("ncpc_global_settings_others_data", []);
        if (count($othersData) == 0) {
            $othersData = [
                "configuratorHeaderTag" => "h1"
            ];
        }
        $args = array(
            'post_type' => 'page', // Type de contenu "page"
            'post_status' => 'publish', // Statut "publié"
            'posts_per_page' => -1, // Tous les articles (-1 pour afficher tous les articles)
        );

        $existing_pages = get_posts($args);

        $pages[0] = esc_html_x("None", "neon-channel-product-customizer-free");

        foreach ($existing_pages as $page) {
            $pages[$page->ID] = $page->post_title;
        }

        if ($product == false || empty($product)) {
            return rest_ensure_response(['product' => "", "pages" => $pages, "configPageID" => $config_page, "others" => $othersData]);
        } else {
            return rest_ensure_response(['product' => $product, "pages" => $pages, "configPageID" => $config_page, "others" => $othersData]);
        }
    }
    /**
     * Add config page
     * @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 save_config_page($request)
    {
        $params = json_decode($request->get_body(), true);
        if (isset($params['configPage'])) {

            $config_page = get_option("ncpc_config_page");
            $othersData = get_option("ncpc_global_settings_others_data", []);
            if ($config_page == $params["configPage"] && $othersData == $params["others"]) {

                return rest_ensure_response(["success" => "same", "message" => __("No change observed", "neon-channel-product-customizer-pro")]);

            } elseif ($othersData == $params["others"]) {

                update_option("ncpc_config_page", $params['configPage']);
                return rest_ensure_response(["success" => true, "message" => __("Config page updated successfully", "neon-channel-product-customizer-pro")]);

            } elseif ($config_page == $params["configPage"]) {

                update_option("ncpc_global_settings_others_data", $params['others']);
                return rest_ensure_response(["success" => true, "message" => __("Data updated successfully", "neon-channel-product-customizer-pro")]);

            } else {

                update_option("ncpc_config_page", $params['configPage']);
                update_option("ncpc_global_settings_others_data", $params['others']);
                return rest_ensure_response(["success" => true, "message" => __("Data updated successfully", "neon-channel-product-customizer-pro")]);

            }
        }
        return rest_ensure_response(["message" => __("Config page not found", "neon-channel-product-customizer-pro")]);
    }
    /**
     * Save others global Settings data
     * @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 save_other_data($request)
    {
        $params = json_decode($request->get_body());
        $option = update_option("ncpc_global_settings_others_data", $params->configPage);
        if ($option) {
            return rest_ensure_response(["success" => __("Save successfully", "neon-channel-product-customizer-free")]);
        } else {
            return rest_ensure_response(["message" => __("Saving failed", "neon-channel-product-customizer-free")]);
        }
    }

    /**
     * Get config page
     * @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_page($request)
    {

        $option = get_option("ncpc_config_page");

        if ($option == false || empty($option)) {
            return rest_ensure_response(["message" => __("Config page not found", "neon-channel-product-customizer-free")]);
        } else {
            return rest_ensure_response($option);
        }
    }

    /**
     * Show all published pages
     *  @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.
     */
    function get_available_pages()
    {
        $args = array(
            'post_type' => 'page', // Type de contenu "page"
            'post_status' => 'publish', // Statut "publié"
            'posts_per_page' => -1, // Tous les articles (-1 pour afficher tous les articles)
        );

        $existing_pages = get_posts($args);

        $pages[0] = esc_html_x("None", "neon-channel-product-customizer-free");

        foreach ($existing_pages as $page) {
            $pages[$page->ID] = $page->post_title;
        }

        return rest_ensure_response($pages);
    }

    /**
     * Add new page 
     * 
     * @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.
     */
    function create_new_page($request)
    {
        $params = json_decode($request->get_body());
        if (isset($params->title)) {

            $new_page = array(
                'post_title' => $params->title,
                'post_status' => 'publish',
                'post_type' => 'page'
            );

            $page_id = wp_insert_post($new_page);

            if ($page_id) {
                return rest_ensure_response(["pageId" => $page_id, "message" => __("Page was created successfully", "neon-channel-product-customizer-free")]);
            } else {
                return rest_ensure_response(["message" => __("Page was not created", "neon-channel-product-customizer-free")]);
            }

        } else {
            return rest_ensure_response(["message" => __("Page was not created", "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;
    }

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