<?php

class BWFCRM_Filter_Funnelkit_Optins extends BWFCRM_Custom_Filter_Base {
	private static $ins = null;

	public static function get_instance() {
		if ( null === self::$ins ) {
			self::$ins = new self();
		}

		return self::$ins;
	}

	public function __construct() {
		$this->name = 'funnelkit_optin';
		add_filter( 'bwfan_contact_sql_join_query', array( $this, 'join_query' ), 10, 2 );
		add_filter( 'bwfan_contact_sql_where_query', array( $this, 'where_query' ), 10, 4 );
		add_filter( 'bwfan_contact_sql_group_by_query', array( $this, 'group_by' ), 10, 2 );
	}

	public function join_query( $join_query, $custom_filters ) {
		if ( ! $this->is_current_filter_exists( $custom_filters ) ) {
			return $join_query;
		}

		/** If Join is already there */
		if ( false !== strpos( $join_query, 'wfacp_stats' ) ) {
			return $join_query;
		}

		global $wpdb;

		$sql = " LEFT JOIN {$wpdb->prefix}bwf_optin_entries as bwf_opt ON c.id=bwf_opt.cid";

		return $join_query . $sql;
	}

	public function where_query( $filter_where, $filter_key, $filter_rule, $filter_value ) {
		if ( $this->name !== $filter_key || empty( $filter_value ) ) {
			return $filter_where;
		}

		$not_null = '';
		$sub_rule = 'AND';
		switch ( $filter_rule ) {
			case 'any':
				$filter_rule = 'LIKE';
				$sub_rule    = 'OR';
				break;
			case 'none':
				$filter_rule = 'NOT LIKE';
				$not_null    = " OR bwf_opt.cid IS NULL ";
				break;
			case 'all':
				$filter_rule = 'LIKE';
				break;
		}

		$filter_value = explode( ',', $filter_value );

		$filter_value = array_map( function ( $val ) use ( $filter_rule ) {
			return "bwf_opt.step_id $filter_rule '%$val%'";
		}, $filter_value );

		$filter_value = implode( " {$sub_rule} ", $filter_value );

		return ' ( ' . $filter_value . $not_null . ' ) ';
	}

	/**
	 * adding group by clause for 'is' operator
	 * not required for 'is not' operator as in where clause we are setting bwf_opt.cid IS NULL and it will return only one data
	 *
	 * @param $group_by_query
	 * @param $filter
	 *
	 * @return string
	 */
	public function group_by( $group_by_query, $filter ) {
		$name = $this->name;

		// filtering for current filter
		$custom_filters = array_filter( $filter, function ( $cust_f ) use ( $name ) {
			return $cust_f['key'] === $name;
		} );

		// if empty or 'is not' rule selected then return
		if ( empty( $custom_filters ) || 'none' === strval( $custom_filters[0]['rule'] ) ) {
			return $group_by_query;
		}

		// grouping by cid from bwf_optin_entries table
		$group_by_query .= "bwf_opt.cid";

		return $group_by_query;
	}
}

$ins = BWFCRM_Filter_Funnelkit_Optins::get_instance();
BWFCRM_Filters::register_custom_filter( $ins->name );
