<?php

/**
 * Class Wiaas_Admin_CM_Packages
 *
 */
class Wiaas_Admin_CL_Packages {

	/**
	 * Handles output of Commercial Lead packages page in admin panel.
	 *
	 * Shows list of packages available for sale and packages sold by current commercial lead.
	 * Enables adding package to commercial lead catalogue and setting package specific prices
	 * for current commercial lead.
	 *
	 */

	public static function init() {

		add_action( 'admin_enqueue_scripts', array(__CLASS__, 'enqueue_scripts'), 100 );

		add_action( 'admin_menu', array(__CLASS__, 'add_cl_packages_menu') );

		add_action( 'admin_head', array( __CLASS__, 'menu_highlight' ) );

		add_filter( 'manage_product_posts_columns', array( __CLASS__, 'define_list_table_products_columns' ), 999 );

		add_filter( 'bulk_actions-edit-product', array( __CLASS__, 'define_list_table_products_bulk_actions' ), 999 );

		add_filter( 'views_edit-product', array( __CLASS__, 'define_list_table_products_views' ), 999 );

		add_filter( 'post_row_actions', array( __CLASS__, 'define_list_table_products_row_actions' ), 999, 2 );

		add_filter( 'list_table_primary_column', array( __CLASS__, 'define_list_table_products_primary_column' ), 999, 2 );

		add_action( 'manage_product_posts_custom_column', array( __CLASS__, 'render_list_table_products_columns' ), 10, 2 );
	}

	public static  function enqueue_scripts() {
		$plugin_url = untrailingslashit( plugins_url( '/', WIAAS_FILE ) );

		wp_enqueue_style( 'wiaas_admin_menu', $plugin_url . '/assets/css/menu.css' );
	}

	public static function add_cl_packages_menu() {
		add_submenu_page(
			'edit.php?post_type=product',
			__( 'Products', 'wiaas' ),
			null,
			'manage_wiaas_cl_products',
			'wiaas-cl-package',
			array(__CLASS__, 'output_package')
		);
	}

	public static function menu_highlight() {
		global $parent_file;

		$screen = get_current_screen();

		if ($screen->id === 'admin_page_wiaas-cl-product') {

			$parent_file  = 'edit.php?post_type=product';
		}
	}

	public static function output_package() {
		wp_enqueue_script( 'jquery-ui-tabs' );

		$package_id = absint( $_GET['cl_package_id'] );

		$package = wc_get_product($package_id);

		if (!$package) {
			return;
		}

		if (! empty($_POST['wiaas_save_cl_extras_nonce']) && ! empty($_POST['cl_extras'])) {
			 if (wp_verify_nonce($_POST['wiaas_save_cl_extras_nonce'], 'wiaas_save_cl_extras')) {
				 self::_handle_cl_extras_update($package_id);
			 }
		}

		$bundled_items = $package->get_bundled_items();

		$bundled_items_per_category = array();
		foreach ($bundled_items as $bundled_item) {
			$category = Wiaas_Product_Category::get_category($bundled_item->product);
			if (isset($category)) {
				if ($category ==='hardware' || $category === 'software') {
					$category = 'products';
				}
				$bundled_items_per_category[$category] ?: array();
				$bundled_items_per_category[$category][] = $bundled_item;
			}
		}

		$configured_prices = Wiaas_Package_Pricing::get_package_prices($package);

		$cl_id = wiaas_get_current_user_organization_id();

        $cl_extras = Wiaas_Package_CL_Pricing::get_extras($cl_id, $package_id);

        $has_default_cl_extras = ! empty($cl_extras);

		// default values for catalogue package
		if (! $has_default_cl_extras) {
            $cl_extras = array();

			foreach ($configured_prices as $type => $configured_price) {
                $cl_extras[$type.'_default'] = array(
					'visible' => true,
					'fixed' => 0,
					'services' => 0,
					'recurrent' => 0
				);
			}
		}

		$package_cl_extra_types = array_keys($cl_extras);

		$customer_ids_with_extras = array();
		foreach ($package_cl_extra_types as $package_cl_extra_type) {
			$customer_id_with_extras = explode('_customer_', $package_cl_extra_type)[1];

			if (isset($customer_id_with_extras) && ($customer_id_with_extras = absint($customer_id_with_extras)) > 0) {
				$customer_ids_with_extras[] = $customer_id_with_extras;
			}
		}
		$customer_ids_with_extras = array_unique($customer_ids_with_extras);

		require 'views/html-cl-package-details.php';
	}


