<?php

class BWFCRM_Filter_WP_User_Role 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 = 'role';
		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 );
	}

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

		global $wpdb;

		$sql = " LEFT JOIN {$wpdb->usermeta} as um ON c.wpid=um.user_id";

		return $join_query . $sql;
	}

	public function where_query( $filter_where, $filter_key, $filter_rule, $filter_value ) {
		global $wpdb;

		if ( 'role' !== $filter_key || empty( $filter_value ) ) {
			return $filter_where;
		}

		switch ( $filter_rule ) {
			case 'is':
				$filter_rule = 'LIKE';
				break;
			case 'is_not':
				$filter_rule = 'NOT LIKE';
				break;
		}

		$sub_rule = 'LIKE' === $filter_rule ? 'OR' : 'AND';

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

		$filter_value = array_map( function ( $val ) use ( $filter_rule ) {
			return "um.meta_value $filter_rule '%\"$val\"%'";
		}, $filter_value );

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

		if ( 'LIKE' === $filter_rule ) {
			return "um.meta_key='{$wpdb->prefix}capabilities' AND ({$filter_value})";
		}

		/** all wp users who does not have mentioned roles + all non-wp-user contacts */
		return "(um.meta_key='{$wpdb->prefix}capabilities' AND ({$filter_value}) OR c.wpid = 0 ) ";
	}
}

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