<?php 
/**
 * class @var ST_WC_Post_Integration
 */
class ST_WC_Post_Integration {
    /**
	 * Licenses_Woocommerce version.
	 *
	 * @var string
	 */
    public $version = '1.0.0';

    protected static $_instance = null;

    /**
	 * Main Licenses Instance.
	 *
	 * Ensures only one instance of Licenses_Woocommerce is loaded or can be loaded.
	 *
	 * @since 1.0
	 * @static
	 * @see Licenses_Woocommerce()
	 * @return Licenses_Woocommerce - Main instance.
	 */
    public static function instance() {
        if ( is_null( self::$_instance ) ) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function __construct() {
        $this->includes();
        $this->hooks();
    }

    public function includes(){ }

    public function hooks() {

        // Hook to add meta box
        add_action('add_meta_boxes', [$this, 'custom_product_meta_box']);
        // Hook to save meta box data
        add_action('save_post', [$this, 'save_custom_product_meta_box']);
        
        // Add a custom column to the WooCommerce Orders table
        add_filter('manage_woocommerce_page_wc-orders_columns', [$this, 'add_custom_order_column'], 20);
        // Display custom data in the custom column
        add_action('manage_woocommerce_page_wc-orders_custom_column', [$this,'show_custom_order_column_content'], 25, 2);
        // meta box for wc+order
        // add_action( 'woocommerce_admin_order_data_after_order_details', [$this, 'add_custom_order_license_field'] );
        


    }


    public function custom_product_meta_box() {
        add_meta_box(
            'custom_product_meta_box',
            __('Spacetree License Settings', 'licenses_spacetree'),
            [$this, 'render_custom_product_meta_box'],
            'product',
            'normal',
            'high'
        );
    }
    
    // Render the content of the meta box
    public function render_custom_product_meta_box($post) {
        // Retrieve existing value (if any)
        $license_type           = get_post_meta($post->ID, '_spacetree-license-type', true);
        $license_items          = get_post_meta($post->ID, '_spacetree-license-items', true);
        $license_expires_in     = get_post_meta($post->ID, '_spacetree-license-expires-in', true);

        if( !$license_type){
            $license_type = "none";
            $license_items = 1;
        }
        // Output HTML for the input field
        ?>
        <div class="spacetree-licenses-meta-wrap components-base-control__field">
			<p class="post-attributes-label-wrapper">
				<strong>License type </strong>
			</p>
			<select style="min-width: 100%;" name="license-type" id="license-type" class="spacetree-license-select-input">
                <option value="none" <?php echo ($license_type == "none")? 'selected' : ''; ?>>none</option>
				<option value="proqyz-wp" <?php echo ($license_type == "proqyz-wp")? 'selected' : ''; ?>>ProQyz WP License</option>
                <option value="ieltslms-wp" <?php echo ($license_type == "ieltslms-wp")? 'selected' : ''; ?>>IELTSLMS WP License</option>
			</select>
		</div>

        <div class="spacetree-licenses-meta-wrap components-base-control__field">
			<p class="post-attributes-label-wrapper">
				<strong> Domains/License </strong>
			</p>
			<input min="1" style="min-width: 100%;" type="number" id="license-items" name="license-items" class="newtag form-input-tip ui-autocomplete-input" value="<?php echo $license_items; ?>" />
		</div>

        <div class="spacetree-licenses-meta-wrap components-base-control__field">
			<p class="post-attributes-label-wrapper">
				<strong> Expires in </strong>
			</p>
			<input style="min-width: 100%;" type="number" id="license-expires-in" name="license-expires-in" class="newtag form-input-tip ui-autocomplete-input" value="<?php echo $license_expires_in; ?>" />
            <span class="description">Enter the number of days before a license expires, or leave blank.</span>
        </div>
        
        <?php
    }
    
    // Save custom meta box data
    public function save_custom_product_meta_box($post_id) {
        
        if (isset($_POST['license-type'])) {
            update_post_meta($post_id, '_spacetree-license-type', sanitize_text_field($_POST['license-type']));
        }
        if (isset($_POST['license-items'])) {
            update_post_meta($post_id, '_spacetree-license-items', sanitize_text_field($_POST['license-items']));
        }

        if (isset($_POST['license-expires-in'])) {
            update_post_meta($post_id, '_spacetree-license-expires-in', sanitize_text_field($_POST['license-expires-in']));
        }

    }

    
    public function add_custom_order_column($columns) {
        // Insert a new column after the 'order_total' column
        $new_columns = [];
        foreach ($columns as $column_key => $column_label) {
            $new_columns[$column_key] = $column_label;
            echo $column_key;
            if ('order_total' === $column_key) {
                $new_columns['rest_order_status'] = __('Rest Order', 'sp_proqyz');
                
            }
        }
        return $new_columns;
    }

    
    public function show_custom_order_column_content($column, $order) {
    
        if ('rest_order_status' === $column ) {
            // Retrieve the order ID from the $order object
            $order_id = $order->get_id();
            
            // Get the user ID who placed the order
            $user_id = $order->get_user_id();
    
            // Retrieve the custom flag from order meta
            $custom_flag = get_user_meta($user_id, '_spacetree_licence_order-status-' . $order_id, true);
    
            // Display the flag or a default message if it doesn't exist
            if( $custom_flag === "failed" ) {
                echo '<mark class="order-status status-failed tips"><span>Failed</span></mark>';
            } else if( $custom_flag === "completed" ) {
                echo '<mark class="order-status status-processing tips"><span>Completed</span></mark>';
            } else if( $custom_flag === "suspended" ) {
                echo '<mark class="order-status status-on-hold tips"><span>Suspended</span></mark>';
            } else {
                echo $custom_flag ? esc_html($custom_flag) : __('', 'sp_proqyz');
            }
        }
    }

    /**
     * metabox
     * woo
     */
    public function add_custom_order_license_field( $order ) {
        // Retrieve the existing license setting, if any
        $order_id = $order->get_id();
        // Get the user ID who placed the order
        $user_id = $order->get_user_id();
    
        foreach ($order->get_items() as $item) {
            $product_id = $item->get_product_id();
            $product = wc_get_product($product_id);

            if ( $product ) {
                $license_type = get_post_meta($product_id, '_spacetree-license-type', true);
                // Retrieve the custom flag from order meta
                if ($license_type === "proqyz-wp") {
                    $custom_flag = get_user_meta($user_id, '_spacetree_licence_order-status-' . $order_id, true);
                    ?>
                    <div class="form-field form-field-wide">
                        <label for="customer_user">
                            Rest Order status:
                        </label>
                        <div class="" style="display: flex;align-items: center;justify-content: space-between;">
                            <select class="wc_order-rest-order-status-input">
                                <option value=''> -Change order status- </option>
                                <option value="completed" <?php echo $custom_flag == 'completed'? 'selected' : ''; ?>> Completed </option>
                                <option value="suspended" <?php echo $custom_flag == 'suspended'? 'selected' : ''; ?>> Suspended </option>
                                <option value="removed" <?php echo $custom_flag == 'removed'? 'selected' : ''; ?>> Removed </option>
                                <option value="failed" <?php echo $custom_flag == 'failed'? 'selected' : ''; ?>> Failed </option>
                            </select>
                            <input type="hidden" class="wc_order-rest-order-id-input" value="<?php echo $order_id; ?>">
                            <button type="button" class="button button-primary wc_order-rest-order-status-btn">Update Status</button>
                        </div>
                    </div>
                    <?php 

                }
            }
        }
    
    }


}

return ST_WC_Post_Integration::instance();