<?php

namespace HulkPlugins\Woo\ProductDescriptionInLoop\Admin\Controllers;

use HulkPlugins\Woo\ProductDescriptionInLoop\Admin\Services\SettingsService;
use HulkPlugins\Woo\ProductDescriptionInLoop\Core\BaseController;
use HulkPlugins\Woo\ProductDescriptionInLoop\Core\SingletonTrait;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;
use function HulkPlugins\Woo\ProductDescriptionInLoop\hulk_woo_pdil_fs;
use const HulkPlugins\Woo\ProductDescriptionInLoop\PLUGIN_DIR_PATH;
use const HulkPlugins\Woo\ProductDescriptionInLoop\PLUGIN_DIR_URL;
defined( 'ABSPATH' ) || exit;
class SettingsController extends BaseController {
    use SingletonTrait;
    public function init_hooks() : void {
        add_action( 'admin_menu', [$this, 'add_submenu_page'] );
        add_action( 'rest_api_init', [$this, 'register_routes'] );
    }

    /**
     * Add submenu under WooCommerce
     * @return void
     */
    public function add_submenu_page() : void {
        add_submenu_page(
            'woocommerce',
            esc_attr__( 'Product Description', 'product-description-in-loop-for-woocommerce' ),
            esc_attr__( 'Product Description', 'product-description-in-loop-for-woocommerce' ),
            'manage_options',
            'hulk_woo_pdil_settings',
            [$this, 'render_settings_page']
        );
    }

    /**
     * Render settings page
     * @return void
     */
    public function render_settings_page() : void {
        $settings_asset = (require PLUGIN_DIR_PATH . 'build/admin/settings/index.asset.php');
        $service = SettingsService::getInstance();
        wp_enqueue_style(
            'hulk_woo_pdil_admin_settings',
            PLUGIN_DIR_URL . 'build/admin/settings/index.css',
            ['wp-components'],
            $settings_asset['version']
        );
        wp_enqueue_script(
            'hulk_woo_pdil_admin_settings',
            PLUGIN_DIR_URL . 'build/admin/settings/index.js',
            $settings_asset['dependencies'],
            $settings_asset['version'],
            true
        );
        $currentTab = 'general';
        require PLUGIN_DIR_PATH . 'templates/admin/settings-page.php';
        $licensing = [
            'can_use_premium_code' => hulk_woo_pdil_fs()->can_use_premium_code(),
            'is_premium'           => hulk_woo_pdil_fs()->is_premium(),
            'checkout_url'         => hulk_woo_pdil_fs()->checkout_url(),
            'is_not_paying'        => hulk_woo_pdil_fs()->is_not_paying(),
            'get_upgrade_url'      => hulk_woo_pdil_fs()->get_upgrade_url(),
            'notice'               => hulk_woo_pdil_fs(),
        ];
        $wooLinks = $service->getWooLinks();
        wp_localize_script( 'hulk_woo_pdil_admin_settings', 'hulk_woo_pdil_settings', [
            'PLUGIN_DIR_URL'                => PLUGIN_DIR_URL,
            'current_tab'                   => $currentTab,
            'description_positions_options' => $service->getDescriptionPositionsOptions(),
            'description_content_options'   => $service->getDescriptionContentOptions(),
            'text_align_options'            => $service->getTextAlignOptions(),
            'saved_settings'                => $service->getSavedSettings(),
            'rest_url'                      => rest_url( 'hulk_woo_pdil' ),
            'nonce'                         => wp_create_nonce( 'wp_rest' ),
            'licensing'                     => $licensing,
            'woo_links'                     => $wooLinks,
        ] );
    }

    /**
     * Register settings save rest route
     * @return void
     */
    public function register_routes() : void {
        register_rest_route( 'hulk_woo_pdil/v1', '/settings', [
            'methods'             => WP_REST_Server::EDITABLE,
            'callback'            => [$this, 'save_settings'],
            'permission_callback' => function () {
                return current_user_can( 'manage_options' );
            },
        ] );
    }

    /**
     * Save settings to the database
     * @param WP_REST_Request $request
     *
     * @return WP_REST_Response
     */
    public function save_settings( WP_REST_Request $request ) : WP_REST_Response {
        $params = $request->get_params();
        // General settings
        $enabled_pages = array_map( static fn( $page ) => sanitize_text_field( $page ), $params['enabled_pages'] );
        // Style settings
        $enable_style = wp_validate_boolean( $params['enable_style'] );
        $text_align = sanitize_text_field( $params['text_align'] );
        // Save the settings in the wp_options table
        update_option( 'hulk_woo_pdil_enabled_pages', $enabled_pages );
        update_option( 'hulk_woo_pdil_enable_style', $enable_style );
        update_option( 'hulk_woo_pdil_text_align', $text_align );
        return new WP_REST_Response([
            'success' => true,
            'message' => esc_attr__( 'Settings saved.', 'product-description-in-loop-for-woocommerce' ),
        ], 200);
    }

}
