<?php

function add_mint_csr_css() {
    $plugin_url = plugin_dir_url( __FILE__ );
   	wp_enqueue_style( 'mint-csr-style',  $plugin_url . "mint-csr.css");
}

add_action( 'wp_enqueue_scripts', 'add_mint_csr_css' );

function get_mint_csr_callback(){
	global $wpdb;

	$html = "";
    wp_enqueue_style( 'cip-css' );
    wp_enqueue_style( 'bs-table' );
    wp_enqueue_style( 'bs-sticky-header' );
    wp_enqueue_script('bs-table');
    wp_enqueue_script('bs-sticky-header');
    wp_enqueue_script('bs-table-filter-control');
    ob_start();
    ?>
    <div class="promotion_mint_csr_table_wrapper">
        <div class="text-right">
            <button type="button" id="add_new_mint_csr_admin_header" class="text-right mb-2" data-toggle="modal" data-target="#AddNewAdminMintCSR"><i class="fa fa-plus" aria-hidden="true"></i> <?php _e('Add', CIP_TXTDOMAIN); ?></button>
        </div>
        <table id="cip_mint_csr_admin_table" data-filter-control="true" data-show-search-clear-button="false" data-pagination="true" data-toggle="table" data-show-columns="false" data-show-toggle="false" data-click-to-select="false" data-show-columns-toggle-all="false" data-show-export="false" data-click-to-select="false" class="table table-bordered" data-side-pagination="server" data-pagination="true" data-page-list="[10, 20, 50, 100]">
        <thead>
            <tr>
                <th data-field="id" class="id" data-switchable="false"><?php _e('ID','corsair-login'); ?></th>
                <th data-field="name" data-filter-control="input" data-sortable="true" class="name" data-switchable="false"><?php _e('Admin Name','corsair-login'); ?></th>
                <th data-field="email" data-filter-control="input" data-sortable="true" class="email" data-switchable="false"><?php _e('Email','corsair-login'); ?></th>
                <th data-field="action" class="action" data-switchable="false"><?php _e('Action','corsair-login'); ?></th>
            </tr>
        </thead>
        <tbody>
        </tbody>
        </table>
    </div>
    <div class="modal fade" id="AddNewAdminMintCSR" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
            <div class="modal-content">
            	<div class="modal-header">
			        <h5 class="modal-title"><?php _e('Add Mint CSR', CIP_TXTDOMAIN); ?></h5>
			        <button type="button" class="close" data-dismiss="modal" aria-label="Close" style="margin: 0;opacity: 1;">
			          <span aria-hidden="true">&times;</span>
			        </button>
			      </div>
                <div class="modal-body">
                    <form class="add_mint_csr_admin_form" id="add_mint_csr_admin_form" name="add_mint_csr_admin_form">
                        <div class="update_mint_csr_verification_content">

                        </div>

                        <div class="form-group update_mint_csr_form_content">
                            <label for="admin_user"><?php echo __('Select Admin', CIP_TXTDOMAIN); ?></label>
                            <select name="admin_user" id="admin_user" class="form-control">
                            	
                            </select>
                            <br>
	                        <button type="submit" class="btn btn-secondary"><?php _e('Submit', CIP_TXTDOMAIN); ?></button>
	                        <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php _e('Cancel', CIP_TXTDOMAIN) ?></button>
	                        <input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_YCIPAddNewAdminMintCSR_'); ?>" />
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div> 
    <div class="modal fade" id="DeleteAdminMintCSR" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
            <div class="modal-content">
            	<div class="modal-header">
			        <h5 class="modal-title"><?php _e('Delete Mint CSR', CIP_TXTDOMAIN); ?></h5>
			        <button type="button" class="close" data-dismiss="modal" aria-label="Close" style="margin: 0;opacity: 1;">
			          <span aria-hidden="true">&times;</span>
			        </button>
			      </div>
                <div class="modal-body">
                    <form class="delete_mint_csr_admin_form" id="delete_mint_csr_admin_form" name="delete_mint_csr_admin_form">
                    	<input type="hidden" name="id" id="min_csr_id" value="">
                        <div class="delete_mint_csr_verification_content">

                        </div>
	                    <input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_Micro_MintCSRDelete_Micro_'); ?>" />
                    </form>
                </div>
            </div>
        </div>
    </div>   
    <?php
    $html .= ob_get_clean();
    return $html;
}

