<?php

namespace SGC\eGiftCard\Http\Controller;

defined('ABSPATH') || exit; // Prevent direct file access.

use SGC\eGiftCard\Http\Request\ValidatorHandler;
use SGC\eGiftCard\Http\Model\GiftCode;

class AdminController extends BaseController
{
    /**
     * Handles the request to get a paginated list of gift codes.
     *
     * @param \WP_REST_Request $request The REST request object.
     *
     * @return \WP_REST_Response The response containing the total items, gift codes, current page, and items per page.
     */
    public function index(\WP_REST_Request $request)
    {
        $page   = intval($request->get_param('page') );
        $limit  = intval($request->get_param('per_page') );
        $offset = ($page - 1) * $limit;

        $giftCode = GiftCode::getInstance();
        $total_items = count($giftCode::all(null, null, 'order_id != 0'));
        $giftCodeData = $giftCode::all($limit, $offset, 'order_id != 0');

        return $this->response([
            'total_items' => $total_items,
            'gift_codes' => $giftCodeData,
            'current_page' => $page,
            'per_page' => $limit
        ]);
    }

    /**
     * Retrieves the general settings for the Smart eGift Card plugin.
     *
     * This method returns the general settings for the plugin, including default values
     * for gift card page ID, redeem gift page ID, gift product ID, gift amounts, WordPress pages,
     * WooCommerce products, and brand logo. If existing settings are found, they are merged with
     * the default values.
     *
     * @return array The general settings for the Smart eGift Card plugin.
     */
    public function general_settings()
    {
        $defaults = [
            'gift_card_page_id'     => '',
            'redeem_gift_page_id'   => '',
            'gift_product_id'       => '',
            'gift_amount'           => '10,20,30,40,50',
            'code_validation'       => '5',
            'wp_pages'              => self::getWPPages(),
            'gift_products'         => self::getWooCommerceProducts(),
            'brand_logo'            => SMART_GIFT_CARD_PLUGIN_URL . 'assets/img/logo.png',
            'design_settings'       => [
                'gift_amount_btn_color' => '#ff0000',
                'gift_amount_btn_hover_color' => '#cc0000',
                'add_to_cart_btn_color' => '#00ff00',
                'add_to_cart_btn_hover_color' => '#00cc00',
                'redeem_btn_color'      => '#0000ff',
                'redeem_btn_hover_color' => '#0000cc',
                'initial_message'       => __('Your kindness, love, and warmth light up my life every day. This gift is a small token of my appreciation for all the joy you bring. May it brighten your day as much as you brighten mine!', 'smart-gift-card'),
                'gift_card_background'  => SMART_GIFT_CARD_PLUGIN_URL . 'assets/img/gift_card_info.png',
            ],
        ];

        $existingSettings = self::getOption('sgc_smart_gift_general_settings', []);

        if ( ! $existingSettings ) {
            $settings = $defaults;
            return $settings;
        }

        $settings = wp_parse_args($existingSettings, $defaults);

        //Filter hook for the general settings
        $settings = apply_filters('sgc_smart_gift_general_settings', $settings);

        return $settings;
    }

    /**
     * Retrieves the advance settings for the Smart eGift Card plugin.
     *
     * This method returns the advance settings for the plugin, including options
     * for allowing gift card usage with other products, custom uploads, and video selection.
     *
     * @return \WP_REST_Response The response containing the advance settings.
     */
    public function get_advance_settings()
    {
        $settings   = $this->general_settings(); 
        
        $sgc_allow_coupons = isset($settings['sgc_allow_coupons']) ? $settings['sgc_allow_coupons'] : 'no';
        $raw = maybe_unserialize(isset($settings['sgc_allowed_occasions']) ? $settings['sgc_allowed_occasions'] : []);
        $sgc_allowed_occasions = [];
        
        if ( is_array($raw) && ! empty($raw) ) {
            $sgc_allowed_occasions = json_decode(stripslashes($raw[0]), true);
        }

        $advance_settings = [
            'sgc_allow_with_others'     => isset($settings['sgc_allow_with_others']) ? $settings['sgc_allow_with_others'] : 'yes',
            'sgc_allow_custom_upload'   => isset($settings['sgc_allow_custom_upload']) ? $settings['sgc_allow_custom_upload'] : 'yes',
            'sgc_allow_video_selection' => isset($settings['sgc_allow_video_selection']) ? $settings['sgc_allow_video_selection'] : 'yes',
            'sgc_allow_coupons'         => $sgc_allow_coupons,
            'sgc_allowed_occasions'     => $sgc_allowed_occasions,
            'occasions'                 => self::get_event_list(),
        ];

        return $this->response([
            'settings' => $advance_settings
        ]);
    }