	/**
	 * @section Customize display of list table products for commercial lead
	 */

	/**
	 * Define columns for commercial lead view
	 * @param array $columns
	 *
	 * @return array
	 */
	public static function define_list_table_products_columns($columns) {
		$cl_columns = array();

		$cl_columns['thumb'] = $columns['thumb'];
		$cl_columns['wiaas_cl_name'] = $columns['name'];
		$cl_columns['taxonomy-product_tag']  = __( 'Reference', 'wiaas' );
		$cl_columns['taxonomy-package_type'] = __('Type', 'wiaas');
		$cl_columns['taxonomy-package_status'] = __('Status', 'wiaas');
		$cl_columns['taxonomy-product_country'] = $columns['taxonomy-product_country'];
		$cl_columns['date'] = $columns['date'];

		return $cl_columns;
	}

	/**
	 * Hide list table products bulk actions for commercial lead view
	 *
	 * @return array
	 */
	public static function define_list_table_products_bulk_actions() {
		return array();
	}

	/**
	 * Hide list table products views for commercial lead view
	 *
	 * @return array
	 */
	public static function define_list_table_products_views() {
		return array();
	}

	/**
	 * Show only ID in table products views for commercial lead view
	 *
	 * @return array
	 */
	public static function define_list_table_products_row_actions($actions, $post) {
		if ($post->post_type === 'product') {
			return array( 'id' => sprintf( __( 'ID: %d', 'woocommerce' ), $post->ID ) );
		}

		return $actions;
	}

	/**
	 *  Define custom primary column in list table products for commercial lead view
	 *
	 * @param $default
	 * @param $screen_id
	 *
	 * @return string
	 */
	public static function define_list_table_products_primary_column($default, $screen_id) {
		if ( 'edit-product' === $screen_id ) {
			return 'wiaas_cl_name';
		}
		return $default;
	}

	public static function render_list_table_products_columns($column, $post_id) {
		if ($column === 'wiaas_cl_name') {

			$package = wc_get_product($post_id);

			$edit_link = admin_url( 'edit.php?post_type=product&page=wiaas-cl-package&cl_package_id=' . absint( $package->get_id() ) );

			echo '<strong><a class="row-title" href="' . esc_url( $edit_link ) . '">' . esc_html( $package->get_title() ) . '</a></strong>';
		}
	}




	// PRIVATE HANDLERS

	private static function _handle_cl_extras_update($package_id) {
		$cl_extras = wp_unslash($_POST['cl_extras']);

		$pay_types = array_keys(Wiaas_Package_Pricing::get_available_pay_types());

		$posted_cl_extras = array();

		foreach ($cl_extras as $cl_extra) {

			$customer_id = isset($cl_extra['customer']) ? absint($cl_extra['customer']) : 0;
			$type = sanitize_key($cl_extra['type']);

			$fixed_extra = isset($cl_extra['fixed']) ? floatval($cl_extra['fixed']) : 0;
			$services_extra = isset($cl_extra['services']) ? floatval($cl_extra['services']) : 0;
			$recurrent_extra = isset($cl_extra['recurrent']) ? floatval($cl_extra['recurrent']) : 0;

			$extra_type = $customer_id > 0 ? $type.'_customer_'.$customer_id : $type.'_default';

			if (in_array($type, $pay_types)) {
				$posted_cl_extras[$extra_type] = array(
					'type' => $type,
					'visible' => $cl_extra['visible'] === 'on',
					'fixed' => $fixed_extra,
					'services' => $services_extra,
					'recurrent' => $recurrent_extra,
				);
			}
		}

        Wiaas_Package_CL_Pricing::set_extras(
			wiaas_get_current_user_organization_id(),
			$package_id,
			$posted_cl_extras
		);
	}
}

Wiaas_Admin_CL_Packages::init();
