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

if ( ! class_exists( 'SBUY_Metabox' ) ) {
    /**
     * Metabox Class.
     *
     * @since 1.0.0
     */
    class SBUY_Metabox {

        /**
         * Constructor
         *
         * @since 1.0.0
         */
        public function __construct() {
            add_action( 'add_meta_boxes', array( $this, 'add_meta_box' ) );
            add_action( 'save_post', array( $this, 'save' ), 10, 2 );

            self::add_admin_column( esc_html__( 'SKU', 'simply-buy' ), 'sbuy_product', function ( $post_id ) {
                $simplybuy = json_decode( get_post_meta( $post_id, '_simplybuy', true ) );
                echo isset( $simplybuy->sku ) ? esc_html( $simplybuy->sku ) : '';
            }, 'date', 'simplybuy_sku', true );
            self::add_admin_column( esc_html__( 'Price', 'simply-buy' ), 'sbuy_product', function ( $post_id ) {
                $simplybuy = json_decode( get_post_meta( $post_id, '_simplybuy', true ) );
                echo isset( $simplybuy->price ) ? esc_html( $simplybuy->price ) . '&nbsp;' . esc_html( SBUY_CORE_CURRENCY_SYMBOL ) : '--';
            }, 'date', 'simplybuy_price', true );
        }

        /**
         * Adds the meta-box container.
         *
         * @param string $post_type name of the post.
         *
         * @since 1.0.0
         */
        public function add_meta_box( $post_type ) {
            $post_types = array( 'sbuy_product' );

            if ( in_array( $post_type, $post_types, true ) ) {
                add_meta_box( 'simplybuy_meta_box', esc_html__( 'SimplyBuy', 'simply-buy' ), array(
                        $this,
                        'render_meta_box_content'
                ), $post_type, 'advanced', 'high' );
            }
        }

        /**
         * Save the meta when the post is saved.
         *
         * @param int $post_id The ID of the post being saved.
         * @param WP_Post $post The post-object.
         *
         * @since 1.0.0
         */
        public function save( int $post_id, $post ) {

            // Check nonce.
            if ( ! isset( $_POST['_simplybuy_inner_custom_box_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_simplybuy_inner_custom_box_nonce'] ) ), 'simplybuy_nonce' ) ) {
                return $post_id;
            }

            if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
                return $post_id;
            }

            // Check the user's permissions.
            $post_type = get_post_type_object( $post->post_type );

            if ( ! current_user_can( $post_type->cap->edit_post, $post_id ) ) {
                return $post_id;
            }

            /* OK, it's safe for us to save the data now. */
            $simplybuy_data = array();

            $simplybuy_data['price'] = isset( $_POST['simplybuy_price'] ) ? sanitize_text_field( wp_unslash( $_POST['simplybuy_price'] ) ) : '';
            $simplybuy_data['sku']   = isset( $_POST['simplybuy_sku'] ) ? sanitize_text_field( wp_unslash( $_POST['simplybuy_sku'] ) ) : '';

            update_post_meta( $post_id, '_simplybuy', wp_json_encode( $simplybuy_data ) );
        }

        /**
         * Render Meta Box content.
         *
         * @param WP_Post $post The post-object.
         *
         * @since 1.0.0
         */
        public function render_meta_box_content( WP_Post $post ): void {

            wp_nonce_field( 'simplybuy_nonce', '_simplybuy_inner_custom_box_nonce' );

            $simplybuy = json_decode( get_post_meta( $post->ID, '_simplybuy', true ) );
            $price     = isset( $simplybuy->price ) ? esc_html( $simplybuy->price ) : '';
            $sku       = isset( $simplybuy->sku ) ? esc_html( $simplybuy->sku ) : '';

            ?>

            <p style="padding: 5px 20px 5px 162px; margin: 9px 0;">
                <label for="simplybuy_sku"
                       style="float: left; width: 150px; padding: 0; margin: 0 0 0 -150px;"><?php echo esc_html__( 'SKU', 'simply-buy' ); ?></label>
                <input type="text" id="simplybuy_sku" name="simplybuy_sku" value="<?php echo esc_attr( $sku ); ?>" size="25"/>
            </p>
            <p style="padding: 5px 20px 5px  162px; margin: 9px 0;">
                <label for="simplybuy_sku"
                       style="float: left; width: 150px; padding: 0; margin: 0 0 0 -150px;"><?php echo esc_html__( 'Price', 'simply-buy' ) . '&nbsp;(' . esc_html( SBUY_CORE_CURRENCY_SYMBOL ) . ')'; ?></label>
                <input type="text" id="simplybuy_price" name="simplybuy_price" value="<?php echo esc_attr( $price ); ?>" size="25"/>
            </p>
            <?php
        }

        public function add_admin_column( $column_title, $post_type, $value, $before_position = false, $order_by = false, $order_by_field_is_meta = false ): void {

            // Column Header
            add_filter( 'manage_' . $post_type . '_posts_columns', function ( $columns ) use ( $column_title, $before_position ) {

                // add to the end of the table.
                if ( ! $before_position ) {

                    $columns[ sanitize_title( $column_title ) ] = $column_title;

                    return $columns;

                }

                $pos = $before_position;

                // get the position if the passed value ist not an integer.
                if ( ! is_int( $pos ) ) {

                    $pos = array_search( $before_position, array_keys( $columns ) );

                    // the value for position is not valid.
                    if ( ! is_int( $pos ) || 0 == $pos ) {

                        return $columns;

                    }
                }

                // slice and merge the array.
                $columns = array_merge( array_slice( $columns, 0, $pos ), array( sanitize_title( $column_title ) => $column_title ), array_slice( $columns, $pos ) );

                return $columns;
            } );

            // Column Content.
            add_action( 'manage_' . $post_type . '_posts_custom_column', function ( $column, $post_id ) use ( $column_title, $value ) {
                if ( sanitize_title( $column_title ) === $column ) {
                    $value( $post_id );
                }
            }, 10, 2 );

            // OrderBy Set?
            if ( ! empty( $order_by ) ) {

                // Column Sorting.
                add_filter( 'manage_edit-' . $post_type . '_sortable_columns', function ( $columns ) use ( $column_title, $order_by ) {
                    $columns[ sanitize_title( $column_title ) ] = $order_by;

                    return $columns;
                } );

                // Column Ordering.
                add_action( 'pre_get_posts', function ( $query ) use ( $order_by, $order_by_field_is_meta ) {
                    if ( ! is_admin() || ! $query->is_main_query() ) {
                        return;
                    }

                    if ( sanitize_key( $order_by ) === $query->get( 'orderby' ) ) {
                        if ( $order_by_field_is_meta ) {
                            $query->set( 'orderby', 'meta_value' );
                            $query->set( 'meta_key', sanitize_key( $order_by ) );
                        } else {
                            $query->set( 'orderby', sanitize_key( $order_by ) );
                        }
                    }
                } );

            }
        }
    }
}
