<?php

require( plugin_dir_path( __FILE__ ) . 'vendor/autoload.php' );
GFForms::include_feed_addon_framework();

class WeichieGravityFormClickUpAddon extends GFFeedAddOn {

	protected $_version = WEICHIE_GRAVITYFORMS_CLICKUP_VERSION;
	protected $_min_gravityforms_version = '1.9';
	protected $_slug = 'weichie-gf-cu';
	protected $_path = 'weichie-gravityforms-clickup/weichie-gravityforms-clickup.php';
	protected $_full_path = __FILE__;
	protected $_title = 'Gravity Forms x Clickup Add-On';
	protected $_short_title = 'ClickUp';

	private static $_instance = null;

  protected $_multiple_feeds = false;

	/**
	 * Get an instance of this class.
	 *
	 * @return WeichieGravityFormClickUpAddon
	 */
	public static function get_instance() {
		if ( self::$_instance == null ) {
			self::$_instance = new WeichieGravityFormClickUpAddon();
		}

		return self::$_instance;
	}

	/**
	 * Handles hooks and loading of language files.
	 */
	public function init() {
		parent::init();

    if ( wgc_fs()->is_plan('multiplefeeds') ) {
      $this->_multiple_feeds = true;
    } else {
      $this->_multiple_feeds = false;
    }

    add_filter( 'gform_submit_button', array( $this, 'form_submit_button' ), 10, 2 );
		add_action( 'gform_after_submission', array( $this, 'after_submission' ), 10, 2 );
	}


	// # SCRIPTS & STYLES -----------------------------------------------------------------------------------------------

	/**
	 * Return the scripts which should be enqueued.
	 *
	 * @return array
	 */
	public function scripts() {
		$scripts = array(
			array(
				'handle'  => 'my_script_js',
				'src'     => $this->get_base_url() . '/js/my_script.js',
				'version' => $this->_version,
				'deps'    => array( 'jquery' ),
				'strings' => array(
					'first'  => esc_html__( 'First Choice', 'simpleaddon' ),
					'second' => esc_html__( 'Second Choice', 'simpleaddon' ),
					'third'  => esc_html__( 'Third Choice', 'simpleaddon' )
				),
				'enqueue' => array(
					array(
						'admin_page' => array( 'form_settings' ),
						'tab'        => 'weichie-gf-cu'
					)
				)
			),

		);

		return array_merge( parent::scripts(), $scripts );
	}

	/**
	 * Return the stylesheets which should be enqueued.
	 *
	 * @return array
	 */
	public function styles() {
		$styles = array(
			array(
				'handle'  => 'my_styles_css',
				'src'     => $this->get_base_url() . '/css/my_styles.css',
				'version' => $this->_version,
				'enqueue' => array(
					array( 'field_types' => array( 'poll' ) )
				)
			)
		);

		return array_merge( parent::styles(), $styles );
	}


	// # FRONTEND FUNCTIONS --------------------------------------------------------------------------------------------

	/**
	 * Add the text in the plugin settings to the bottom of the form if enabled for this form.
	 *
	 * @param string $button The string containing the input tag to be filtered.
	 * @param array $form The form currently being displayed.
	 *
	 * @return string
	 */
	function form_submit_button( $button, $form ) {
		$settings = $this->get_form_settings( $form );
		if ( isset( $settings['enabled'] ) && true == $settings['enabled'] ) {
			$text   = $this->get_plugin_setting( 'mytextbox' );
			$button = "<div>{$text}</div>" . $button;
		}

		return $button;
	}


	// # ADMIN FUNCTIONS -----------------------------------------------------------------------------------------------

	/**
	 * Configures the settings which should be rendered on the add-on settings tab.
	 *
	 * @return array
	 */
	public function plugin_settings_fields() {
		return array(
			array(
				'title'  => esc_html__( 'ClickUp API Settings', 'simpleaddon' ),
				'fields' => array(
					array(
						'name'              => 'weichie_clickup_api_key',
						//'tooltip'           => esc_html__( 'This is the tooltip', 'simpleaddon' ),
						'label'             => esc_html__( 'Enter your Personal ClickUp API', 'simpleaddon' ),
						'type'              => 'text',
						'class'             => 'small',
						//'feedback_callback' => array( $this, 'is_valid_setting' ),
					),
          array(
            'label' => __('Need multiple ClickUp feeds?', 'weichiecom-gravityforms-clickup') . ' <a href="' . wgc_fs()->get_upgrade_url() . '">' .
              __('Upgrade Now!', 'weichiecom-gravityforms-clickup') .
              '</a>',
            'type' => 'checkbox',
          ),
				)
			)
		);
	}