    /**
     * Update general settings and store them in the options table.
     * 
     * @return mixed The response of the update action, either errors or success message.
     */
    public function update_settings()
    {
        // Validate the input data using the ValidatorHandler class.
        $errors = ValidatorHandler::validateGeneralSettings($this->request);

        // If there are validation errors, return the errors with a 403 status code.
        if (count($errors) > 0) {
            return $this->response($errors, 403);
        }

        $existingSettings = self::getOption('sgc_smart_gift_general_settings', []);

        // Check if a new brand logo has been uploaded.
        //nonce verification is not required here as the request is made using rest api and nonce already verified there
        if ( ! empty($_FILES['brand_logo']['name'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
            // Get the WordPress upload directory
            $upload_dir = wp_upload_dir();
            $upload_path = $upload_dir['basedir'] . '/' . SMART_GIFT_CARD_PLUGIN_ASSET_ID;

            if ( isset($existingSettings['brand_logo'] ) && ! empty( $existingSettings['brand_logo'] ) ) {
                $file = $upload_path . '/' . $existingSettings['brand_logo'];
                wp_delete_file($file);
            }

            // Upload the new file
            $brand_logo = self::handle_file_upload('brand_logo');
            if ( is_wp_error( $brand_logo ) ) {
                return $this->response($brand_logo->get_error_message(), 400);
            }
        } else {
            $brand_logo = isset($existingSettings['brand_logo']) ? $existingSettings['brand_logo'] : '';
        }

        if ( !$brand_logo ) {
            $brand_logo = SMART_GIFT_CARD_PLUGIN_URL . 'assets/img/logo.png';
        }

        // Prepare the data array to store the settings.
        $data = array(
            'gift_card_page_id'   => intval($this->request->get( 'gift_card_page_id' ) ),
            'redeem_gift_page_id' => intval($this->request->get( 'redeem_gift_page_id' ) ),
            'gift_product_id'     => intval($this->request->get( 'gift_product_id' ) ),
            'gift_amount'         => sanitize_text_field( $this->request->get( 'gift_amount' ) ),
            'code_validation'     => intval($this->request->get( 'code_validation' ) ),
            'brand_logo'          => $brand_logo
        );

        // Filter hook for the general settings before updating.
        $data = apply_filters( 'sgc_smart_gift_general_settings_before_update', $data );

        // Update or insert the settings in the wp_options table.
        self::updateOption('sgc_smart_gift_general_settings', $data);

        $data = [
            'message' => 'Settings updated successfully!',
            'settings' => $this->general_settings()
        ];

        // Return a success response after updating.
        return $this->response($data, 200);
    }

    public function update_advance_settings()
    {
        // Validate the input data using the ValidatorHandler class.
        $errors = ValidatorHandler::validateAdvanceSettings($this->request);

        // If there are validation errors, return the errors with a 403 status code.
        if (count($errors) > 0) {
            return $this->response($errors, 403);
        }

        $existingSettings = self::getOption('sgc_smart_gift_general_settings', []);
        $sgc_allowed_occasions = array_map( 'sanitize_text_field', (array) $this->request->get( 'sgc_allowed_occasions' ) );
        // Prepare the data array to store the advance settings.
        $data = array(
            'sgc_allow_with_others'    => rest_sanitize_boolean( $this->request->get( 'sgc_allow_with_others' ) ) ? 'yes' : 'no',
            'sgc_allow_custom_upload'  => rest_sanitize_boolean( $this->request->get( 'sgc_allow_custom_upload' ) ) ? 'yes' : 'no',
            'sgc_allow_video_selection'=> rest_sanitize_boolean( $this->request->get( 'sgc_allow_video_selection' ) ) ? 'yes' : 'no',
            'sgc_allow_coupons'=> rest_sanitize_boolean( $this->request->get( 'sgc_allow_coupons' ) ) ? 'yes' : 'no',
            'sgc_allowed_occasions'    => maybe_serialize( $sgc_allowed_occasions ),
        );

        $existingSettings = array_merge($existingSettings, $data);

        // Update or insert the settings in the wp_options table.
        self::updateOption('sgc_smart_gift_general_settings', $existingSettings);

        return $this->get_advance_settings();
    }

    /**
     * Update design settings and store them in the options table.
     * 
     * @return mixed The response of the update action, either errors or success message.
     */
    public function update_design_settings()
    {
        // Validate the input data using the ValidatorHandler class.
        $errors = ValidatorHandler::validateDesignSettings($this->request);

        // If there are validation errors, return the errors with a 403 status code.
        if (count($errors) > 0) {
            return $this->response($errors, 403);
        }

        // Check if a new gift card background has been uploaded.
        //nonce verification is not required here as the request is made using rest api and nonce already verified there
        if ( ! empty($_FILES['gift_card_background']['name'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
            // Get the WordPress upload directory
            $upload_dir = wp_upload_dir();
            $upload_path = $upload_dir['basedir'] . '/' . SMART_GIFT_CARD_PLUGIN_ASSET_ID;

            if ( isset($existingSettings['gift_card_background'] ) && ! empty( $existingSettings['gift_card_background'] ) ) {
                $file = $upload_path . '/' . $existingSettings['gift_card_background'];
                wp_delete_file($file);
            }

            // Upload the new file
            $gift_card_background = self::handle_file_upload('gift_card_background');
            if ( is_wp_error( $gift_card_background ) ) {
                return $this->response($gift_card_background->get_error_message(), 400);
            }
            $gift_card_background = $upload_dir['baseurl'] . '/' . SMART_GIFT_CARD_PLUGIN_ASSET_ID . '/' . $gift_card_background;
        } else {
            $gift_card_background = isset($existingSettings['gift_card_background']) ? $existingSettings['gift_card_background'] : '';
        }

        if ( !$gift_card_background ) {
            $gift_card_background = SMART_GIFT_CARD_PLUGIN_URL . 'assets/img/gift_card_info.png';
        }

        $existingSettings = self::getOption('sgc_smart_gift_general_settings', []);

        // Prepare the data array to store the design settings.
        $design_settings = array(
            'gift_amount_btn_color' => sanitize_text_field( $this->request->get( 'gift_amount_btn_color' ) ),
            'gift_amount_btn_hover_color' => sanitize_text_field( $this->request->get( 'gift_amount_btn_hover_color' ) ),
            'add_to_cart_btn_color' => sanitize_text_field( $this->request->get( 'add_to_cart_btn_color' ) ),
            'add_to_cart_btn_hover_color' => sanitize_text_field( $this->request->get( 'add_to_cart_btn_hover_color' ) ),
            'redeem_btn_color'      => sanitize_text_field( $this->request->get( 'redeem_btn_color' ) ),
            'redeem_btn_hover_color'      => sanitize_text_field( $this->request->get( 'redeem_btn_hover_color' ) ),
            'initial_message'       => sanitize_textarea_field( $this->request->get( 'initial_message' ) ),
            'gift_card_background'  => $gift_card_background,
        );

        $existingSettings['design_settings'] = $design_settings;

        // Update or insert the settings in the wp_options table.
        self::updateOption('sgc_smart_gift_general_settings', $existingSettings);

        $data = [
            'message' => 'Design Settings updated successfully!',
            'settings' => $this->general_settings()
        ];

        // Return a success response after updating.
        return $this->response($data, 200);
    }
}
