<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Buy_One_Get_One_Free_Woocommerce_Menu{

    public $plugin_name;
    public $menu;
    public $version;
    
    function __construct($plugin_name , $version){
        $this->plugin_name = $plugin_name;
        $this->version = $version;
        add_action( 'admin_menu', array($this,'plugin_menu') );
        add_action($this->plugin_name.'_promotion', array($this,'promotion'));

        add_action( 'wp_ajax_pisol_bogo_search_product', array( $this, 'search_product' ) );

        add_action( 'admin_enqueue_scripts', array($this,'removeConflictCausingScripts'), 1000 );
    }

    function plugin_menu(){
        
        $this->menu = add_menu_page(
            __( 'BOGO Deal','buy-one-get-one-free-woocommerce'),
            __( 'BOGO Deal','buy-one-get-one-free-woocommerce'),
            'manage_options',
            'pisol-bogo-deal',
            array($this, 'menu_option_page'),
            'dashicons-cart',
            6
        );

        add_action("load-".$this->menu, array($this,"bootstrap_style"));
 
    }

    public function bootstrap_style() {

        
        
        wp_enqueue_style( $this->plugin_name."_bootstrap", plugin_dir_url( __FILE__ ) . 'css/bootstrap.css', array(), $this->version, 'all' );
        wp_register_script( 'selectWoo', WC()->plugin_url() . '/assets/js/selectWoo/selectWoo.full.min.js', array( 'jquery' ) );
        wp_enqueue_script( 'selectWoo' );
        wp_enqueue_style( 'select2', WC()->plugin_url() . '/assets/css/select2.css');

        wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/buy-one-get-one-free-woocommerce-admin.js', array( 'jquery', 'selectWoo' ), $this->version, false );

        wp_enqueue_script( $this->plugin_name."_quick_save", plugin_dir_url( __FILE__ ) . 'js/pisol-quick-save.js', array('jquery'), $this->version, 'all' );
		
	}

    function menu_option_page(){
        if(function_exists('settings_errors')){
            settings_errors();
        }
        ?>
        <div class="bootstrap-wrapper">
        <div class="pisol-container mt-2">
            <div class="pisol-row">
                    <div class="col-12">
                        <div class='bg-dark'>
                        <div class="pisol-row">
                            <div class="col-12 col-sm-2 py-2 d-flex align-items-center justify-content-center">
                                    <a href="https://www.piwebsolution.com/" target="_blank"><img id="pi-logo" class="img-fluid ml-2" src="<?php echo esc_url(plugin_dir_url( __FILE__ )); ?>img/pi-web-solution.svg"></a>
                            </div>
                            <div class="col-12 col-sm-10 d-flex text-center small">
                                <nav id="pisol-navbar" class="navbar navbar-expand-lg navbar-light mr-0 ml-auto">
                                    <div>
                                        <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                                            <?php do_action($this->plugin_name.'_tab'); ?>
                                            <a class=" px-3 text-light d-flex align-items-center  border-left border-right   mr-0 ml-auto" href="https://www.piwebsolution.com/buy-one-get-one-free-offer-maker-plugin-for-woocommerce/">
                                               <span class="dashicons dashicons-book"></span> User Guide
                                            </a>
                                        </ul>
                                    </div>
                                </nav>
                            </div>
                        </div>
                        </div>
                    </div>
            </div>
            <div class="pisol-row">
                <div class="col-12">
                <div class="bg-light border pl-3 pr-3 pt-0">
                    <div class="pisol-row">
                        <div class="col">
                        <?php do_action($this->plugin_name.'_tab_content'); ?>
                        </div>
                        <?php do_action($this->plugin_name.'_promotion'); ?>
                    </div>
                </div>
                </div>
            </div>
        </div>
        </div>
        <?php
    }

    function promotion(){
        if(isset($_GET['tab']) && $_GET['tab'] == 'bogo_category_rule') return;
        ?>
        <div class="col-12 col-sm-12 col-md-4 border-left">
            <div class="pi-shadow mt-3 rounded">
                <h2 id="pi-banner-tagline" class="mb-0 pt-4" style="color:#ccc !important;">
                        <span class="d-block mb-4">⭐️⭐️⭐️⭐️⭐️</span>
                        <span class="d-block mb-2">🚀 Trusted by <span style="color:#fff;">1,000+</span> WooCommerce Stores</span>
                        <span class="d-block mb-2">Rated <span style="color:#fff;">4.9/5</span> – Users love it</span>
                </h2>
                <div class="inside my-4 pl-2">
                    <ul class="text-left pisol-pro-feature-list mb-4">
                        <li>✓ Offer BOGO product as Free or Discounted</li>
                        <li>✓ Set BOGO on category level</li>
                        <li>✓ Exclude products from category offer</li>
                        <li>✓ Override category offer at product level</li>
                        <li>✓ Set max spend limit per category</li>
                        <li>✓ Show category offer on category pages</li>
                        <li>✓ Offer same or different product as free</li>
                        <li>✓ Set different free product for each product</li>
                        <li>✓ Set custom buy quantity</li>
                        <li>✓ Set custom free quantity</li>
                        <li>✓ Set offer start & end date</li>
                        <li>✓ Set different messages before/after start</li>
                        <li>✓ Create custom offer message using shortcodes</li>
                        <li>✓ Apply offers to all variations</li>
                        <li>✓ Restrict offer to specific variations</li>
                        <li>✓ Show offer message only for eligible variations</li>
                        <li>✓ Offer different free product per variation</li>
                        <li>✓ Set custom quantity & limits per variation</li>
                        <li>✓ Set different schedule per variation</li>
                        <li>✓ Set unique message per variation</li>
                        <li>✓ Allow customer to remove free product</li>
                        <li>✓ Allow changing variation of free variable product</li>
                        <li>✓ Run category offers on specific weekdays</li>
                        <li>✓ Let customer choose from multiple free products</li>
                        <li>✓ Allow switching free product on cart/checkout</li>
                    </ul>
                    <h4 class="pi-bottom-banner">💰 Just <?php echo esc_html(PI_BOGO_PRICE); ?></h4>
                    <h4 class="pi-bottom-banner">🔥 Unlock all features and grow your sales!</h4>
                    <div class="text-center pb-3 pt-2">
                        <a class="btn btn-primary btn-lg" href="<?php echo esc_url(PI_BOGO_BUY_URL); ?>&utm_ref=bottom_link" target="_blank">🔓 Unlock Pro Now – Limited Time Price!</a>
                    </div>
                </div>
            </div>

            <div class="bg-dark opacity-75 text-light text-center mb-3">
                <a class="" href="<?php echo esc_url(PI_BOGO_BUY_URL); ?>&utm_ref=discount_banner" target="_blank">
                <?php new pisol_promotion('pisol_bogo_installation_date'); ?>
                </a>
            </div>
            
        </div>
        <?php
        $this->support();
    }

    function isWeekend() {
        return (wp_date('N', strtotime(wp_date('Y/m/d'))) >= 6);
    }

    public function search_product( $x = '', $post_types = array( 'product' ) ) {

		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

        ob_start();
        
        if(!isset($_GET['keyword'])) die;

		$keyword = isset($_GET['keyword']) ? sanitize_text_field($_GET['keyword']) : "";

		if ( empty( $keyword ) ) {
			die();
		}
		$arg            = array(
			'post_status'    => 'publish',
			'post_type'      => $post_types,
			'posts_per_page' => 50,
			's'              => $keyword

		);
		$the_query      = new WP_Query( $arg );
		$found_products = array();
		if ( $the_query->have_posts() ) {
			while ( $the_query->have_posts() ) {
				$the_query->the_post();
				$prd = wc_get_product( get_the_ID() );
				$cat_ids  = wp_get_post_terms( get_the_ID(), 'product_cat', array( 'fields' => 'ids' ) );

				/* remove grouped product or external product */
				if($prd->is_type('grouped') || $prd->is_type('external')){
					continue;
				}
				

				if ( $prd->has_child() && $prd->is_type( 'variable' ) ) {
					
				} else {
					$product_id    = get_the_ID();
					$product_title = get_the_title();
					$the_product   = new WC_Product( $product_id );
					if ( ! $the_product->is_in_stock() ) {
						$product_title .= ' (Out of stock)';
					}
					$product          = array( 'id' => $product_id, 'text' => $product_title );
					$found_products[] = $product;
				}
			}
        }
		wp_send_json( $found_products );
		die;
    }

    function removeConflictCausingScripts(){
        if(isset($_GET['page']) && $_GET['page'] == 'pisol-bogo-deal'){
            /* fixes css conflict with Nasa Core */
            wp_dequeue_style( 'nasa_back_end-css' );
        }
    }

    function support(){
        $website_url = home_url();
        $plugin_name = $this->plugin_name;
        ?>
        <form action="https://www.piwebsolution.com/quick-support/" method="post" target="_blank" style="display:inline; position:fixed; bottom:30px; right:30px; z-index:9999;" >
            <input type="hidden" name="website_url" value="<?php echo esc_attr( $website_url ); ?>">
            <input type="hidden" name="plugin_name" value="<?php echo esc_attr( $plugin_name ); ?>">
            <button type="submit" style="background:none;border:none;cursor:pointer;padding:0;">
                <img src="<?php echo esc_url( plugin_dir_url( __FILE__ ) ); ?>img/chat.png" 
                    alt="Live Support" title="Quick Support" style="width:60px;height:60px;">
            </button>
        </form>
        <?php
    }

}