<?php

if ( ! class_exists( 'GFForms' ) ) {
	die();
}

class Wiaas_Order_Fields {

	public static function init() {

		add_action( 'gform_field_standard_settings', array( __CLASS__, 'field_settings' ) );

		add_filter('gform_fileupload_entry_value_file_path', array( __CLASS__, 'display_order_document_fields' ), 999, 2);

		add_action('gform_post_update_entry', array(__CLASS__, 'maybe_map_entry_to_order'), 10, 2);

		add_action('gform_after_update_entry', array(__CLASS__, 'maybe_apply_user_input_changes'), 10, 3);
	}

	/**
     * Workflow user input are handled separately in gravity flow. We get them here
     * and then try to apply changes to order
     *
	 * @param $form
	 * @param $entry_id
	 * @param $original_entry
	 */
	public static function maybe_apply_user_input_changes($form, $entry_id, $original_entry) {

	    $entry = GFAPI::get_entry($entry_id);

	    self::maybe_map_entry_to_order($entry, $original_entry);
    }


	/**
     * Persist workflow entry change to order
     *
	 * @param $entry
	 * @param $old_entry
	 */
	public static function maybe_map_entry_to_order($entry, $old_entry) {

	    $form = GFAPI::get_form($old_entry['form_id']);

	    $order_field = GFCommon::get_fields_by_type($form, 'wiaas_order')[0];

	    if (empty($order_field)) {

	        return;
        }

	    $order_id = $entry[$order_field->id];

	    // get order process entry
	    $order = wc_get_order($order_id);
	    $process_entry = Wiaas_Delivery_Process::get_order_delivery_process_entry($order_id);

	    if ( !$order || empty($process_entry) ) {

	        return;
        }

        // apply entry changes to order properties
        foreach ($form['fields'] as $field) {

	        $old_value = $old_entry[$field->id];
	        $new_value = $entry[$field->id];

	        // check if field changed
            if ($old_value ===  $new_value || empty($new_value)) {

                continue;
            }

            // save changes to order
	        switch ($field->type) {

                case 'wiaas_order_bundle_installation_date':
	                /**
	                 * Persist bundle installation date
	                 */

	                // get corresponding bundle field
	                $bundle_field = GFCommon::get_fields_by_type( $form, 'wiaas_order_bundle' )[0];

	                if (empty($bundle_field)) {

		                continue;
	                }

	                $bundle_item = $bundle_field->get_bundle_item( $entry[$bundle_field->id] );

	                if (empty($bundle_item)) {

		                continue;
	                }

	                $bundle_item->update_meta_data('_wiaas_installation_date', $new_value);
	                $bundle_item->save_meta_data();

                    break;

                case 'wiaas_order_bundle_document':
	                /**
	                 * Persist delivery flow documents for bundle
	                 */

                    // get corresponding bundle field
                    $bundle_field = GFCommon::get_fields_by_type( $form, 'wiaas_order_bundle' )[0];

                    if (empty($bundle_field)) {

                        continue;
                    }

                    $bundle_item = $bundle_field->get_bundle_item( $entry[$bundle_field->id] );

                    if (empty($bundle_item)) {

                        continue;
                    }

                    $bundle_documents = $bundle_item->get_meta('_wiaas_documents', true);
	                if (empty($bundle_documents)) {
		                $bundle_documents = array();
	                }

	                $new_documents = $field->multipleFiles ? json_decode( $new_value ) : array( $new_value );
	                if (! empty($old_value) ) {

		                $old_documents = $field->multipleFiles ? json_decode( $old_value ) : array( $old_value );
		                $added_documents = array_diff($new_documents, $old_documents);
	                } else {

		                $added_documents = $new_documents;
	                }


	                foreach ($added_documents as $added_document) {
		                $info = pathinfo( $added_document );

		                $dir = wp_upload_dir();
		                $relative_file_path = str_replace($dir['baseurl'] . '/', '', $added_document);

		                $bundle_documents[] = array(
			                'key' => wp_generate_uuid4(),
			                'name' => $info['filename'],
			                'extension' => $info['extension'],
			                'version' => $relative_file_path,
			                'url'  => $field->get_download_url( $added_document, true ),
			                'type' => $field->wiaasDocTypeFilter
		                );
	                }

	                $bundle_item->update_meta_data('_wiaas_documents', $bundle_documents);
	                $bundle_item->save_meta_data();

                    break;

                case 'wiaas_order_document':
	                /**
	                 * Persist delivery flow documents for order
	                 */
                    $new_documents = $field->multipleFiles ? json_decode( $new_value ) : array( $new_value );

                    if (! empty($old_value) ) {

	                    $old_documents = $field->multipleFiles ? json_decode( $old_value ) : array( $old_value );
	                    $added_documents = array_diff($new_documents, $old_documents);
                    } else {

                        $added_documents = $new_documents;
                    }

                    $order_documents = $order->get_meta('_wiaas_other_documents', true);
                    if (empty($order_documents)) {
                        $order_documents = array();
                    }

                    foreach ($added_documents as $added_document) {
	                    $info = pathinfo( $added_document );

	                    $dir = wp_upload_dir();
	                    $relative_file_path = str_replace($dir['baseurl'] . '/', '', $added_document);

	                    $order_documents[] = array(
		                    'key' => wp_generate_uuid4(),
		                    'name' => $info['filename'],
		                    'extension' => $info['extension'],
		                    'version' => $relative_file_path,
		                    'url'  => $field->get_download_url( $added_document, true ),
                            'type' => $field->wiaasDocTypeFilter
                        );
                    }

	                $order->update_meta_data('_wiaas_other_documents', $order_documents);
                    $order->save_meta_data();

                    break;

                case 'wiaas_order_installation_select':
	                /**
	                 * Persist installation for bundle
	                 */

	                $selected_installation = $field->get_selected_installation($new_value);

	                if ( empty($selected_installation) ) {
	                    // no installation selected
		                continue;
                    }

	                // get corresponding bundle field
	                $bundle_field = GFCommon::get_fields_by_type( $form, 'wiaas_order_bundle' )[0];

	                if (empty($bundle_field)) {

		                continue;
	                }

	                $bundle_item = $bundle_field->get_bundle_item( $entry[$bundle_field->id] );

	                if (empty($bundle_item)) {

		                continue;
	                }

	                $bundle_item->update_meta_data('_wiaas_installation', $selected_installation->get_id());
	                $bundle_item->save_meta_data();

	                /**
	                 * Apply actions related to order item installation
	                 * (ex. make order visible to corresponding installation company)
	                 */
	                do_action('wiaas_order_item_installation_assigned', $order, $bundle_item, $selected_installation);
            }
        }
    }

