<?php

require_once EH_CRM_MAIN_PATH . '/vendor/autoload.php';

use Illuminate\Support\Arr;
use WSDesk\Tickets\TicketRepository;


if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// ob_start();
$users      = get_users( array( 'role__in' => array( 'WSDesk_Agents', 'WSDesk_Supervisor', 'administrator' ) ) );
$users_data = array();
for ( $i = 0; $i < count( $users ); $i++ ) {
	$uid                        = $users[ $i ]->ID;
	$user                       = new WP_User( $uid );
	$users_data[ $i ]['id']     = $uid;
	$users_data[ $i ]['name']   = $user->display_name;
	$users_data[ $i ]['email']  = $user->user_email;
	$users_data[ $i ]['avatar'] = get_avatar_url( $uid );
	$users_data[ $i ]['role']   = $user->roles;
	$users_data[ $i ]['caps']   = $user->caps;
	$users_data[ $i ]['tags']   = get_user_meta( $uid, 'wsdesk_tags', true );
}

$user_ids = array_map(
	function ( $user ) {
		return $user['id'];
	},
	$users_data
);

global $wpdb;

$ticket_reply_count_by_users = wpFluent()->table( 'wsdesk_tickets' )
				   ->whereIn( 'ticket_author', $user_ids )
			   ->where( 'ticket_parent', '<>', 0 )
			   ->where( 'ticket_trash', 0 )
				->groupBy( 'ticket_author' )
				->select( 'ticket_author', wpFluent()->raw( 'count(ticket_id) as count' ) )
			->get();

$ticket_reply_count_by_users = Arr::pluck( $ticket_reply_count_by_users, 'count', 'ticket_author' );

$repo   = new TicketRepository();
$filter = [
	'view' => [
		'agents' => $user_ids,
	],
];

$agentsQuery            = $repo->applyFilter( $filter )->select( 'ticket_id' );
$assigned_tickets_count = $repo->getCountByAgents( $agentsQuery->getQuery()->getRawSql() );
$assigned_tickets_count = Arr::pluck( $assigned_tickets_count, 'count', 'slug' );

$hasRatingQuery = 'select ticket_id from ' . $wpdb->prefix . 'wsdesk_ticketsmeta as m where m.meta_key = "ticket_rating"';


$agentsQuery              = $agentsQuery->where( \DB::raw( 'ticket_id in (' . $hasRatingQuery . ')' ) );
$has_rating_tickets_count = $repo->getCountByAgents( $agentsQuery->getQuery()->getRawSql() );
$has_rating_tickets_count = Arr::pluck( $has_rating_tickets_count, 'count', 'slug' );

$hasRatingQuery           .= ' and meta_value = "great"';
$agentsQuery               = $agentsQuery->where( \DB::raw( 'ticket_id in (' . $hasRatingQuery . ')' ) );
$good_rating_tickets_count = $repo->getCountByAgents( $agentsQuery->getQuery()->getRawSql() );
$good_rating_tickets_count = Arr::pluck( $good_rating_tickets_count, 'count', 'slug' );

//dd($good_rating_tickets_count);

?>

