<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://wpconfiguratorbuilder.com/
 * @since      1.0.0
 *
 * @package    wcb-configurator-builder
 * @subpackage wcb-configurator-builder/includes
 */

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

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    wcb-configurator-builder
 * @subpackage wcb-configurator-builder/admin
 * @author     WPCB <support@wpconfiguratorbuilder.com>
 */

class WPCB_Fields {

	/**
	 * Constructor.
	 */
	public function __construct() {

		add_action( 'carbon_fields_register_fields', array( $this, 'load_datastore' ), 5 );

		if ( defined( 'DOING_AJAX' ) ) {
			return;
		}
		// if ( ! wpcb_load_fields() ) {
		// 	return;
		// }

		add_action( 'after_setup_theme', array( $this, 'load_fields' ) );

		// add_filter( 'carbon_fields_before_field_save', function ( Carbon_Fields\Field\Field $field ) {
		// 	// Only target gallery fields
		// 	if ( $field->get_type() !== 'media_gallery' ) {
		// 		return $field;
		// 	}
		// 	$value = $field->get_value();
		// 	if ( empty( $value ) || ! is_array( $value ) ) {
		// 		return $field;
		// 	}
		// 	// Remove attachment IDs that no longer exist
		// 	$clean_value = array_values( array_filter( $value, function ( $attachment_id ) {
		// 		return get_post( $attachment_id ) !== null;
		// 	}));
		// 	// Only update if something changed
		// 	if ( $clean_value !== $value ) {
		// 		$field->set_value( $clean_value );
		// 		$value = $field->get_value();
		// 	}
		// 	return $field;
		// });
	}

	/**
	 * Spin up the Carbon Fields library.
	 *
	 * @since    1.0.0
	 */
	public function load_fields() {
		// load fields.
		require_once( WPCB_BASE . 'vendor/carbon-fields/vendor/autoload.php' );
		\Carbon_Fields\Carbon_Fields::boot();
	}

	/**
	 * Spin up the Carbon Fields datastore.
	 *
	 * @since    1.0.0
	 */
	public function load_datastore() {
		require_once( WPCB_BASE . 'includes/class-wpcb-datastore.php' );
	}
}