	/**
	 * Adds the Order Fields group to the form editor.
	 *
	 * @param array $field_groups The properties for the field groups.
	 *
	 * @return array
	 */
	public static function maybe_add_order_field_group( $field_groups ) {
		foreach ( $field_groups as $field_group ) {
			if ( $field_group['name'] == 'wiaas_order_fields' ) {
				return $field_groups;
			}
		}

		$field_groups[] = array(
			'name'   => 'wiaas_order_fields',
			'label'  => __( 'Order Fields', 'wiaas' ),
			'fields' => array()
		);

		return $field_groups;
	}


	public static function display_order_document_fields($file_path, $field) {

	    if (strpos($file_path, 'gf-download') === false &&
            strpos($file_path, 'gf-wiaas-order-doc') === false) {

		    $field = new Wiaas_Field_Order_Bundle_Document();

		    return $field->get_download_url($file_path);
        }

        return $file_path;
	}

	/**
     * Add custom settings for form order fields
     *
	 * @param int $position
	 */
	public static function field_settings( $position ) {
		if ( $position === 20 ) {
			// After Field description setting.
			?>

			<li class="wiaas_doc_type_filter field_setting">

				<label for="wiaas-doc-type-filter" class="section_label">
					<?php esc_html_e( 'Document Type', 'wiaas' ); ?>
				</label>
				<select id="wiaas-doc-type-filter" onchange="SetFieldProperty('wiaasDocTypeFilter',this.value);">
					<option value="configuration"><?php esc_html_e( 'Configuration', 'wiaas' ); ?></option>
					<option value="order_questionaire"><?php esc_html_e( 'Order Questionaire', 'wiaas' ); ?></option>
					<option value="installation_protocol"><?php esc_html_e( 'Installation protocol', 'wiaas' ); ?></option>
                    <option value="install_guide"><?php esc_html_e( 'Installation Guide', 'wiaas' ); ?></option>
					<option value="customer_acceptance"><?php esc_html_e( 'Customer acceptance', 'wiaas' ); ?></option>
				</select>

			</li>

            <li class="wiaas_installation_organization_filter field_setting">
                <input type="checkbox" id="wiaas-installation-organization-filter"
                       onclick="var value = jQuery(this).is(':checked'); SetFieldProperty('wiaasOnlyInstallationOrg', value);""/>
                <label for="wiaas-installation-organization-filter" class="inline">
	                <?php esc_html_e( 'Only installation', 'wiaas' ); ?>
                </label>
            </li>

			<?php
		}
	}


