<?php

/**
 * Class Wiaas_Admin_CL_Customers
 */
class Wiaas_Admin_CL_Customers {

	/**
	 * Displays table list of customers that are linked to commercial lead
	 *
	 * Enables commercial lead to update default order type for his shop
	 *
	 * Enables commercial lead to update order type for specific shop customer
	 *
	 */

    public static function init() {

    	add_action( 'admin_menu', array( __CLASS__, 'add_customers_page' ), 9 );
    }

	/**
	 * Add customer menu page for commercial lead
	 */
    public static function add_customers_page() {
        add_menu_page(
            __( 'Customers', 'wiaas' ),
            __( 'Customers', 'wiaas' ),
            'manage_wiaas_cl_customers',
            'wiaas-cl-customers',
            array(__CLASS__, 'output_customers'),
            'dashicons-groups',
            '66.0' );
    }

	/**
	 * Render content for customer menu page
	 */
    public static function output_customers() {
        $organization_id = wiaas_get_current_user_organization_id();

        // handle default order type update if needed
	    if (! empty($_POST['wiaas_update_cl_default_order_type_nonce']) &&
	        ! empty($_POST['default_order_type']) &&
	        wp_verify_nonce(
	        	$_POST['wiaas_update_cl_default_order_type_nonce'],
		        'wiaas_update_cl_default_order_type')
	    ) {

	    	$default_order_type = sanitize_key($_POST['default_order_type']);

		    Wiaas_Shop::update_default_order_type($organization_id, $default_order_type);

	    }

	    // handle customer order type update if needed
	    if (! empty($_POST['wiaas_update_cl_customer_order_type_nonce']) &&
	        ! empty($_POST['customer_order_type']) &&
	        wp_verify_nonce(
	        	$_POST['wiaas_update_cl_customer_order_type_nonce'],
		        'wiaas_update_cl_customer_order_type')
	    ) {

			$customer_id = absint($_POST['customer_order_type']['customer_id']);
			$order_type = sanitize_key($_POST['customer_order_type']['order_type']);

		    Wiaas_Shop::update_shop_customer_order_type(
				$organization_id,
				$customer_id,
				$order_type);
	    }

	    $customers = Wiaas_Shop::get_shop_customers($organization_id);

        require 'views/html-admin-cl-customers-page.php';
    }
}

Wiaas_Admin_CL_Customers::init();