add_action('wp_footer', 'wpb_hook_javascript_for_mint_csr_footer');
function wpb_hook_javascript_for_mint_csr_footer() {
	$cip_mint_csr_url = add_query_arg( [
		'action'	=>	'cip_mint_csr_admins_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );

	$get_admin_users = add_query_arg( [
		'action'	=>	'cip_get_admin_users',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );

	$add_mint_csr_url = add_query_arg( [
		'action'	=>	'cip_add_mint_csr_admins_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	$delete_mint_csr_url = add_query_arg( [
		'action'	=>	'cip_delete_mint_csr_admins_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );

    ?>
        <script>
            jQuery(document).ready(function($){

                const swalToast1 = Swal.mixin({
                    toast: true,
                    animation: true,
                    position: 'bottom',
                    showConfirmButton: false,
                    timer: 4000,
                    timerProgressBar: true,
                    didOpen: (toast) => {
                      toast.addEventListener('mouseenter', Swal.stopTimer)
                      toast.addEventListener('mouseleave', Swal.resumeTimer)
                    }
                });
                
                var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };


        		if( $('#cip_mint_csr_admin_table').length > 0 ){		
					var cip_mint_csr_url = "<?php echo $cip_mint_csr_url ?>";
					// console.log( cip_sms_alert_management_list_url );
					var $minCSRTable = $('#cip_mint_csr_admin_table');
					var params = {}
					$minCSRTable.bootstrapTable({
						method: 'post',
						contentType: 'application/x-www-form-urlencoded',
						url: cip_mint_csr_url,
						searchTimeOut:1000,
						queryParams: function (p) {
							params = p.filter;
							return {
								columnfilter: p.filter,
								limit: p.limit,
								offset: p.offset,
								sort: p.sort,
								order: p.order,
							};
						},
						stickyHeader: false,
						onPostBody: function (){
							if( $('[data-toggle-tt="tooltip"]').length > 0 ){
								$('[data-toggle-tt="tooltip"]').tooltip();
							}
							$('.filter-control input.search-input').prop('readonly',false);
					  	},
						onSearch: function( search ){
							$('.filter-control input.search-input').prop('readonly',true);
						}
					});
				}

				$(document).on('click','#add_new_mint_csr_admin_header',function(e){
					e.preventDefault()
					var get_admin_users = "<?php echo $get_admin_users ?>";
					$.blockUI(block_config);

					$.ajax({
	                    url: get_admin_users,
	                    type: "POST",
	                    success: function (response) {
                            
                            console.log(response)
                            var html = '<option disabled selected value="" required>Select Admin</option>';
	                        $.each(response, function(index, value){
	                        	html += '<option value="'+value.ID+'">'+value.user_email+'</option>';
	                        })
	                        $('#admin_user').html(html)
							$('#AddNewAdminMintCSR').modal('show');
	                        $.unblockUI();

	                    }
		            });	

				})

				$(document).on('hidden.bs.modal','#AddNewAdminMintCSR', function () {
				  	$('.update_mint_csr_verification_content').html('')
	                $('.update_mint_csr_form_content').show()
	                $("#add_mint_csr_admin_form")[0].reset();
				})

				$(document).on('click','.delete-mint-csr-admin',function(){
					
						var delete_mint_csr_url = "<?php echo $delete_mint_csr_url ?>";
						
						var recordid = $(this).attr('data-delete')
						var micro = $(this).attr('data-micro');
	                    Swal({
	                        title: 'Are you sure?',
	                        text: "Do you want to remove admin from Mint CSR?",
	                        type: 'warning',
	                        showCancelButton: true,
	                        confirmButtonText: 'Yes'
	                      }).then((result) => {
	                        if (result.value) {
									$.blockUI(block_config);

					                $.ajax({
					                    url: delete_mint_csr_url,
					                    type: "POST",
					                    data: {'id': recordid,'_micro': micro},
					                    success: function (response) {
					                    	if(response.verificationCodeSent)
					                    	{
					                    		$('#DeleteAdminMintCSR .delete_mint_csr_verification_content').html(response.otpContent);
					                    		$('#DeleteAdminMintCSR #min_csr_id').val(recordid)
					                    		$('#DeleteAdminMintCSR').modal('show');
					                    	}else{
						                        if(response.error)
						                        {
						                        	swalToast1({ type: 'error', title: response.message, text: '',allowOutsideClick: true});
						                        }
						                        else
						                        {	
						                        	swalToast1({ type: 'success', title: response.message, text: '',allowOutsideClick: true});
						                        	let eve = jQuery.Event("keyup");
				                                    eve.which = 13
				                                    eve.keyCode = 13
				                                    $('#cip_mint_csr_admin_table input[type="search"].form-control.search-input').val('').trigger(eve);
						                        }	                        						                    		
					                    	}
					                        
				                            $.unblockUI();
					                    }
					                });	
		                        }
		                   })
				})

				$(document).on('submit','#delete_mint_csr_admin_form',function(e){
					e.preventDefault();
					
					var delete_mint_csr_url = "<?php echo $delete_mint_csr_url ?>";

					var container = $(this);
					var request = $(container).serialize();
					$.blockUI(block_config);

	                $.ajax({
	                    url: delete_mint_csr_url,
	                    type: "POST",
	                    data: request,
	                    success: function (response) {
	                    	if(response.verificationCodeSent)
	                    	{
	                    		$('#DeleteAdminMintCSR .delete_mint_csr_verification_content').html(response.otpContent);
	                    		$('#DeleteAdminMintCSR #min_csr_id').val(recordid)
	                    		$('#DeleteAdminMintCSR').modal('show');
	                    	}else{
		                        if(response.error)
		                        {
		                        	swalToast1({ type: 'error', title: response.message, text: '',allowOutsideClick: true});
		                        }
		                        else
		                        {	
		                        	swalToast1({ type: 'success', title: response.message, text: '',allowOutsideClick: true});
	                    			$('#DeleteAdminMintCSR').modal('hide');
		                        	let eve = jQuery.Event("keyup");
                                    eve.which = 13
                                    eve.keyCode = 13
                                    $('#cip_mint_csr_admin_table input[type="search"].form-control.search-input').val('').trigger(eve);
		                        }	                        						                    		
	                    	}
	                        
                            $.unblockUI();
	                    }
	                });	
				})

				$(document).on('submit','#add_mint_csr_admin_form',function(e){
					e.preventDefault();
					var add_mint_csr_url = "<?php echo $add_mint_csr_url ?>";
					var container = $(this);
					if($(this).find('select#admin_user').val())
					{
						$.blockUI(block_config);
						var request = $(container).serialize();

		                $.ajax({
		                    url: add_mint_csr_url,
		                    type: "POST",
		                    data: request,
		                    success: function (response) {
		                        if(response.verificationCodeSent)
		                        {
		                        	$('.update_mint_csr_verification_content').html(response.otpContent)
		                        	$('.update_mint_csr_form_content').hide()
		                        }else{
			                        if(response.error)
			                        {
			                        	swalToast1({ type: 'error', title: response.message, text: '',allowOutsideClick: true});
			                        }
			                        else
			                        {	
			                        	swalToast1({ type: 'success', title: response.message, text: '',allowOutsideClick: true});
			                        	$('#AddNewAdminMintCSR').modal('hide');
			                        	let eve = jQuery.Event("keyup");
	                                    eve.which = 13
	                                    eve.keyCode = 13
	                                    $('#cip_mint_csr_admin_table input[type="search"].form-control.search-input').val('').trigger(eve);
			                        }	                        	
		                        }
	                            $.unblockUI();
		                    }
		                });						
					}else{
						swalToast1({ type: 'error', title: 'Please select admin to add', text: '',allowOutsideClick: true});
					}
				})

            })
        </script>
	<?php 
}
add_action( 'wp_ajax_cip_mint_csr_admins_loader', 'cip_mint_csr_admins_loader_callback' );

function cip_mint_csr_admins_loader_callback(){
	global $wpdb;
    $mintCSRTable = $wpdb->prefix.'mint_csr';
    
    $total_items = $wpdb->get_var("SELECT COUNT(id) FROM $mintCSRTable WHERE 1=1");
    
    $limit = isset( $_POST['limit'] ) ? $_POST['limit'] : 10;
    $offset = isset( $_POST['offset'] ) ? $_POST['offset'] : 0;
    $orderby = isset( $_POST['sort'] ) ? $_POST['sort'] : 'id';
    $order = (isset($_POST['order']) && in_array($_POST['order'], array('asc', 'desc'))) ? $_POST['order'] : 'desc';
    
    $filter_qry = "";
    $filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
    if( !empty( $filters ) ){
        foreach( $filters as $filterKey => $filterData ){
            $filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
        }
        $total_items = $wpdb->get_var("SELECT COUNT(id) FROM $mintCSRTable WHERE 1=1 $filter_qry");
    }
    
    $getMintCSRs = $wpdb->get_results("SELECT * FROM $mintCSRTable WHERE 1=1 $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");
    
    $rows = array();
    if( $getMintCSRs ){
        $sno= $_REQUEST['offset'] + 1;
        foreach( $getMintCSRs as $getMintCSR ){
            $row = array();
            $row['id'] = $sno;
         
         	$row['name'] =  $getMintCSR->name;
         	$row['email'] =  $getMintCSR->email;
           	$row['action'] = '<a href="javascript:void(0);" class="delete-mint-csr-admin ml-3" data-delete="'. $getMintCSR->id .'" data-micro="'.wp_create_nonce('_Micro_MintCSRDelete_Micro_').'" data-toggle-tt="tooltip" data-placement="top" title="Delete"><i class="fas fa-trash-alt"></i></a>';
                
            $rows[] = $row;
            $sno=$sno+1;
        }
    }
    $out = array(
        'total'         =>  $total_items,
        'rows'          =>  $rows,
    );
    echo wp_json_encode( $out );
    exit;
}

add_action( 'wp_ajax_cip_get_admin_users', 'cip_get_admin_users_callback' );
function cip_get_admin_users_callback(){
	global $wpdb;

	$args = array(
	    'role__in' => array('administrator', 'supportagent'), // Include both roles
	    'orderby'  => 'user_nicename',
	    'order'    => 'ASC'
	);

	$users = get_users( $args );
	

	$table_name = $wpdb->prefix . 'mint_csr';

	$addedUserId = $wpdb->get_col("SELECT `user_id` FROM $table_name");

	$finelUsers = [];
	foreach ($users as $key => $user) {
		if(!in_array($user->ID, $addedUserId))
		{
			$data = [
				'display_name' => $user->display_name,
				'user_email' => $user->user_email,
				'ID' => $user->ID
			];
			array_push($finelUsers, $data);
		}
	}

	wp_send_json($finelUsers);

}


add_action( 'wp_ajax_cip_delete_mint_csr_admins_loader', 'cip_delete_mint_csr_admins_loader_callback' );
function cip_delete_mint_csr_admins_loader_callback(){
	global $wpdb;
	$table_name = $wpdb->prefix . 'mint_csr';

	$user = wp_get_current_user();
	
	$response['error'] = true;
	$response['message'] = __('Something went wrong', CIP_TXTDOMAIN);		

	if(wp_verify_nonce( $_POST['_micro'],'_Micro_MintCSRDelete_Micro_' ) && $user)
	{
		if( !isset( $_POST['verification_code'] ) ){ //send OTP to user email
			$response['verificationCodeSent'] = true;
			$encryptId = base64_encode( $user->ID . md5('CL_RESEND_CL'));
			$activeType = base64_encode( md5('GoogleAuth2FA') );
			ob_start();
			?>
			<input type="hidden" name="microtoken" value="<?php echo $encryptId; ?>" />
			<input type="hidden" name="activetype" value="<?php echo $activeType; ?>" />
			<div class="otp_section pb-3">
				<label for="verification_code"><?php echo __('Please enter authenticator code', CIP_TXTDOMAIN); ?></label>
				<input type="text" name="verification_code" id="verification_code" class="input" maxlength="6" pattern="{0-9}+" />
				<small class="form-text text-muted"><?php _e('Enter the 6-digit code generated by the Authenticator App.') ?></small>
			</div>
			<input type="submit" name="wpa-submit-verify" id="" class="button-primary" value="<?php echo __('Verify Code', CIP_TXTDOMAIN); ?>" />
			<?php
			$otpContent = ob_get_clean();
			$response['otpContent'] = $otpContent;
		}else if( isset( $_POST['verification_code'] ) ){
			$user_id = $user->ID;
			$decryptedIdRaw = base64_decode( $_POST['microtoken'] );
			$decryptedUserId = preg_replace(sprintf('/%s/', md5('CL_RESEND_CL') ), '', $decryptedIdRaw);
			if( $decryptedUserId == $user_id ){
				$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
				$google_auth_key_login = get_user_meta( $user_id, 'google_auth_key_login', true );

				if(!$google_auth_key && $google_auth_key_login != 1)
				{
					$response['error'] = true;
					$response['message'] = __('Please enable 2FA from profile page.', CIP_TXTDOMAIN);
					wp_send_json($response, $status_code );
				}
				if( !empty( $_POST['verification_code'] ) ){
					$google2fa = new \PragmaRX\Google2FA\Google2FA();
					if( $google2fa->verifyKey($google_auth_key, $_POST['verification_code']) ){
					
							if(isset($_POST['id']))
							{
								$id = $_POST['id'];
								$user_details = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $id));

								if ($user_details) {
								    $where = ['id' => $id];

								    $deleted = $wpdb->delete($table_name, $where); 

								    if ($deleted) {
								        $response['error'] = false;
								        $response['message'] = __('Admin deleted successfully', CIP_TXTDOMAIN);

										$logs = sprintf( __('Admin Deleted To Mint CSR by %s at %s. admin detail: 
							                Name: %s
							                Email: %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A'),$user_details->name,$user_details->email);

							            create_cip_logs_entery( $user_id, 'sa', '','sa', $logs, true );
								    } else {
								        $response['error'] = true;
								        $response['message'] = __('Something went wrong. Please try again.', CIP_TXTDOMAIN);
								    }
								} else {
								    $response['error'] = true;
								    $response['message'] = __('User not found.', CIP_TXTDOMAIN);
								}
							} else {
							    $response['error'] = true;
							    $response['message'] = __('Please pass user id.', CIP_TXTDOMAIN);
							}
					}else{
						$response['error'] = true;
						$response['message'] = __('Invalid authenticator code', CIP_TXTDOMAIN);
					}
				}else{
					$response['error'] = true;
					$response['message'] = __('Please enter authenticator code', CIP_TXTDOMAIN);
				}
			}else{
				$response['error'] = true;
				$response['message'] = __('User authentication failed. Please try again or contact an admin', CIP_TXTDOMAIN);
			}
		}
	}


	wp_send_json(
		$response,
		$status_code
	);

}
add_action( 'wp_ajax_cip_add_mint_csr_admins_loader', 'cip_add_mint_csr_admins_loader_callback' );
function cip_add_mint_csr_admins_loader_callback(){
	global $wpdb;
	
	$user = wp_get_current_user();
	$response['error'] = true;
	$response['message'] = __('Something went wrong', CIP_TXTDOMAIN);		
	if(wp_verify_nonce( $_POST['_micro'],'_YCIPAddNewAdminMintCSR_' ) && $user)
	{
		if( !isset( $_POST['verification_code'] ) ){ //send OTP to user email
			$response['verificationCodeSent'] = true;
			$encryptId = base64_encode( $user->ID . md5('CL_RESEND_CL'));
			$activeType = base64_encode( md5('GoogleAuth2FA') );
			ob_start();
			?>
			<input type="hidden" name="microtoken" value="<?php echo $encryptId; ?>" />
			<input type="hidden" name="activetype" value="<?php echo $activeType; ?>" />
			<div class="otp_section pb-3">
				<label for="verification_code"><?php echo __('Please enter authenticator code', CIP_TXTDOMAIN); ?></label>
				<input type="text" name="verification_code" id="verification_code" class="input" maxlength="6" pattern="{0-9}+" />
				<small class="form-text text-muted"><?php _e('Enter the 6-digit code generated by the Authenticator App.') ?></small>
			</div>
			<input type="submit" name="wpa-submit-verify" id="" class="button-primary" value="<?php echo __('Verify Code', CIP_TXTDOMAIN); ?>" />
			<?php
			
			$otpContent = ob_get_clean();
			$response['otpContent'] = $otpContent;
		}else if( isset( $_POST['verification_code'] ) ){
			$user_id = $user->ID;
			$decryptedIdRaw = base64_decode( $_POST['microtoken'] );
			$decryptedUserId = preg_replace(sprintf('/%s/', md5('CL_RESEND_CL') ), '', $decryptedIdRaw);
			if( $decryptedUserId == $user_id ){
				$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
				$google_auth_key_login = get_user_meta( $user_id, 'google_auth_key_login', true );

				if(!$google_auth_key && $google_auth_key_login != 1)
				{
					$response['error'] = true;
					$response['message'] = __('Please enable 2FA from profile page.', CIP_TXTDOMAIN);
					wp_send_json($response, $status_code );
				}
				if( !empty( $_POST['verification_code'] ) ){
					$google2fa = new \PragmaRX\Google2FA\Google2FA();
					if( $google2fa->verifyKey($google_auth_key, $_POST['verification_code']) ){
					
						$userData = get_userdata($_POST['admin_user']);

						$table_name = $wpdb->prefix . 'mint_csr';

						$result = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $table_name WHERE user_id = %d", $_POST['admin_user'] ));
						if ($result > 0) {
							$response['error'] = true;
							$response['message'] = __('Admin already added', CIP_TXTDOMAIN);
						}else{
							
							$data = [
								"name" => $userData->display_name,
								"email" => $userData->user_email,
								"user_id" => $userData->ID
							];

							$wpdb->insert($table_name, $data);

							$response['error'] = false;
							$response['message'] = 'Admin successfully added for Mint CSR25';

							$logs = sprintf( __('Admin Added To Mint CSR by %s at %s. admin detail: 
				                Name: %s
				                Email: %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A'),$userData->display_name,$userData->user_email);
				            create_cip_logs_entery( $user_id, 'sa', '','sa', $logs, true );

						}

					}else{
						$response['error'] = true;
						$response['message'] = __('Invalid authenticator code', CIP_TXTDOMAIN);
					}
				}else{
					$response['error'] = true;
					$response['message'] = __('Please enter authenticator code', CIP_TXTDOMAIN);
				}
			}else{
				$response['error'] = true;
				$response['message'] = __('User authentication failed. Please try again or contact an admin', CIP_TXTDOMAIN);
			}

		}
	}
	wp_send_json(
		$response,
		$status_code
	);
}