<?php
/**
 * @author      Flycart (Alagesan)
 * @license     http://www.gnu.org/licenses/gpl-3.0.html
 * @link        https://www.flycart.org
 * */

namespace Wlpr\App;

use Wlpr\App\Helpers\Check;
use Wlpr\App\Helpers\License;
use Wlpr\App\Helpers\Loyalty;

class Router
{
    private static $admin, $site, $designer;

    /**
     * init action and filter
     * @since 1.0.0
     */
    function init()
    {
        self::$site = empty(self::$site) ? new \Wlpr\App\Controllers\Site\Main() : self::$site;
        $options = get_option('wlpr_settings', '');
        if (is_admin()) {
            self::$admin = empty(self::$admin) ? new \Wlpr\App\Controllers\Admin\Main() : self::$admin;
            register_activation_hook(WLPR_PLUGIN_FILE, array(self::$admin, 'pluginActivation'));
            $activation_check = new Check();
            if (!$activation_check->init_check()) {
                add_action('all_admin_notices', array($activation_check, 'inactive_notice'));
                return false;
            }
            add_action('wpmu_new_blog', array(self::$admin, 'onCreateBlog'), 10, 6);
            add_filter('wpmu_drop_tables', array(self::$admin, 'onDeleteBlog'));
            add_action('all_admin_notices', array(self::$admin, 'initAdminNotices'));
            add_action('admin_menu', array(self::$admin, 'addMenu'));
            add_filter('plugin_action_links_' . plugin_basename(WLPR_PLUGIN_FILE), array(self::$admin, 'pluginActionLinks'));
            add_action('network_admin_menu', array(self::$admin, 'addMenu'));
            add_action('admin_enqueue_scripts', array(self::$admin, 'adminScripts'), 100);
            /*************************** Category hooks ************************/
            // setting in category page
            add_action('product_cat_add_form_fields', array(self::$admin, 'renderProductCategoryFields'));
            // setting in category edit page
            add_action('product_cat_edit_form_fields', array(self::$admin, 'renderProductCategoryFields'));
            // save setting in category
            add_action('create_product_cat', array(self::$admin, 'saveProductCategoryPointsField'));
            add_action('edited_product_cat', array(self::$admin, 'saveProductCategoryPointsField'));
            /** End Category hooks */
            /*************************** Simple Product hooks ************************/
            // setting in simple product page
            add_action('woocommerce_product_options_general_product_data', array(self::$admin, 'renderSimpleProductFields'));
            // save simple product setting
            add_action('woocommerce_process_product_meta_simple', array(self::$admin, 'saveSimpleProductFields'));
            // save 'Points Earned' field for bundle products
            add_action( 'woocommerce_process_product_meta_bundle', array( self::$admin, 'saveSimpleProductFields' ) );
            /** End Simple Product hooks */
            /************************** Variable product hook ********************/
            // add 'Points Earned' to variable products under the 'Variations' tab after the shipping class dropdown
            add_action('woocommerce_product_after_variable_attributes', array(self::$admin, 'renderVariableProductFields'), 15, 3);
            // save the 'Points Earned' field for variable products
            add_action('woocommerce_save_product_variation', array(self::$admin, 'saveVariableProductFields'), 20);
            // save the 'Points Earned' field for variable subscription products
            //add_action( 'woocommerce_save_product_subscription_variation', array( self::$admin, 'save_variable_product_fields' ) );
            /** End variable product hook */
            // save 'Points Earned' field for subscription products
            add_action('woocommerce_process_product_meta_subscription', array(self::$admin, 'saveSimpleProductFields'));
            if (wp_doing_ajax()) {
                //save global setting
                add_action('wp_ajax_wlpr_save_settings', array(self::$admin, 'saveSettings'));
                add_action('wp_ajax_wlpr_save_referral', array(self::$admin, 'saveReferral'));
                //update point
                add_action('wp_ajax_wlpr_apply_point', array(self::$admin, 'applyPoint'));
                add_action('wp_ajax_wlpr_delete_user', array(self::$admin, 'deleteUser'));
                add_action('wp_ajax_wlpr_bulk_delete_user', array(self::$admin, 'bulkDeleteUser'));

                add_action('wp_ajax_wlpr_save_private_note', array(self::$admin, 'savePrivateCustomerNote'));
                add_action('wp_ajax_wlpr_process_import', array(self::$admin, 'process_import'));
                add_action('wp_ajax_wlpr_process_migration', array(self::$admin, 'process_migration'));
                add_action('wp_ajax_wlpr_update_expire_date', array(self::$admin, 'update_expire_date'));
            }
            add_action('wp_ajax_wlpr_import_popup', array(self::$admin, 'import_popup'));
            add_action('wp_ajax_wlpr_import_popup_preview', array(self::$admin, 'wlpr_import_popup_preview'));
            add_action('wp_ajax_wlpr_export_popup', array(self::$admin, 'export_popup'));
            add_action('wp_ajax_wlpr_process_export', array(self::$admin, 'process_export'));
            add_action('wp_ajax_wlpr_export_file', array(self::$admin, 'export_files'));


            add_action('wp_ajax_wlpr_new_customer_popup', array(self::$admin, 'new_customer_popup'));
            add_action('wp_ajax_wlpr_save_customer', array(self::$admin, 'wlpr_save_customer'));
            //Init the license
            $license = new License();
            $license->initUpdateChecker();
        }else{
            add_action('wp_enqueue_scripts', array(self::$site, 'add_frontend_scripts'));
            add_action('plugins_loaded', array(self::$site, 'includes'));
            add_action('woocommerce_init', array(self::$site, 'setReferCouponToSession'));
            add_action('wp_loaded', array(self::$site, 'addReferCouponToCheckout'), 10);

            // Add javascript used by apply discount button
            //add_action('woocommerce_before_cart', array(self::$site, 'renderDiscountJavascript'));
            //add_action('woocommerce_before_checkout_form', array(self::$site, 'renderDiscountJavascript'));

            /************************** cart/checkout hook ********************/
            $cart_earn_point_display = (isset($options['wlpr_cart_earn_point_display']) && !empty($options['wlpr_cart_earn_point_display']) ? $options['wlpr_cart_earn_point_display'] : 'before');
            if($cart_earn_point_display == 'before'){
                add_action('woocommerce_before_cart', array(self::$site, 'displayEarnPointsMessage'), 13);
            }elseif($cart_earn_point_display == 'after'){
                add_action('woocommerce_after_cart_table', array(self::$site, 'displayEarnPointsMessage'), 13);
            }elseif($cart_earn_point_display == 'content'){
                add_action('woocommerce_cart_contents', array(self::$site, 'displayEarnPointsMessage'), 555);
            }elseif($cart_earn_point_display == 'summary'){
                add_action('woocommerce_cart_totals_before_order_total', array(self::$site, 'checkoutEarnPoints'), 555);
            }
            $cart_redeem_point_display = (isset($options['wlpr_cart_redeem_point_display']) && !empty($options['wlpr_cart_redeem_point_display']) ? $options['wlpr_cart_redeem_point_display'] : 'before');
            if($cart_redeem_point_display == 'before'){
                add_action('woocommerce_before_cart', array(self::$site, 'displayRedeemPointsMessage'), 14);
            }elseif ($cart_redeem_point_display == 'after'){
                add_action('woocommerce_after_cart_table', array(self::$site, 'displayRedeemPointsMessage'), 14);
            }elseif ($cart_redeem_point_display == 'content'){
                add_action('woocommerce_cart_contents', array(self::$site, 'displayRedeemPointsMessage'), 14);
            }
            $referral_settings = get_option('wlpr_referral',array());
            $referral_message_display = (isset($referral_settings['wlpr_cart_referral_message_display']) && !empty($referral_settings['wlpr_cart_referral_message_display']) ? $referral_settings['wlpr_cart_referral_message_display'] : 'before');
            if($referral_message_display == 'before'){
                add_action('woocommerce_before_cart', array(self::$site, 'displayReferralMessage'), 11);
            }elseif($referral_message_display == 'after'){
                add_action('woocommerce_after_cart_table', array(self::$site, 'displayReferralMessage'), 11);
            }
            //checkout
            if($cart_earn_point_display == 'summary'){
                add_action('woocommerce_review_order_before_order_total', array(self::$site, 'checkoutEarnPoints'));
            }else{
                add_action('woocommerce_before_checkout_form', array(self::$site, 'displayEarnPointsMessage'), 5);
            }

            add_action('woocommerce_before_checkout_form', array(self::$site, 'displayRedeemPointsMessage'), 6);
            add_action('woocommerce_before_checkout_form', array(self::$site, 'displayReferralMessage'), 4);
            /** End cart/checkout hook */
            /************************** simple product page hook ********************/
            $display_product_display_position = (isset($options['display_product_display_position']) && !empty($options['display_product_display_position']) ? $options['display_product_display_position'] : 'before_price');
            if(in_array($display_product_display_position,array('before_price','after_price'))){
                add_filter('woocommerce_get_price_html', array(self::$site, 'renderProductMessage'), PHP_INT_MAX, 2);
            }elseif ($display_product_display_position == 'before_add_to_cart'){
                add_action('woocommerce_before_add_to_cart_form', array(self::$site, 'renderProductMessageCart'), PHP_INT_MAX);
                add_filter('woocommerce_loop_add_to_cart_link', array(self::$site, 'renderProductMessageCartLink'), PHP_INT_MAX, 2);
            }elseif ($display_product_display_position == 'after_add_to_cart'){
                add_action('woocommerce_after_add_to_cart_button', array(self::$site, 'renderProductMessageCart'), PHP_INT_MAX);
                add_filter('woocommerce_loop_add_to_cart_link', array(self::$site, 'renderProductMessageCartLink'), PHP_INT_MAX, 2);
            }elseif ($display_product_display_position == 'before_title'){
                add_action('woocommerce_before_shop_loop_item_title', array(self::$site, 'renderProductMessageCart'),PHP_INT_MAX);
                add_action('woocommerce_single_product_summary', array(self::$site, 'renderProductMessageCart'),4);
            }elseif ($display_product_display_position == 'after_title'){
                add_action('woocommerce_after_shop_loop_item_title', array(self::$site, 'renderProductMessageCart'),9);
                add_action('woocommerce_single_product_summary', array(self::$site, 'renderProductMessageCart'),6);
            }
            add_action('woocommerce_before_shop_loop',array(self::$site, 'renderProductMessageStyle'), PHP_INT_MAX);
            add_action('woocommerce_before_single_product',array(self::$site, 'renderProductMessageStyle'), PHP_INT_MAX);
            // thankyou page message
            $thank_you_msg_position = (isset($options['wlpr_thank_you_position']) && !empty($options['wlpr_thank_you_position']) ? $options['wlpr_thank_you_position'] : 'before');
            if($thank_you_msg_position == 'before'){
                add_action('woocommerce_before_thankyou', array(self::$site, 'renderThankYouMessage'));
            }elseif($thank_you_msg_position == 'after'){
                add_action('woocommerce_thankyou', array(self::$site, 'renderThankYouMessage'));
            }
            //product review display
            add_filter('woocommerce_product_review_comment_form_args', array(self::$site, 'displayProductReviewMessage'));
            // display points on a separate tab on user's account page
            add_action('woocommerce_init', array(self::$site, 'add_endpoints'));
            // signup message
            add_action('woocommerce_before_checkout_registration_form', array(self::$site, 'woo_signup_message'));
        }
        // handle the apply discount AJAX submit on the checkout page
        $display_product_display_position = (isset($options['display_product_display_position']) && !empty($options['display_product_display_position']) ? $options['display_product_display_position'] : 'before_price');
        if(in_array($display_product_display_position,array('before_price','after_price'))){
            add_filter('advanced_woo_discount_rules_dynamic_get_price_html', array(self::$site, 'renderProductMessage'), PHP_INT_MAX, 3);
        }
        add_action('wp_ajax_wlpr_loyal_point_remove_fee', array(self::$site, 'ajaxRemoveFee'));

        add_filter('woocommerce_add_to_cart_fragments', array(self::$site, 'displayCartMessageFragment'));
        add_action('wp_ajax_wlpr_apply_loyal_discount', array(self::$site, 'ajaxApplyDiscount'));
        add_action('wp_ajax_nopriv_wlpr_apply_loyal_discount', array(self::$site, 'ajaxApplyDiscount'));
        add_filter('woocommerce_update_order_review_fragments', array(self::$site, 'displayCartMessageFragment'));

        add_action('wp_ajax_wlpr_loyal_point_apply_discount', array(self::$site, 'ajaxApplyDiscount'));
        add_action('wp_ajax_nopriv_wlpr_loyal_point_apply_discount', array(self::$site, 'ajaxApplyDiscount'));
        add_action('wp_ajax_wlpr_loyal_point_get_reword_message', array(self::$site, 'displayEarnPointsMessage'));
        add_action('wp_ajax_nopriv_wlpr_loyal_point_get_reword_message', array(self::$site, 'displayEarnPointsMessage'));

        add_action('wp_ajax_wlpr_validate_license_key', array(self::$admin, 'validateLicenseKey'));

        // Expire points on schedule
        add_action('wlpr_expire_points', array(self::$site, 'expire_points'));
        // Set up hooks and schedules for expirying points daily
        add_action('woocommerce_init', array(self::$site, 'wlpr_expire_points_schedule'));
        register_deactivation_hook(WLPR_PLUGIN_FILE, array(self::$site, 'wlpr_expire_points_remove_schedule'));
        add_action('woocommerce_checkout_update_order_review',array(self::$site,'update_order_review'));
        //$wlpr_discount_method = Loyalty::point()->getDiscountMethod();
        // Fee event
        add_action( 'woocommerce_cart_calculate_fees',array(self::$site, 'getDiscountFeeAmount') );
        add_filter('woocommerce_cart_totals_get_fees_from_cart_taxes', array(self::$site, 'getDiscountFeeTaxes') ,10,3);
        add_filter('woocommerce_cart_totals_fee_html', array(self::$site, 'displayDiscountFee'), 10, 2);
        // Coupon event
        // set our custom coupon data
        add_filter('woocommerce_get_shop_coupon_data', array(self::$site, 'getDiscountData'), PHP_INT_MAX, 2);
        add_filter('woocommerce_coupon_get_discount_amount', array(self::$site, 'getDiscountAmount'), 10, 5);
        add_filter('woocommerce_coupon_error', array(self::$site, 'getDiscountErrorMessage'), 10, 3);
        // filter the custom "coupon applied successfully" message
        add_filter('woocommerce_coupon_message', array(self::$site, 'getDiscountAppliedMessage'), 10, 3);
        // Coupon loading
        add_action('woocommerce_cart_loaded_from_session', array(self::$site, 'pointsLast'));
        add_action('woocommerce_applied_coupon', array(self::$site, 'pointsLast'));
        // handle the apply discount submit on the cart page
        add_action('wp', array(self::$site, 'cartApplyDiscount'));
        //add_action('wp', array(self::$site, 'removeSchedule'));
        // add earned points message on the thank you / order received page
        // reshow messages on checkout if coupon was removed?
        add_action('woocommerce_removed_coupon', array(self::$site, 'discountRemoved'));
        // Coupon display
        add_filter('woocommerce_cart_totals_coupon_label', array(self::$site, 'changeCouponLabel'),10,2);
        add_action('woocommerce_after_calculate_totals', array(self::$site, 'removeThirdPartyCoupon'), 20);
        // End Coupon event
        // delete transients
        add_action('woocommerce_delete_product_transients', array(self::$site, 'deleteTransients'));
        /** end variable message */
        add_action('wp_ajax_wlpr_launcher_change', array(self::$site, 'changeLauncherTemplate'));
        if (defined('WC_VERSION')) {
            // Sync variation prices.
            if (version_compare(WC_VERSION, '3.0.0', '<')) {
                add_action('woocommerce_variable_product_sync', array(self::$site, 'variableProductSync'), 10, 2);
            } else {
                add_action('woocommerce_variable_product_sync_data', array(self::$site, 'variableProductSync'), 10);
            }
        }
        add_action('woocommerce_checkout_update_order_meta', array(self::$site, 'saveReferralToOrder'), 10, 2);
        add_action('woocommerce_after_order_object_save',array(self::$site, 'update_discount_code'),1000,2);
        //update point
        add_action('woocommerce_order_status_changed', array(self::$site, 'updatePoints'),1000,4);
        /*add_action('woocommerce_order_status_processing', array(self::$site, 'updatePoints'));
        add_action('woocommerce_order_status_completed', array(self::$site, 'updatePoints'));
        add_action('woocommerce_order_status_on-hold', array(self::$site, 'updatePoints'));*/
        //add_action('woocommerce_checkout_order_processed', array(self::$site, 'logRedemptionPoints'));
        //add_action('woocommerce_order_status_changed', array(self::$site, 'saveReferralPoint'),10,4);
        // credit points back to the user if their order is cancelled or refunded
        add_action('woocommerce_order_status_cancelled', array(self::$site, 'handleCancelledRefundedOrder'));
        add_action('woocommerce_order_status_refunded', array(self::$site, 'handleCancelledRefundedOrder'));
        add_action('woocommerce_order_status_failed', array(self::$site, 'handleCancelledRefundedOrder'));
        add_action('woocommerce_order_partially_refunded', array(self::$site, 'handlePartiallyRefundedOrder'), 10, 2);
        // add points for user signup & writing a review
        add_action('comment_post', array(self::$site, 'productReviewAction'), 10, 2);
        add_action('comment_unapproved_to_approved', array(self::$site, 'productReviewApproveAction'));
        //

        //register form message
        add_action('woocommerce_register_form', array(self::$site, 'register_form'));
        add_action('register_form', array(self::$site, 'register_form'));
        add_action('user_register', array(self::$site, 'createAccountAction'));
        add_action('wp_login',array(self::$site,'checkIsOldUser'),10,2);

        //short code process
        add_shortcode('wlpr_process_code',array(self::$site, 'process_short_code'));
        //process email
        add_filter( 'woocommerce_email_classes', array(self::$site, 'addEmailClass'));
        // Only proceed if this is own request.
        if (  \Wlpr_Designer::is_own_customizer_request() && \Wlpr_Designer::is_own_preview_request() ) {
            \Wlpr_Designer::get_instance();
        }
        add_action('wp_footer', array(self::$site, 'footer_content'));
        add_action('wlpr_expire_email_points', array(self::$site, 'sendExpirePointEmail'));
        add_action('woocommerce_after_order_item_object_save',array(self::$site, 'item_save_process'),10,2);

        /*custom work*/
        $need_validate_fields = array('wlpr_launcher_login_header_content',
            'wlpr_launcher_login_referee_content',
            'wlpr_launcher_body_login_referee_content',
            'wlpr_launcher_login_no_referral_content',
            'wlpr_launcher_login_referral_content',
            'wlpr_launcher_login_review_content',
            'wlpr_launcher_guest_header_content',
            'wlpr_launcher_guest_signup_content',
            'wlpr_launcher_guest_review_content',
            'wlpr_launcher[preview_customer]',
            'wlpr_launcher_login_referee_card_enable',
            'wlpr_launcher_login_referral_card_enable',
            'wlpr_launcher_login_review_card_enable',
            'wlpr_launcher_guest_signup_card_enable',
            'wlpr_launcher_guest_review_card_enable',
            'wlpr_launcher_login_referee_ordering',
            'wlpr_launcher_login_referral_ordering',
            'wlpr_launcher_login_review_ordering',
            'wlpr_launcher_login_referee_heading',
            'wlpr_launcher_login_referral_heading',
            'wlpr_launcher_login_review_heading',
            'wlpr_launcher_guest_signup_button_text',
            'wlpr_launcher_guest_signup_signin_link_text',
            'wlpr_launcher_guest_review_heading',
            'wlpr_launcher_font_family',
            'wlpr_launcher_login_referee_background_color',
            'wlpr_launcher_login_referee_text_color',
            'wlpr_launcher_login_referral_background_color',
            'wlpr_launcher_login_referral_text_color',
            'wlpr_launcher_login_review_background_color',
            'wlpr_launcher_login_review_text_color',
            'wlpr_launcher_guest_signup_button_color',
            'wlpr_launcher_guest_signup_button_text_color',
            'wlpr_launcher_guest_signup_text_color',
            'wlpr_launcher_guest_signup_background_color',
            'wlpr_launcher_guest_review_background_color',
            'wlpr_launcher_guest_review_text_color',
            'wlpr_launcher_header_background_color',
            'wlpr_launcher_header_text_color',
            'wlpr_launcher_body_background_color',
            'wlpr_launcher_guest_signup_signin_prefix_text',
            'wlpr_launcher_guest_signup_button_url',
            'wlpr_launcher_guest_signup_signin_url',
            'wlpr_launcher[custom_css]'
        );
        foreach ($need_validate_fields as $field){
            add_filter('customize_validate_'.$field, array(self::$admin, 'validateCustomizeSettings'),10,3);
        }

       // add_action( 'customize_changeset_save_data',array(self::$admin, 'beforeSaveCustomizeSettings'), 10, 2 );
       // add_action( 'customize_save_validation_before',array(self::$admin, 'beforeSaveValidation'));

        add_action('wlpr_birth_day_points', array(self::$site, 'onBirthDayPoints'));
        add_action('wp_ajax_wlpr_save_birth_date', array(self::$site, 'saveBirthDate'));
        add_action('wp_ajax_wlpr_facebook_share_reward', array(self::$site, 'facebookShareReward'));
        add_action('wp_ajax_wlpr_twitter_share_reward', array(self::$site, 'twitterShareReward'));
        add_action('wp_ajax_wlpr_email_share_reward', array(self::$site, 'emailShareReward'));
        add_action('wp_ajax_wlpr_whats_app_share', array(self::$site, 'whatsAppShareReward'));
    }
}