<div class="panel-group" id="manage_role" style="margin-bottom: 0px !important">
	<?php
	if ( count( $users_data ) !== 0 ) {
		$flag            = 0;
		$current_user_id = wp_get_current_user()->ID;
		foreach ( wp_get_current_user()->roles as $urole ) {
			if ( 0 == $flag ) {
				$current_user_access = $urole;
				$flag                = 1;
			}
		}
		for ( $i = 0; $i < count( $users_data ); $i++ ) {
			$uid = $users_data[ $i ]['id'];
			if ( in_array( 'WSDesk_Agents', $users_data[ $i ]['role'] ) ) {
				$urole = 'WSDesk Agents';
			} elseif ( in_array( 'WSDesk_Supervisor', $users_data[ $i ]['role'] ) ) {
				$urole = 'WSDesk Supervisor';
			} elseif ( in_array( 'administrator', $users_data[ $i ]['role'] ) ) {
				$urole = 'Administrator';
			}
			$enabledisable = '';
			if ( 'Administrator' == $urole || 'WSDesk Supervisor' == $urole ) {
				if ( 'administrator' != $current_user_access ) {
					$enabledisable = 'disabled';
					if ( $uid == $current_user_id ) {
						$enabledisable = '';
					}
				}
				if ( 'administrator' == $current_user_access ) {
					if ( 'Administrator' == $urole ) {
						$enabledisable = 'disabled';
					}
				}
			}

			$roles_temp = $users_data[ $i ]['role'];
			$roles      = array();
			foreach ( $roles_temp as $value ) {
				$current_role = $value;
				array_push( $roles, ucfirst( str_replace( '_', ' ', $current_role ) ) );
			}
			$caps_temp = array_keys( $users_data[ $i ]['caps'] );
			$caps      = '';
			for ( $j = 0; $j < count( $caps_temp ); $j++ ) {
				switch ( $caps_temp[ $j ] ) {
					case 'reply_tickets':
						$caps .= '<span class="tags">' . __( 'Reply Tickets', 'wsdesk' ) . '</span> ';
						break;
					case 'delete_tickets':
						$caps .= '<span class="tags">' . __( 'Delete Tickets', 'wsdesk' ) . '</span> ';
						break;
					case 'manage_tickets':
						$caps .= '<span class="tags">' . __( 'Manage Tickets', 'wsdesk' ) . '</span> ';
						break;
					case 'credit_deduction':
						if ( defined( 'PFS_IS_INSTALLED' ) ) {
							$caps .= '<span class="tags">' . __( 'Credit Deduction', 'wsdesk' ) . '</span> ';
						}
						break;
					case 'manage_templates':
						$caps .= '<span class="tags">' . __( 'Manage Templates', 'wsdesk' ) . '</span> ';
						break;
					case 'settings_page':
						$caps .= '<span class="tags">' . __( 'Settings Manage', 'wsdesk' ) . '</span> ';
						break;
					case 'agents_page':
						$caps .= '<span class="tags">' . __( 'Agents Manage', 'wsdesk' ) . '</span> ';
						break;
					case 'import_page':
						$caps .= '<span class="tags">' . __( 'Import Manage', 'wsdesk' ) . '</span> ';
						break;
					case 'email_page':
						$caps .= '<span class="tags">' . __( 'Email Manage', 'wsdesk' ) . '</span> ';
						break;
					case 'merge_tickets':
						$caps .= '<span class="tags">' . __( 'Merge Tickets', 'wsdesk' ) . '</span> ';
				}
			}
			if ( '' === $caps ) {
				if ( 'Administrator' == $urole ) {
					$caps .= '<span class="tags">' . __( 'Reply Tickets', 'wsdesk' ) . '</span> ';
					$caps .= '<span class="tags">' . __( 'Delete Tickets', 'wsdesk' ) . '</span> ';
					$caps .= '<span class="tags">' . __( 'Manage Tickets', 'wsdesk' ) . '</span> ';
					if ( defined( 'PFS_IS_INSTALLED' ) ) {
						$caps .= '<span class="tags">' . __( 'Credit Deduction', 'wsdesk' ) . '</span> ';
					}
					$caps .= '<span class="tags">' . __( 'Merge Tickets', 'wsdesk' ) . '</span> ';
					$caps .= '<span class="tags">' . __( 'Manage Templates', 'wsdesk' ) . '</span> ';
					$caps .= '<span class="tags">' . __( 'Settings Manage', 'wsdesk' ) . '</span> ';
					$caps .= '<span class="tags">' . __( 'Agents Manage', 'wsdesk' ) . '</span> ';
					$caps .= '<span class="tags">' . __( 'Import Manage', 'wsdesk' ) . '</span> ';
					$caps .= '<span class="tags">' . __( 'Email Manage', 'wsdesk' ) . '</span> ';
				} else {
					$caps .= __( 'No Capabilities Assigned', 'wsdesk' );
				}
			}
			$tags_temp = $users_data[ $i ]['tags'];
			$tags      = '';
			if ( ! empty( $tags_temp ) ) {
				for ( $j = 0; $j < count( $tags_temp ); $j++ ) {
					$stag = eh_crm_get_settings(
						array(
							'slug' => $tags_temp[ $j ],
							'type' => 'tag',
						),
						array( 'title' )
					);
					if ( ! empty( $stag ) ) {
								 $tags .= '<span class="tags">' . $stag[0]['title'] . '</span>';
					}
				}
			} else {
				$tags .= __( 'No Tags Mapped', 'wsdesk' );
			}
			if ( '' == $tags ) {
				$tags .= __( 'No Tags Mapped', 'wsdesk' );
			}
			$overall_replies  = Arr::get( $ticket_reply_count_by_users, $users_data[ $i ]['id'], 0 );
			$overall_assigned = Arr::get( $assigned_tickets_count, $users_data[ $i ]['id'] );
			$all              = (int) Arr::get( $has_rating_tickets_count, $users_data[ $i ]['id'] );
			$good             = (int) Arr::get( $good_rating_tickets_count, $users_data[ $i ]['id'] );
			$bad              = $all - $good;
			if ( 0 !== $all ) {
				$rating = ( $good / ( $all / 100 ) ) - ( $bad / ( $all / 100 ) );
			} else {
				$rating = 'None';
			}
			echo '<div class="panel panel-default">
                        <div class="panel-heading collapsed" data-toggle="collapse" data-parent="#manage_role" data-target="#content_' . esc_attr( $uid ) . '">
                            <span class ="manage-role-toggle"></span>
                            <h4 class="panel-title">
                                    ' . esc_html( $users_data[ $i ]['name'] ) . ' ( ' . esc_attr( $urole ) . ' )
                            </h4>
                        </div>
                        <div id="content_' . esc_attr( $uid ) . '" class="panel-collapse collapse">
                            <div class="panel-body">
                                <div class="col-md-12">
                                    <center>
                                        <div class="well profile">
                                           <div class="col-sm-12">
                                               <div class="col-xs-12 col-sm-9">
                                                   <h2>' . esc_html( $users_data[ $i ]['name'] ) . '</h2>
                                                   <p><strong>' . esc_html__( 'Roles', 'wsdesk' ) . ': </strong> ' . esc_html( implode( ', ', $roles ) ) . ' </p>
                                                   <p><strong>' . esc_html__( 'Email', 'wsdesk' ) . ': </strong> ' . esc_html( $users_data[ $i ]['email'] ) . ' </p>
                                                   <p><strong>' . esc_html__( 'Capability', 'wsdesk' ) . ': </strong>
                                                       <span style="line-height:1.75"> ' . wp_kses( $caps, array( 'span' => array( 'class' => array() ) ) ) . ' </span>
                                                   </p>
                                               </div>
                                               <div class="col-xs-12 col-sm-3 text-center">
                                                    <center>
                                                        <figure>
                                                            <img src="' . esc_url( $users_data[ $i ]['avatar'] ) . '" alt="" class="img-circle img-responsive">
                                                            <figcaption class="ratings">
                                                                <p style="line-height:1.75!important"><strong>' . esc_html__( 'Tags', 'wsdesk' ) . ': </strong>
                                                                    ' . wp_kses( $tags, array( 'span' => array( 'class' => array() ) ) ) . '
                                                                </p>
                                                            </figcaption>
                                                        </figure>
                                                    </center>
                                               </div>
                                           </div>
                                           <div class="col-xs-12 divider text-center">
                                               <div class="col-xs-12 col-sm-4 emphasis">
                                                   <h2><strong> ' . esc_html( $overall_replies ) . ' </strong></h2>
                                                   <p><small>' . esc_html__( 'Overall Replies', 'wsdesk' ) . '</small></p>
                                                   <button class="btn btn-success btn-block edit_user" id="user_edit_' . esc_attr( $uid ) . '" ' . esc_attr( $enabledisable ) . '><span class="glyphicon glyphicon-edit"></span> ' . esc_html__( 'Edit Profile', 'wsdesk' ) . '</button>
                                               </div>
                                               <div class="col-xs-12 col-sm-4 emphasis">
                                                   <h2><strong> ' . esc_html( $overall_assigned ) . ' </strong></h2>
                                                   <p><small>' . esc_html__( 'Tickets Assigned', 'wsdesk' ) . '</small></p>
                                                   <a class="btn btn-info btn-block" target="_blank" href="' . esc_url( admin_url( 'admin.php?page=wsdesk_reports&user=' ) . esc_url( $uid ) ) . '" ><span class="glyphicon glyphicon-signal"></span> ' . esc_html__( 'View Reports', 'wsdesk' ) . ' </a>
                                               </div>
                                               <div class="col-xs-12 col-sm-4 emphasis">
                                                   <h2><strong> ' . esc_html( $rating ) . ' </strong></h2>
                                                   <p><small>' . esc_html__( 'Support Rating', 'wsdesk' ) . '</small></p>
                                                   <div class="btn-group dropup btn-block">
                                                        <button type="button" class="btn btn-primary dropdown-toggle" ' . esc_attr( $enabledisable ) . ' style="width:100% !important" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                                        <span class="glyphicon glyphicon-user"></span> ' . esc_html__( 'Actions', 'wsdesk' ) . ' <span class="caret"></span>
                                                        </button>
                                                        <ul class="dropdown-menu">
                                                          <li><span class="user_actions user_actions_remove" id="user_actions_remove_' . esc_attr( $uid ) . '"><span class="glyphicon glyphicon-remove pull-right"></span>' . esc_html__( 'Remove WSDesk Role', 'wsdesk' ) . '</span></li>
                                                        </ul>
                                                    </div>
                                               </div>
                                           </div>
                                        </div>
                                    </center>
                                </div>
                            </div>
                            <div id="user_content_change_' . esc_attr( $uid ) . '">
                            </div>
                        </div>
                    </div>';
		}
	} else {
		?>
		<div style="text-align: center">
			<h1><span class="glyphicon glyphicon-screenshot" style="font-size: 2em;color: lightgrey;"></span></h1><br>
		<?php
		esc_html_e( 'No WSDesk role assigned to any users / No Agents added', 'wsdesk' );
		?>
		</div>
		<?php
	}
	?>
</div>
<?php
// return ob_get_clean();
