<?php
/**
 * Cost & Reports
 *
 * @package CostReports/includes
 */

defined( 'ABSPATH' ) || exit;

require_once dirname( __FILE__ ) . '/class-cyp-functions.php';

/**
 * Class for hooks and functions
 */
class Cyp_Woo {


	/**
	 * Admin hooks
	 */
	public static function cyp_admin_hooks() {
		
		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'cyp_header_scripts' ) );

		add_action( 'woocommerce_product_options_general_product_data', array( __CLASS__, 'cyp_add_product_options_pricing' ) );
		add_action( 'admin_notices', array( __CLASS__, 'cyp_admin_activation_notice_success' ) );
		add_action( 'woocommerce_process_product_meta', array( __CLASS__, 'cyp_save_product_meta_fields' ) );

		add_filter( 'woocommerce_order_item_display_meta_key', array( __CLASS__, 'cyp_set_custom_order_display_name_callback' ) );
		add_filter( 'admin_footer_text', array( __CLASS__, 'cyp_set_footer_text' ) );
		
		//CYP
		add_action( 'cyp_action_cyp_create_link_to_wbte', array( __CLASS__, 'cyp_create_link_to_wbte' ) );

		//Ajax
		add_action( 'wp_ajax_cyp_get_customer_details', array( __CLASS__,  'cyp_get_customer_details_callback' ) );
		add_action( 'wp_ajax_nopriv_cyp_get_customer_details', array( __CLASS__,  'cyp_get_customer_details_callback' ) );

		//Add settings
		add_filter( 'woocommerce_get_settings_pages', array( __CLASS__, 'cyp_add_settings' ) );

		//Add settings
		self::cyp_add_language_support();

	}

	/**
	 * Get customer data
	 */
	public static function cyp_get_customer_details_callback() {

		check_ajax_referer( 'footer_id', 'nonce' );
		$data        = wp_unslash( $_POST );
		$customer_id = $data['customer_id'];

		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( 'You do not have sufficient permissions' );
		}
	
		$customer     = new WC_Customer( $customer_id );
		$total_spent  = $customer->get_total_spent();
		$total_orders = $customer->get_order_count();

		$html  = '<h4>' . __( 'Name: ', 'woo-calculate-your-price' ) . esc_html( $customer->get_first_name() ) . ' ' . esc_html( $customer->get_last_name() ) . '</h4>';
		$html .= '<div>' . __( 'Total Spent: ', 'woo-calculate-your-price' ) . wc_price( $total_spent ) . '</div>';
		$html .= '<div>' . __( 'Total Orders: ', 'woo-calculate-your-price' ) . (int) $total_orders . '</div><br/>';
	
		wp_send_json_success( $html );
		wp_die();
	}

	/**
	 * Add scripts and style
	 *
	 * @param var $hook object.
	 */
	public static function cyp_header_scripts( $hook ) {
		
		if ( 'woocommerce_page_crw' !== $hook ) {
			return;
		}

		if ( defined( 'WC_VERSION' ) ) {
			$woocommerce_version = WC_VERSION;
		} else {
			$woocommerce_version = 'unknown'; // Fallback if WooCommerce is not installed
		}
		
		wp_register_script( 'cyp_jquery-ui', 'https://code.jquery.com/ui/1.14.1/jquery-ui.js', array( 'jquery' ), '1.14.1', true );
		wp_enqueue_script( 'cyp_jquery-ui' );

		wp_register_script( 'cyp_tablecalc', plugins_url( '../assets/js/jquery.tablecalc.min.js', __FILE__ ), array( 'jquery' ), CAS_COST_REPORTS_VS, false );
		wp_enqueue_script( 'cyp_tablecalc' );

		wp_enqueue_script( 'select2' ); // WooCommerce includes this by default in the admin
		wp_enqueue_style( 'select2' );  // WooCommerce includes the styles
		
		if ( CAS_COST_REPORTS_PROD ) {
			wp_register_script( 'cyp_scripts', plugins_url( '../assets/js/cyp-scripts.min.js', __FILE__ ), array( 'jquery' ), CAS_COST_REPORTS_VS, true );
		} else {
			wp_register_script( 'cyp_scripts', plugins_url( '../assets/js/cyp-scripts.js', __FILE__ ), array( 'jquery' ), CAS_COST_REPORTS_VS, true );
		}	

		wp_register_script( 'lozad', 'https://cdn.jsdelivr.net/npm/lozad/dist/lozad.min.js', array(), '1', false );
		wp_enqueue_script( 'lozad' );

		wp_register_script( 'exportjs', 'https://cdn.jsdelivr.net/npm/@linways/table-to-excel@1.0.4/dist/tableToExcel.min.js', array(), '1', false );
		wp_enqueue_script( 'exportjs' );

		wp_register_style( 'woocommerce_admin', plugins_url( '../plugins/woocommerce/assets/css/admin.css' ), array(), $woocommerce_version );
		wp_enqueue_style( 'woocommerce_admin' );

		wp_register_style( 'fonta', 'https://use.fontawesome.com/releases/v6.4.2/css/all.css', array(), '6.4.2' );
		wp_enqueue_style( 'fonta' );

		wp_register_style( 'jquery-ui', 'https://code.jquery.com/ui/1.14.1/themes/base/jquery-ui.css', array(), '1.14.1', 'all' );
		wp_enqueue_style( 'jquery-ui' );

		wp_register_style( 'cyp_css', plugins_url( '../assets/css/cyp.css', __FILE__ ), array(), CAS_COST_REPORTS_VS );
		wp_enqueue_style( 'cyp_css' );

		wp_register_style( 'cyp_dark_css', plugins_url( '../assets/css/cyp-dark.css', __FILE__ ), array(), CAS_COST_REPORTS_VS );
		wp_enqueue_style( 'cyp_dark_css' );
		

		$options    	    = get_option( 'cyp_options' );
		$default_markup     = $options['cyp_default_markup'];
		$default_pages      = $options['cyp_posts_per_page'];
		$shipping_cost      = $options['cyp_show_shipping_cost_tbl'];
		$hide_id_sku        = ( isset( $options['cyp_table_hide_id_sku'] ) && 'yes' === $options['cyp_table_hide_id_sku'] ) ? 'true' : 'false';
		$sum_col            = 11;
		$prices_include_tax = get_option( 'woocommerce_prices_include_tax' );
		
		if ( 'yes' === $shipping_cost ) {
			$sum_col = 12;
		}

		$currency_data = array(
			'currency_symbol'    => get_woocommerce_currency_symbol(),
			'decimal_separator'  => wc_get_price_decimal_separator(),
			'thousand_separator' => wc_get_price_thousand_separator(),
			'decimals'           => wc_get_price_decimals(),
			'currency_position'  => get_option( 'woocommerce_currency_pos' ),
		);

		$obj_data = array_merge(
			array(
				'products'        => __( 'Products', 'woo-calculate-your-price' ),
				'variations'      => __( 'Variations', 'woo-calculate-your-price' ),
				'decimal_sep'     => get_option( 'woocommerce_price_decimal_sep' ),
				'thousand_sep'    => get_option( 'woocommerce_price_thousand_sep' ),
				'num_decimals'    => get_option( 'woocommerce_price_num_decimals' ),
				'default_markup'  => $default_markup,
				'default_pages'   => $default_pages,
				'shipping_cost'   => $shipping_cost,
				'hide_id_sku'     => $hide_id_sku,
				'sum_col'         => $sum_col,
				'woo_inc_tax'     => $prices_include_tax,
				'orders_role'     => $options['cyp_orders_show_role'],
				'orders_company'  => $options['cyp_orders_show_company'],
				'orders_custom1'  => $options['cyp_custom_1_orders'],
				'orders_custom2'  => $options['cyp_custom_2_orders'],
				'select_cat'      => __( 'Select Categories', 'woo-calculate-your-price' ),
				'tags_filter'     => __( 'Select Tags', 'woo-calculate-your-price' ),
				'stock_filter'    => __( 'Select Stock Status', 'woo-calculate-your-price' ),
				'customer_filter' => __( 'Select Customers', 'woo-calculate-your-price' ),
				'order_statuses'  => __( 'Select Statuses', 'woo-calculate-your-price' ),
				'select_dates'    => __( 'Select Date Range', 'woo-calculate-your-price' ),
				'use_dark_mode'   => ! empty( $options[ 'cyp_use_dark_mode' ] ) ? $options[ 'cyp_use_dark_mode' ] : 'no',
			),
			$currency_data
		);
		
		wp_localize_script( 'cyp_scripts', 'cyp_object', $obj_data );
		wp_enqueue_script( 'cyp_scripts' );

	}

	/**
	 * Add settings and language support
	 */
	public static function cyp_add_language_support() {

		load_plugin_textdomain( 'woo-calculate-your-price', false, basename( dirname( __FILE__ ) ) . '/languages' );

	}

	/**
	 * Add settings and language support
	 */
	public static function cyp_add_settings( $settings ) {

		$settings[] = include_once dirname( __FILE__ ) . '../../includes/class-cyp-settings.php';
		return $settings;

	}

	/**
	 * Add extra pricing fields
	 */
	public static function cyp_add_product_options_pricing() {

		$cyp_options         = get_option( 'cyp_options' );
		$hide_purchase_price = $cyp_options['cyp_hide_purchase_price'] ? $cyp_options['cyp_hide_purchase_price'] : 'no';
		$hide_cost_of_goods  = $cyp_options['cyp_hide_cost_of_goods'] ? $cyp_options['cyp_hide_cost_of_goods'] : 'no';
		$purchase_price_lbl  = ! empty ( $cyp_options['cyp_purchase_price_label'] ) ? $cyp_options['cyp_purchase_price_label'] : 'Purchase price';
		
		if ( 'no' === $hide_purchase_price ) {
			woocommerce_wp_text_input(
				array(
					'id'                => '_purchase_price',
					'class'             => 'wc_input_price',
					'label'             => __( $purchase_price_lbl, 'woo-calculate-your-price' ),
					'type'              => 'text',
				)
			);
		} else {
			woocommerce_wp_hidden_input(
				array(
					'id'                => '_purchase_price',
					'label'             => __( $purchase_price_lbl, 'woo-calculate-your-price' ),
					'type'              => 'number',
					'custom_attributes' => array(
						'step' 	=> 'any',
						'min'	=> '0',
						) 
				)
			);
		}

		woocommerce_wp_hidden_input(
			array(
				'id'        => '_cyp_shipping_cost',
				'label'     => __( 'Shipping cost', 'woo-calculate-your-price' ),
				'type'      => 'number',
			)
		);

		woocommerce_wp_hidden_input(
			array(
				'id'        => '_other_cost',
				'label'     => __( 'Other cost', 'woo-calculate-your-price' ),
				'type'      => 'number',
			)
		);

		if ( 'no' === $hide_cost_of_goods ) {
			woocommerce_wp_text_input(
				array(
					'id'        => '_cost_of_goods',
					'class'     => 'wc_input_price',
					'label'     => __( 'Cost of goods', 'woo-calculate-your-price' ),
					'type'      => 'text',
				)
			);
		} else {
			woocommerce_wp_hidden_input(
				array(
					'id'        => '_cost_of_goods',
					'label'     => __( 'Cost of goods', 'woo-calculate-your-price' ),
					'type'      => 'number',
				)
			);
		}

		woocommerce_wp_hidden_input(
			array(
				'id'                => '_markup_percent',
				'label'             => __( 'Markup', 'woo-calculate-your-price' ),
				'type'              => 'number',
				'custom_attributes' => array(
					'step' 	=> 'any',
					'min'	=> '0',
					) 
			)
		);
	}

	/**
	 * On activation notice
	 */
	public static function cyp_admin_activation_notice_success() {

		$allowed_tags = array(
			'a' => array(
				'class'  => array(),
				'href'   => array(),
				'target' => array(),
				'title'  => array(),
			),
		);

		/* translators: %s: url for documentation */
		$read_doc = __( 'Read the <a href="%1$s" target="_blank"> extension documentation </a> for more information.', 'woo-calculate-your-price' );
		$out_str  = sprintf( $read_doc, esc_url( 'https://docs.woocommerce.com/document/cost-reports-woocommerce' ) );

		if ( get_transient( 'cyp-admin-notice-activated' ) ) {
			?>
			<div class="updated woocommerce-message">
				<a class="woocommerce-message-close notice-dismiss" href="<?php echo esc_url( wp_nonce_url( add_query_arg( 'wc-hide-notice', 'cyp_admin_activation_notice_success' ), 'woocommerce_hide_notices_nonce', '_wc_notice_nonce' ) ); ?>"><?php esc_html_e( 'Dismiss', 'woo-calculate-your-price' ); ?></a>
				<p>
					<?php esc_html_e( 'Thank you for installing Cost & Reports for WooCommerce. You can now start using the extension. ', 'woo-calculate-your-price' ); ?>
					<?php echo wp_kses( $out_str, $allowed_tags ); ?>
				</p>
				<p class="submit">
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=crw' ) ); ?>" class="button-primary"><?php esc_html_e( 'Start Cost & Reports', 'woo-calculate-your-price' ); ?></a>
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=wc-settings&tab=crw' ) ); ?>" class="button-secondary"><?php esc_html_e( 'Settings', 'woo-calculate-your-price' ); ?></a>
				</p>
			</div>

			<?php
			delete_transient( 'cyp-admin-notice-activated' );
		}
	}

	/**
	 * Save custom fields to Products.
	 *
	 * @param var $product_id product id.
	 */
	public static function cyp_save_product_meta_fields( $product_id ) {
		
		$nonce = isset( $_REQUEST['woocommerce_meta_nonce'] ) ? sanitize_text_field( $_REQUEST['woocommerce_meta_nonce'] ) : ''; // @codingStandardsIgnoreLine.
		if ( ! wp_verify_nonce( $nonce, 'woocommerce_save_data' ) ) { 
			return;
		}

		$cyp_options    = get_option( 'cyp_options' );
		$cog_field      = ( $cyp_options['cyp_cost_of_goods_field'] ) ? $cyp_options['cyp_cost_of_goods_field'] : '_cost_of_goods';
		$product        = wc_get_product( $product_id );
		$cost_of_goods  = isset( $_POST['_cost_of_goods'] ) ? sanitize_text_field( $_POST['_cost_of_goods'] ) : '';
		$purchase_price = isset( $_POST['_purchase_price'] ) ? sanitize_text_field( $_POST['_purchase_price'] ) : '';
		$shipping_cost  = isset( $_POST['_cyp_shipping_cost'] ) ? sanitize_text_field( $_POST['_cyp_shipping_cost'] ) : '';
		
		if ( $cost_of_goods && '_cost_of_goods' === $cog_field ) {
			$product->update_meta_data( '_cost_of_goods', $cost_of_goods );
		}

		if ( isset( $purchase_price ) ) {
			$product->update_meta_data( '_purchase_price', $purchase_price );	
		}

		if ( isset( $shipping_cost ) ) {
			$product->update_meta_data( '_cyp_shipping_cost', $shipping_cost );	
		}

		$product->save();

	}

	/**
	 * Set display name for COG and purchase price
	 */
	public static function cyp_set_custom_order_display_name_callback( $display_key ) {

		
		if ( is_admin() ) {

			$options            = get_option( 'cyp_options' );
			$purchase_price_lbl = ! empty ( $options['cyp_purchase_price_label'] ) ? $options['cyp_purchase_price_label'] : 'Purchase price';

			if ( '_cost_of_goods' === $display_key ) {
				return __( 'Cost of goods', 'woo-calculate-your-price' );
			}

			if ( '_purchase_price' === $display_key ) {
				return __( $purchase_price_lbl, 'woo-calculate-your-price' );
			}
			
		}
		
		return $display_key;
	}

	
	/**
	 * Set footer text (Home page footer is set in sticky footer template).
	 */
	public static function cyp_set_footer_text( $text ) {
		$page = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS );

		if ( 'crw' === $page ) {
			$img_file = plugins_url( '../consortia-100.png', __FILE__ );

			/* translators: %s: url to vendor and logo */ 
			printf(
				wp_kses(
					/* translators: %s: url to vendor and logo */ 
					__( '- developed by %1$s%2$s%3$s %4$sLove it? Rate us ★★★★★%5$s', 'woo-calculate-your-price' ),
					array(
						'a'    => array( 'href' => array(), 'target' => array(), 'title' => array(), 'style' => array() ),
						'img'  => array( 'src' => array(), 'class' => array(), 'alt' => array() )
					)
				),
				'<a href="https://www.consortia.no/en/" target="_blank" style="font-size: smaller;">',
				'<img src="' . esc_url( $img_file ) . '" class="cas-logo" alt="Consortia logo">',
				'</a>',
				'<a href="https://woocommerce.com/products/cost-reports-woocommerce/#reviews" target="_blank" title="' . esc_attr__( 'Rate this plugin', 'woo-calculate-your-price' ) . '" style="padding-left:4px; text-decoration: none;font-size: smaller;">',
				'</a>'
			);
		} else {
			return $text;
		}

	}

	/** 
	 * If Bulk Table Editor is present create link
	 */
	public static function cyp_create_link_to_wbte() {

		if ( is_plugin_active( 'woo-bulk-table-editor/woo-bulk-table-editor.php' ) ) {
			$p_cat = filter_input( 1, 'product_cat', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
			?>
			<a href="<?php echo esc_url( admin_url( 'edit.php?post_type=product&page=wbte-products&product_cat=' . $p_cat ) ); ?>" class="button" id="wbte">
				<i class="fas fa-tags"></i> <?php esc_attr_e( 'Bulk Table Editor', 'woo-calculate-your-price' ); ?></a>
			<?php
		}

	}

}
Cyp_Woo::cyp_admin_hooks();