	/**
     * Create new entry for order delivery process action form
     *
	 * @param int $order_id
	 * @param array $form
	 * @param int|null $bundle_item_id
	 *
	 * @return array|bool
	 */
	public static function map_order_to_entry($order_id, $form, $bundle_item_id = null) {

	    if (empty($form['fields']) ||
            empty(GFCommon::get_fields_by_type( $form, array('wiaas_order')) ) ) {
	        // form does not have order field so cannot be mapped
	        return false;
        }

		$order = wc_get_order($order_id);

        $entry = array();

	    foreach ($form['fields'] as $field) {

            switch ($field->type) {

                case 'wiaas_order':

                    $entry[(string) $field->id] = $order->get_id();

                    break;

                case 'workflow_user':
	                $entry[(string) $field->id] = $order->get_customer_id(); // save customer if needed

	                break;

                case 'wiaas_order_bundle':

	                $bundle_item = $order->get_item($bundle_item_id);

                    if ( empty($bundle_item) && $field->isRequired) {
	                    // there is no data for required field so entry cannot be created
	                    return false;
                    }

                    if (! empty($bundle_item)) {

	                    $entry[(string) $field->id] = $order->get_id() . '|' . $bundle_item->get_id();
                    }

	                break;

                case 'wiaas_order_bundle_document':

	                $bundle_item = $order->get_item($bundle_item_id);

	                if ( empty($bundle_item) && $field->isRequired) {
		                // there is no data for required field so entry cannot be created
		                return false;
	                }

	                if (! empty($bundle_item)) {

		                $documents = wiaas_get_standard_package_order_item_documents($order, $bundle_item_id);

		                $filtered_documents = array();

		                foreach ($documents as $document) {

		                    if ($document['type'] === $field->wiaasDocTypeFilter) {

		                        $filtered_documents[] = $document;
                            }
                        }

		                if ( empty($filtered_documents) && $field->isRequired ) {
			                // there is no data for required field so entry cannot be created
			                return false;
		                }

		                if (! empty ($filtered_documents) && ! $field->multipleFiles) {

			                $document = $filtered_documents[0];

			                $entry[$field->id] = $document['version'];

                        } else if (! empty ($filtered_documents) ) {

		                    $versions = array();
		                    foreach ($filtered_documents as $filtered_document) {
		                        $versions[] = $filtered_document['version'];
                            }

			                $entry[$field->id] = json_encode($versions);
                        }
                    }

	                break;

	            case 'wiaas_order_installation_select':

		            $bundle_item = $order->get_item($bundle_item_id);

		            if ( empty($bundle_item) && $field->isRequired) {
			            // there is no data for required field so entry cannot be created
			            return false;
		            }

		            // installation is already selected
		            if (!empty($bundle_item->get_meta('_wiaas_installation', true))) {

			            $entry[(string) $field->id] = 'wiaas_installation_' . $order->get_id() . '|' . $bundle_item->get_meta('_wiaas_installation', true);

			            continue;
                    }

		            $bundled_items = wc_pb_get_bundled_order_items($bundle_item, $order);

		            $installation_items = array();

		            foreach ($bundled_items as $id => $bundled_item) {

		                $product = $bundled_item->get_product();

		                if ($product && Wiaas_Product_Category::is_installation($product)) {

		                    $installation_items[] = $bundled_item;
                        }
                    }

                    if (empty($installation_items)) {
	                    // there is no data for required field so entry cannot be created
		                return false;
                    }

                    if (count($installation_items) === 1) {

		                $installation_item = $installation_items[0];

	                    $entry[(string) $field->id] = 'wiaas_installation_' . $order->get_id() . '|' . $installation_item->get_id();

	                    /**
	                     * Apply actions related to order item installation
                         * (ex. make order visible to corresponding installation company)
	                     */
	                    do_action('wiaas_order_item_installation_assigned', $order, $bundle_item, $installation_item);

                    } else if (count($installation_items) > 1) {

		                // force admin to select installation
	                    $entry[(string) $field->id] = '0';
                    }

            }
        }

        return $entry;
    }

}

Wiaas_Order_Fields::init();