    /**
     * Process the feed e.g. subscribe the user to a list.
     *
     * @param array $feed The feed object to be processed.
     * @param array $entry The entry object currently being processed.
     * @param array $form The form object currently being processed.
     *
     * @return bool|void
     */
    public function process_feed( $feed, $entry, $form ) {

        $team_id = $feed['meta']['clickup_team_id'];
        $space_id  = $feed['meta']['clickup_space_id'];
        $project_id  = $feed['meta']['clickup_project_id'];
        $list_id  = $feed['meta']['clickup_list_id'];

        $member_ids = [];

        $custom_fields = $this->get_field_map_fields( $feed, 'custom_fields' );
        $_custom_fields = [];

        foreach( $custom_fields as $custom_id => $custom_field ){
            $_custom_fields[] = [
                'id' => $custom_id,
                'value' => rgar( $entry, $custom_field ),
            ];
        }

        foreach( $feed['meta'] as $key => $value ){
            if( strstr($key, 'clickup_member_ids_') && $value == 1 ){
                $member_ids[] = str_replace('clickup_member_ids_', '', $key);
            }
        }

        $settings = $this->get_plugin_settings();
        $key = rgar( $settings, 'weichie_clickup_api_key' );

        $clickup = new \ClickUp\Client($key);

        $team = $clickup->team($team_id);
        $space = $team->space($space_id);
        $project = $space->project($project_id);
        $list = $project->taskList($list_id);

        $tags = $feed['meta']['tags'];

        $taskArgs = [
            'name' => GFCommon::replace_variables( $feed['meta']['title'], $form, $entry),
            'description' => trim(strip_tags(GFCommon::replace_variables( $feed['meta']['description'], $form, $entry))),
        ];

        if( !empty($member_ids) ){
            $taskArgs['assignees'] = $member_ids;
        }

        if( !empty($_custom_fields) ){
            $taskArgs['custom_fields'] = $_custom_fields;
        }

        if( !empty($tags) ){
            $taskArgs['tags'] = array_map('trim', explode(',',$tags));
        }

        $list->createTask($taskArgs);
    }

