<?php
/**
 * Column class for FlexStock.
 *
 * @package StockSyncWithGoogleSheetForWooCommerce
 * @since 1.0.0
 */

// Namespace.
namespace StockSyncWithGoogleSheetForWooCommerce;

// Exit if accessed directly.
defined('ABSPATH') || exit;

if ( ! class_exists('\StockSyncWithGoogleSheetForWooCommerce\Column') ) {

	/**
	 * Column class for FlexStock.
	 *
	 * @package StockSyncWithGoogleSheetForWooCommerce
	 * @since 1.0.0
	 */
	class Column extends Base {
		/**
		 * Get all columns.
		 *
		 * @return array
		 */
		public function get_all_columns() {
			$columns = [
				'ID'             => [
					'label' => 'ID',
					'type'  => 'field',
					'priority' => 1,
				],
				'product_type'   => [
					'label' => 'Type',
					'type'  => 'term',
					'priority' => 2,
				],
				'post_title'     => [
					'label' => 'Name',
					'type'  => 'field',
					'priority' => 3,
				],
				'_stock'         => [
					'label' => 'Stock',
					'type'  => 'meta',
					'priority' => 4,
				],
				'_stock_status'  => [
					'label'  => 'Stock Status',
					'column' => false,
					'type'   => 'meta',
					'priority' => 5,
				],
				'_regular_price' => [
					'label'  => 'Regular price',
					'update' => true,
					'type'   => 'meta',
					'priority' => 6,
				],
				'_sale_price'    => [
					'label' => 'Sale price',
					'type'  => 'meta',
					'priority' => 7,
				],
				'product_image' => [
					'label' => 'Image',
					'type'  => 'meta',
					'priority' => 8,
				],
				'post_status' => [
					'label' => 'Status',
					'type'  => 'field',
					'priority' => 9999,
				],
			];
			$custom_meta_value = $this->custom_meta_fields();

			if ( ! empty( $custom_meta_value ) ) {
				$columns = $columns + $custom_meta_value;
			}

			$attribute_columns = $this->attribute_columns();
			if ( ! empty( $attribute_columns ) ) {
				$columns = $columns + $attribute_columns;
			}
		

			return apply_filters('ssgsw_columns', $columns);
		}

		/**
		 * Get separate attribute columns
		 *
		 * @return array
		 */
		public function attribute_columns() {
			$separate_attributes = true === wp_validate_boolean( ssgsw_get_option('separate_attributes', false) );
			$show_attributes     = true === wp_validate_boolean( ssgsw_get_option('show_attributes', false) );
			
			if ( ! $separate_attributes || ! $show_attributes || ! ssgsw_is_license_valid() ) {
				return [];
			}

			$all_attributes = ssgsw_get_all_attributes();
			$allowed_attributes = ssgsw_get_option('allowed_attributes', null);
			$skipped_attributes = ssgsw_get_option('skipped_attributes', []);

			if ( ! is_array( $skipped_attributes ) ) {
				$skipped_attributes = [];
			}

			$columns = [];
			
			// New Logic: Check allowed_attributes first (Opt-in)
			if ( $allowed_attributes !== null ) {
				if ( ! is_array( $allowed_attributes ) ) {
					$allowed_attributes = [];
				}
				foreach ( $all_attributes as $attr ) {
					if ( in_array( $attr['slug'], $allowed_attributes ) ) {
						$columns[ 'attribute_' . $attr['slug'] ] = [
							'label'    => $attr['label'],
							'type'     => 'meta',
							'priority' => 10, // Adjust priority as needed
						];
					}
				}
			} else {
				// Old Logic: Fallback to skipped_attributes (Opt-out)
				foreach ( $all_attributes as $attr ) {
					if ( in_array( $attr['slug'], $skipped_attributes ) ) {
						continue;
					}

					$columns[ 'attribute_' . $attr['slug'] ] = [
						'label'    => $attr['label'],
						'type'     => 'meta',
						'priority' => 10, // Adjust priority as needed
					];
				}
			}

			return $columns;
		}

		/**
		 * Format custom meta data
		 *
		 * @return array
		 */
		public function custom_meta_fields() {
			$custom_array = [];
			return apply_filters('ssgsw_add_custom_meta_fileds', $custom_array);
		}

		/**
		 * Get Editable Columns.
		 *
		 * @return array
		 */
		public function get_columns() {
			$columns = $this->get_all_columns();
		
			$show_short_description = true === wp_validate_boolean( ssgsw_get_option('show_short_description', false) );
			$show_product_category  = true === wp_validate_boolean( ssgsw_get_option('show_product_category', false) );
			$show_total_sales       = true === wp_validate_boolean( ssgsw_get_option('show_total_sales', false) );
			$show_sku               = true === wp_validate_boolean( ssgsw_get_option('show_sku', false) );
			$show_attributes        = true === wp_validate_boolean( ssgsw_get_option('show_attributes', false) );
			$show_product_images    = true === wp_validate_boolean( ssgsw_get_option('show_product_images', false) );
			$product_url            = true === wp_validate_boolean( ssgsw_get_option('show_product_url', false) );
			$long_description       = true === wp_validate_boolean( ssgsw_get_option('show_long_description', false) );
			$post_status            = true === wp_validate_boolean( ssgsw_get_option('show_product_status', false) );
			$product_tag       		= true === wp_validate_boolean( ssgsw_get_option('show_product_tags', false) );
			$shop_name_sync       		= true === wp_validate_boolean( ssgsw_get_option('shop_name_sync', false) );
			$show_product_image_alt = true === wp_validate_boolean( ssgsw_get_option('show_product_image_alt', false) );
			$show_upsell_ids        = true === wp_validate_boolean( ssgsw_get_option('show_upsell_ids', false) );
			$show_crosssell_ids     = true === wp_validate_boolean( ssgsw_get_option('show_crosssell_ids', false) );
			$show_custom_badge      = true === wp_validate_boolean( ssgsw_get_option('show_custom_badge', false) );
			$show_product_brand     = true === wp_validate_boolean( ssgsw_get_option('show_product_brand', false) );
			if ( ! $shop_name_sync || ! ssgsw_is_license_valid() ) {
				unset($columns['post_author']);
			}
			if ( ! $product_tag || ! ssgsw_is_license_valid() ) {
				unset($columns['product_tag']);
			}
			if ( ! $show_short_description || ! ssgsw_is_license_valid() ) {
				unset($columns['post_excerpt']);
			}
			if ( ! $product_url || ! ssgsw_is_license_valid()) {
				unset($columns['ssgsw_product_url'] );
			}
			if ( ! $long_description || ! ssgsw_is_license_valid() ) {
				unset($columns['post_content']);
			}
			if ( ! $show_product_category || ! ssgsw_is_license_valid()) {
				unset($columns['product_cat']);
			}
			if ( ! $show_product_images || ! ssgsw_is_license_valid() ) {
				unset($columns['product_image']);
			}
			if ( ! $post_status || ! ssgsw_is_license_valid() ) {
				unset($columns['post_status']);
			}
			if ( ! $show_total_sales || ! ssgsw_is_license_valid()) {
				unset($columns['total_sales']);
			}
			if ( ! $show_sku || ! ssgsw_is_license_valid()) {
				unset($columns['_sku']);
			}
			
			if ( ! $show_product_brand || ! ssgsw_is_license_valid() ) {
				unset($columns['product_brand']);
			}

			if ( ! $show_attributes || ! ssgsw_is_license_valid()) {
				unset($columns['_product_attributes']);
			}

			if ( ! $show_product_image_alt || ! ssgsw_is_license_valid() ) {
				unset($columns['product_image_alt']);
			}

			if ( ! $show_upsell_ids || ! ssgsw_is_license_valid() ) {
				unset($columns['Upsell_IDS']);
			}

			if ( ! $show_crosssell_ids || ! ssgsw_is_license_valid() ) {
				unset($columns['Crosssell_IDS']);
			}

			if ( ! $show_custom_badge || ! ssgsw_is_license_valid() ) {
				unset($columns['CustomBadge']);
			}

			$separate_attributes = true === wp_validate_boolean( ssgsw_get_option('separate_attributes', false) );
			if ( $separate_attributes && $show_attributes && ssgsw_is_license_valid() ) {
				unset($columns['_product_attributes']);
			}

			// Sort columns by priority.
			uasort($columns, function ( $a, $b ) {
				return isset($a['priority']) && isset($b['priority']) ? $a['priority'] - $b['priority'] : 0;
			});

			return $columns;
		}
		/**
		 * Get Editable Column Keys.
		 *
		 * @return array
		 */
		public function get_columns_filter() {
			$columns = $this->get_columns();
			// Remove columns which are not editable.
			$columns = array_filter($columns, function ( $column ) {
				return isset($column['column']) ? $column['column'] : true;
			});
			return $columns;
		}

		/**
		 * Get Editable Column Keys.
		 *
		 * @return array
		 */
		public function get_columns_no_edit_remove() {
			if(ssgsw_check_action_api() ) {
				$columns = ssgsw_get_external_options();
			} else {
				$columns = $this->get_columns();
			}
			// Remove columns which are not editable.
			$columns = array_filter($columns, function ( $column ) {
				return isset($column['column']) ? $column['column'] : true;
			});
			return $columns;
		}
		/**
		 * Get Editable Column Keys.
		 *
		 * @return array
		 */
		public function get_column_keys() {
			if(ssgsw_check_action_api() ) {
				$columns = ssgsw_get_external_options();
			} else {
				$columns = $this->get_columns();
			}
			// Remove columns which are not editable.
			$columns = array_filter($columns, function ( $column ) {
				return isset($column['column']) ? $column['column'] : true;
			});
		

			$keys = array_keys($columns);

			return $keys;
		}

		/**
		 * Get Editable Column Values.
		 *
		 * @return array
		 */
		public function get_column_names() {
			if(ssgsw_check_action_api() ) {
				$columns_data = ssgsw_get_external_options();
			} else {
				$columns_data = $this->get_columns();
			}
			$columns = array_filter($columns_data, function ( $column ) {
				return isset($column['column']) ? $column['column'] : true;
			});

			$values = array_column(array_values($columns), 'label');

			return $values;
		}

		/**
		 * Get column keys for query.
		 *
		 * @return array
		 */
		public function get_queryable_columns() {
			if(ssgsw_check_action_api() ) {
				$columns = ssgsw_get_external_options();
			} else {
				$columns = $this->get_columns();
			}

			$columns = array_filter($columns, function ( $column ) {
				return isset($column['query']) ? $column['query'] : true;
			});

			return $columns;
		}

		/**
		 * Get column keys for query.
		 *
		 * @return array
		 */
		public function get_queryable_column_keys() {
			$columns = $this->get_queryable_columns();

			$keys = array_keys($columns);

			return $keys;
		}


		/**
		 * Get queryable fields.
		 *
		 * @return array
		 */
		public function get_queryable_fields() {
			$columns = $this->get_queryable_columns();

			$columns = array_filter($columns, function ( $column ) {
				return 'field' === $column['type'];
			});

			return array_keys($columns);
		}

		/**
		 * Get queryable meta fields.
		 *
		 * @return array
		 */
		public function get_queryable_metas() {
			$columns = $this->get_queryable_columns();

			$columns = array_filter($columns, function ( $column ) {
				return 'meta' === $column['type'];
			});

			return apply_filters('ssgsw_queryable_metas', $columns);
		}

		/**
		 * Get queryable term fields.
		 *
		 * @return array
		 */
		public function get_queryable_taxonomies() {
			$columns = $this->get_queryable_columns();

			$columns = array_filter($columns, function ( $column ) {
				return 'term' === $column['type'];
			});

			return array_keys($columns);
		}

		/**
		 * Get queryable relation fields.
		 *
		 * @return array
		 */
		public function get_queryable_relations() {
			$columns = $this->get_queryable_columns();

			$columns = array_filter($columns, function ( $column ) {
				return 'relation' === $column['type'];
			});

			return array_keys($columns);
		}

		/**
		 * Get queryable attribute fields.
		 *
		 * @return array
		 */
		public function get_queryable_attributes() {
			$columns = $this->get_queryable_columns();

			$columns = array_filter($columns, function ( $column ) {
				return 'attribute' === $column['type'];
			});

			return $columns;
		}

		/**
		 * Init Getter and Setter Hooks.
		 *
		 * @param mixed $stock_id Stock ID.
		 * @param bool  $reverse Reverse.
		 * @return mixed
		 */
		public function get_stock_status( $stock_id = 'instock', $reverse = false ) {
			if ( is_numeric( $stock_id ) ) {
				return absint( $stock_id );
			}

			if ( $reverse ) {
				$stock_id = strtolower($stock_id);
				return str_replace(' ', '', $stock_id);
			}

			$stocks = [
				'instock'     => 'In Stock',
				'outofstock'  => 'Out of Stock',
				'onbackorder' => 'On Backorder',
			];

			return isset( $stocks[ $stock_id ] ) ? $stocks[ $stock_id ] : $stock_id;
		}
		/**
		 * Init Getter and Setter Hooks.
		 *
		 * @param mixed $stock_id Stock ID.
		 * @param bool  $reverse Reverse.
		 * @return mixed
		 */
		public function get_stock_status_update( $stock_id = 'instock', $reverse = false ) {
			$stocks = [
				'instock'     => 'instock',
				'outofstock'  => 'outofstock',
				'onbackorder' => 'onbackorder',
			];
			return in_array( $stock_id, $stocks ) ? $stocks[ $stock_id ] : 'instock';
		}

		/**
		 * Returns first term.
		 *
		 * @param string $categories Categories.
		 * @return string
		 */
		public function get_first_term( $categories = '0' ) {
			if ($categories !== null) {//phpcs:ignore
				$categories     = explode(',', $categories);
				$first_category = explode(':', $categories[0]);

				return isset( $first_category[1] ) ? $first_category[1] : '';
			}
			return '';
		}

		/**
		 * Get items by comma separated values.
		 *
		 * @param string $categories Categories.
		 * @return string
		 */
		public function get_items_by_comma( $categories = 0 ) {
			if ($categories !== null) {//phpcs:ignore
				$categories = explode(',', $categories);

				$items = [];
				foreach ( $categories as $category ) {
					$category = explode(':', $category);
					$items[]  = isset( $category[1] ) ? $category[1] : '';
				}
				return implode(', ', $items);
			} else {
				return '';
			}
		}

		/**
		 * Get Product Type.
		 *
		 * @param string $product_type Product Type.
		 * @return mixed
		 */
		public function get_product_type( $product_type = 'simple' ) {
			$product_type = $this->get_first_term($product_type);

			$types = [
				'simple'   => 'Simple',
				'variable' => 'Variable',
				'grouped'  => 'Grouped',
				'external' => 'External',
			];

			return array_key_exists($product_type, $types) ? $types[ $product_type ] : ( empty($product_type) ? 'Variation' : $product_type );
		}
	}
}
