<?php

// Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) {
	exit;
}

if ( !class_exists( 'WooProductVariationGallery' ) ) {
	return;
}

if ( ! class_exists( 'PWBE_WooProductVariationGallery' ) ) :

final class PWBE_WooProductVariationGallery {

	function __construct() {
		add_filter( 'pwbe_product_columns', array( $this, 'pwbe_product_columns' ) );
		add_filter( 'pwbe_results_product_initial', array( $this, 'pwbe_results_product_initial' ) );
		add_filter( 'pwbe_save_field_value', array( $this, 'pwbe_save_field_value' ), 10, 2 );
	}

	function pwbe_product_columns( $columns ) {
        $new_columns = array();


        $new_columns[] = array(
            'name' => 'Variation Gallery',
            'type' => 'images',
            'table' => 'meta',
            'field' => 'rtwpvg_images',
            'readonly' => 'false',
            'visibility' => 'variation',
            'sortable' => 'true',
            'views' => array( 'all', 'standard' )
        );

        if ( !empty( $new_columns ) ) {
            $start_index = 1;
            foreach ( $columns as $index => $column ) {
                // Insert the new columns after this column.
                if ( $column['field'] === '_product_image_gallery' ) {
                    $start_index = $index + 1;
                    break;
                }
            }

            array_splice( $columns, $start_index, 0, $new_columns );
        }

        return $columns;
	}

	function pwbe_results_product_initial( $pwbe_product ) {
		if ( property_exists( $pwbe_product, 'rtwpvg_images' ) ) {
			$images_array = maybe_unserialize( $pwbe_product->rtwpvg_images );
			$pwbe_product->rtwpvg_images = implode( ',', $images_array );
		}

		return $pwbe_product;
	}

    function pwbe_save_field_value( $value, $field ) {
        if ( $field['field'] == 'rtwpvg_images' ) {
            if ( !empty( $value ) ) {
				$images_array = (array) array_map( 'absint', explode( ',', $value ) );
				$value = array_values( array_unique( $images_array ) );
            } else {
                $value = PW_Bulk_Edit::NULL;
            }
        }

        return $value;
    }
}

new PWBE_WooProductVariationGallery();

endif;
