<?php

namespace Tech360;

defined( 'ABSPATH' ) or die;

class ACFields {

	private $disabled_fields = [];
	private $message;
	private $disabled_message;

	function __construct( $message = null, $disabled_message = null ) {

		if( is_string( $message ) && ! empty( $message) ) {
			$this->message = $message;
		} else {
			$this->message = __( 'This feature has some limitations in your theme.', 'tech360' );
		}

		if( is_string( $disabled_message ) && ! empty( $disabled_message ) ) {
			$this->disabled_message = $disabled_message;
		} else {
			$this->disabled_message = __( 'This field has been disabled in your theme. Contact <a href="https://www.tech360group.com/" target="_blank">Tech360</a> to purchase an upgraded plan.', 'tech360' );
		}

	}

	/**
	 * Add field to be disabled
	 * @param array			$field
	 */

	function add( $field ) {

		if( ! is_array( $field ) ) {
			return;
		}

		if( ! array_key_exists( 'name', $field ) ) {
			return;
		}

		$field_name = $field[ 'name' ];

		$this->disabled_fields[ $field_name ] = [];

		if( array_key_exists( 'choices', $field ) ) {
			$this->disabled_fields[ $field_name ][ 'choices' ] = $field[ 'choices' ];
		}

		if( array_key_exists( 'readonly', $field ) ) {
			$this->disabled_fields[ $field_name ][ 'readonly' ] = $field[ 'readonly' ];
		}

		if( array_key_exists( 'disabled', $field ) ) {
			$this->disabled_fields[ $field_name ][ 'disabled' ] = $field[ 'disabled' ];
		}

	}

	/**
	 * Disable field
	 * @param array			$field
	 */
	function _disable_field( $field ) {

		$field_name = $field[ 'name' ];

		if( empty( $this->disabled_fields ) ) {
			return $field;
		}

		if( ! array_key_exists( $field_name, $this->disabled_fields ) ) {
			return $field;
		}

		if( is_array( $this->disabled_fields[ $field_name ] ) && ! empty( $this->disabled_fields[ $field_name ] ) ) {
			foreach( $this->disabled_fields[ $field_name ] as $key => $settings ) {
				if( 'disabled' != $key ) {
					$field[ $key ] = $settings;
				} else {
					if( $settings == true ) {
						$field[ 'type' ] = 'message';
						$field[ 'value' ] = false;
						$field[ 'message' ] = sprintf( '<p>%s</p>', $this->disabled_message );
					}
				}
			}
		}



		$field[ 'instructions' ] .= '<p style="color: #c75a5a"><em>' . $this->message . '</em></p>';

		return $field;

	}

	/**
	 * Disable fields
	 */
	function disable() {

		foreach( array_keys( $this->disabled_fields ) as $field ) {
			add_action( 'acf/load_field/name=' . $field, [ $this, '_disable_field' ] );
		}

	}

	/**
	 * Hide ACF from admin menu
	 */
	function hide_acf() {
		add_filter( 'acf/settings/show_admin', '__return_false' );
	}

}