    /**
     * Configures the settings which should be rendered on the feed edit page in the Form Settings > Simple Feed Add-On area.
     *
     * @return array
     */
    public function feed_settings_fields() {

        $settings = $this->get_plugin_settings();
        $key = rgar( $settings, 'weichie_clickup_api_key' );

        $clickup = new ClickUp\Client($key);

        $teams = $clickup->teams()->objects();
        $teams_choices = [];
        foreach( $teams as $team ){
            $teams_choices[] = [
                'label' => $team->name(),
                'value' => $team->id(),
            ];
        }

        $list_id = false;
        $team_id = ($this->get_setting('clickup_team_id')) ? $this->get_setting('clickup_team_id') : false;
        $space_id = ($this->get_setting('clickup_space_id')) ? $this->get_setting('clickup_space_id') : false;;
        $project_id = ($this->get_setting('clickup_project_id')) ? $this->get_setting('clickup_project_id') : false;;
        $list_id = ($this->get_setting('clickup_list_id')) ? $this->get_setting('clickup_list_id') : false;;

        $fields = [];

        $fields[] = array(
                'label' => esc_html__( 'Select a Team', 'simpleaddon' ),
                'type'  => 'select',
                'name'  => 'clickup_team_id',
                'onchange' => 'SelectChanged()',
                'choices'  => $teams_choices,
            );

        if( $team_id ) {

            $team = $clickup->team($team_id);
            $spaces = $team->spaces()->objects();
            $space_choices = [];
            foreach( $spaces as $space ){
                $space_choices[] = [
                    'label' => $space->name(),
                    'value' => $space->id(),
                ];
            }

            $fields[] = array(
                'label' => esc_html__('Select a Space', 'simpleaddon'),
                'type' => 'select',
                'name' => 'clickup_space_id',
                //'onchange' => 'SelectChanged()',
                'choices' => $space_choices,
            );
        }

        if( $space_id ) {

            try {
                $team = $clickup->team($team_id);
                $space = $team->space($space_id);
                $projects = $space->projects()->objects();
                $projects_choices = [];
                foreach ($projects as $project) {
                    $projects_choices[] = [
                        'label' => $project->name(),
                        'value' => $project->id(),
                    ];
                }

                $fields[] = array(
                    'label' => esc_html__('Select a Project', 'simpleaddon'),
                    'type' => 'select',
                    'name' => 'clickup_project_id',
                    //'onchange' => 'SelectChanged()',
                    'choices' => $projects_choices,
                );
            } catch(Exception $e){}
        }

        if( $project_id ) {

            try {
                $team = $clickup->team($team_id);
                $space = $team->space($space_id);
                $project = $space->project($project_id);
                $lists = $project->taskLists()->objects();
                $list_choices = [];
                foreach ($lists as $list) {
                    $list_choices[] = [
                        'label' => $list->name(),
                        'value' => $list->id(),
                    ];
                }

                $fields[] = array(
                    'label' => esc_html__('Select a List', 'simpleaddon'),
                    'type' => 'select',
                    'name' => 'clickup_list_id',
                    //'onchange' => 'SelectChanged()',
                    'choices' => $list_choices,
                );
            } catch(Exception $e){}

        }

        if( $list_id ) {

            try {
                $team = $clickup->team($team_id);
                $space = $team->space($space_id);
                $project = $space->project($project_id);

                $list = $project->taskList($list_id);

                $members = $list->members();

                $custom_fields = $list->customFields();

                // Get text fields only for now
                $custom_text_fields = [];
                foreach( $custom_fields['fields'] as $field ){
                    if( in_array($field['type'], ['short_text', 'url']) ){
                        $custom_text_fields[] = [
                            'name'          => $field['id'], // str_replace('-','_',sanitize_title($field['name'])),
                            'label'         => esc_html__( $field['name'], 'sometextdomain' ),
                            'required'      => false,
                            //'field_type'    => array( 'name', 'email', 'text', 'hidden' ),
                            //'default_value' => $this->get_first_field_by_type( 'name', 3 ),
                        ];
                    }
                }

                $member_choices = [];
                foreach( $members['members'] as $member ){
                    $member_choices[] = [
                        'label' => (($member['profilePicture']=='')?'':'%img%'.$member['profilePicture'].'%endimg%') . $member['username'], //'<img src="'.$member['profilePicture'].'">' .
                        'name' => 'clickup_member_ids_'.$member['id'],
                        'value' => $member['id'],
                    ];
                }

                $fields[] = array(
                    'label' => esc_html__('Select a Assignee', 'simpleaddon'),
                    'type' => 'checkbox',
                    'multiple' => true,
                    'name' => 'clickup_member_ids',
                    //'onchange' => 'SelectChanged()',
                    'choices' => $member_choices,
                );

                if( !empty($custom_text_fields) ){
                    $fields[] = array(
                        'name'      => 'custom_fields',
                        'label'     => esc_html__( 'Map Custom Fields', 'sometextdomain' ),
                        'type'      => 'field_map',
                        'field_map' => $custom_text_fields,
                        //'tooltip'   => '<h6>' . esc_html__( 'Map Fields', 'sometextdomain' ) . '</h6>' . esc_html__( 'Select which Gravity Form fields pair with their respective third-party service fields.', 'sometextdomain' )
                    );
                }

                // @TODO Custom fields load

            } catch(Exception $e){}

            $fields[] = array(
                'name' => 'title', // name
                'label' => esc_html__('Task Title', 'simplefeedaddon'),
                'required' => 1,
                'type'    => 'text',
                'class'   => 'medium merge-tag-support mt-position-right',
            );
            $fields[] = array(
                'name' => 'description', // name
                'label' => esc_html__('Task Description', 'simplefeedaddon'),
                'required' => 1,
                'type'    => 'textarea',
                'class'   => 'medium merge-tag-support mt-position-right',
            );
            $fields[] = array(
              'name' => 'tags', // name
              'label' => esc_html__('Tags', 'simplefeedaddon'),
              'required' => 0,
              'type'    => 'text',
              'class'   => 'medium mt-position-right',
              'instructions' => 'Please enter tags separated by comma.',
            );
            $fields[] = array(
                'name'           => 'condition',
                'label'          => esc_html__( 'Condition', 'simplefeedaddon' ),
                'type'           => 'feed_condition',
                'checkbox_label' => esc_html__( 'Enable Condition', 'simplefeedaddon' ),
                'instructions'   => esc_html__( 'Process this simple feed if', 'simplefeedaddon' ),
            );
        }

        return array(
            array(
                'title'  => esc_html__( 'ClickUp Feed Settings', 'simplefeedaddon' ),
                'fields' => $fields,
            ),
        );
    }

    /**
     * Configures which columns should be displayed on the feed list page.
     *
     * @return array
     */
    public function feed_list_columns() {
        return array(
            'title' => esc_html__( 'ClickUp Feed', 'simplefeedaddon' ),
        );

    }

    /**
     * Format the value to be displayed in the mytextbox column.
     *
     * @param array $feed The feed being included in the feed list.
     *
     * @return string
     */
    public function get_column_value_mytextbox( $feed ) {
        return '<b>' . rgars( $feed, 'meta/mytextbox' ) . '</b>';
    }

    /**
     * Prevent feeds being listed or created if an api key isn't valid.
     *
     * @return bool
     */
    public function can_create_feed() {

        // Get the plugin settings.
        $settings = $this->get_plugin_settings();

        // Access a specific setting e.g. an api key
        $key = rgar( $settings, 'weichie_clickup_api_key' );

        // @TODO check if clickup api is working and connected
        if( $key ){
            return true;
        }

        return false;
    }

    public function after_submission(){

    }

}
