<?php
add_shortcode('SA-PACKAGES-LISTING-AUTHENTICATION-MANAGE', 'sa_packages_listing_authentication_manage_callback');
function sa_packages_listing_authentication_manage_callback(){
	$html = "";

	if( current_user_can('supportmanager') || current_user_can('supportagent') ){
        wp_enqueue_style( 'cip-css' );
        wp_enqueue_style( 'bs-table' );
        wp_enqueue_style( 'bs-sticky-header' );
        wp_enqueue_style('sa-packages-style',plugin_dir_url(__FILE__) . 'package-style.css', array(),'1.0', 'all');
		wp_enqueue_script('bs-table');
		wp_enqueue_script('bs-sticky-header');
		wp_enqueue_script('bs-table-filter-control');
        wp_enqueue_script('sa-packages-script', plugin_dir_url(__FILE__) . 'package-script.js', array('jquery'), '1.0', true);
		ob_start();
		?>
		<div class="modal fade" id="add_package_button_modal" tabindex="-1" role="dialog">
			<div class="modal-dialog modal-dialog-centered" role="document">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title">Add/Update SA Package</h5>
						<button type="button" class="close" data-dismiss="modal" aria-label="Close">
							<span aria-hidden="true">&times;</span>
						</button>
					</div>
					<div class="modal-body">
						<form id="saPackageForm">
							<input type="hidden" name="id" id="id" value="">
							<div class="mb-3">
								<label for="packageid">Amplivo Package ID*</label>
								<input type="number" name="packageid" id="packageid" class="form-control" placeholder="Enter Amplivo Package ID" required>
							</div>
							<div class="mb-3">
								<label for="euro_amount">Euro Amount*</label>
								<input type="text" name="euro_amount" id="euro_amount" class="form-control" placeholder="Enter Euro Amount" required>
							</div>
							<div class="mb-3">
								<label for="heading">Heading</label>
								<input type="text" name="heading" id="heading" class="form-control" placeholder="Enter Heading" required>
							</div>
							<div class="mb-3">
								<label for="description">Description*</label>
								<div class="notes-des">
									Note:
									<ul>
										<li>Use [kg] and [price] to display the product's Kgs and price.</li>
										<li> Use [BR] to move the subsequent text to a new line. </li>
									</ul>
								</div>
								<textarea  rows="3" name="description" id="description" class="form-control" placeholder="Enter Description" required></textarea>
							</div>
							<div class="mb-3">
								<label for="active"><input type="checkbox" name="active" id="active">Do you want to activate this package?</label>
							</div>
						</form>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-primary" id="savePackage">Save Package</button>
						<button type="button" class="btn btn-secondary" id="closePackage" data-dismiss="modal">Close</button>
					</div>
				</div>
			</div>
		</div>
		<button id="add_package_button" class="btn btn-primary">Add Package</button>
		<table id="sa_packages_listing_list" data-filter-control="true" data-show-search-clear-button="true" 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"><?php _e('ID', 'aac-helper-domain'); ?></th>
				<th data-field="packageid" class="packageid" data-filter-control="input"><?php _e('Amplivo Package ID', 'aac-helper-domain'); ?></th>

				<th data-field="heading" class="heading" data-filter-control="input"><?php _e('Heading', 'aac-helper-domain'); ?></th>
				<th data-field="description" class="description" data-filter-control="input"><?php _e('Description', 'aac-helper-domain'); ?></th>
				<th data-field="euro_amount" class="euro_amount" data-filter-control="input"><?php _e('Euro Amount', 'aac-helper-domain'); ?></th>
				<th data-field="active_inactive" class="active_inactive" data-filter-control="select" data-filter-data="var:selectChoices"><?php _e('Active/Inactive', 'aac-helper-domain'); ?></th>
				<th data-field="action" class="action"><?php _e('Action', 'aac-helper-domain'); ?></th>
			</tr>
		</thead>
		<tbody>
		</tbody>
		</table>
		<script>
			var selectChoices = {
				" ": "All",
				"1": "active",
				"0": "In-active"
			};
		</script>
		<?php
		$html .= ob_get_clean();
	}
	return $html;
}

// AJAX handler for adding/updating SA Packages
add_action('wp_ajax_handle_sa_package_form', 'handle_sa_package_form');
add_action('wp_ajax_nopriv_handle_sa_package_form', 'handle_sa_package_form'); // For non-logged-in users
function handle_sa_package_form() {
    global $wpdb;
    // Get form data sent via AJAX
    $form_data = isset($_POST['form_data']) ? wp_unslash($_POST['form_data']) : '';
    parse_str($form_data, $form_values); // Parse serialized form data into an array
	if($form_values['packageid'] == "" || $form_values['description'] == "" || $form_values['euro_amount'] == "" ){
		wp_send_json_error(array('message' => 'Please fill all required fields.'));
		die();
	}
    $package_name = isset($form_values['package_name']) ? sanitize_text_field($form_values['package_name']) : '';
    $euro_amount = isset($form_values['euro_amount']) ? floatval($form_values['euro_amount']) : 0;
	$euro_amount = $euro_amount;
    $heading = isset($form_values['heading']) ? sanitize_textarea_field($form_values['heading']) : '';
    $description = isset($form_values['description']) ? sanitize_textarea_field($form_values['description']) : '';
    $active = (isset($form_values['active']) && $form_values['active'] == 'on' ) ? 1 : 0;
    $package_id = isset($form_values['id']) ? intval($form_values['id']) : 0;
    $packageid = isset($form_values['packageid']) ? intval($form_values['packageid']) : 0;
	$existing_package = $wpdb->get_row(
		$wpdb->prepare(
			"SELECT id FROM {$wpdb->prefix}sa_packages WHERE packageid = %f AND id != $package_id",
			$packageid,
		)
	);

	if ($existing_package) {
		// The $packageid is already used in another row.
		// You may want to handle this situation, such as showing an error message.
		wp_send_json_error(array('message' => 'This package ID is already in use.'));
		die();
	}
	if($active == 1){
		$active_value = "Active";
	}else{
		$active_value = "In-active";
	}
    if ($package_id > 0) {
		$per_result = $wpdb->get_results($wpdb->prepare(
			"SELECT * FROM {$wpdb->prefix}sa_packages WHERE id = ".$package_id.""
		));
        // Update existing package
        $wpdb->update(
            $wpdb->prefix . 'sa_packages',
            array(
                'packageid' => $packageid,
                'euro_amount' => $euro_amount,
	            'heading' => $heading,
                'description' => $description,
                'active' => $active,
            ),
            array('id' => $package_id),
            array('%f','%d', '%s','%s','%f'),
            array('%d')
        );
		$data = array(
			'id' => $package_id,
			'packageid' => $packageid,
			'euro_amount' => $euro_amount,
			'heading' => $heading,
			'description' => $description,
			'active' => $active_value,
		);
		foreach($per_result as $row){
			$rowactive = ($row->active == 'active') ? 'Active' : 'In-active' ;
			$per_updatedata = array(
				'id' => $row->id,
				'packageid' => $row->packageid,
				'euro_amount' => $row->euro_amount,
				'heading' => $row->heading,
				'description' => $row->description,
				'active' => $rowactive,
			);
		}
		$updatedata = array(
			'id' => $package_id,
			'packageid' => $packageid,
			'euro_amount' => $euro_amount,
			'heading' => $heading,
			'description' => $description,
			'active' => $active,
		);
		$data_encoded = json_encode($data);
		$per_update_encoded = json_encode($per_updatedata);
		$log_type = 'packages_csr';
		$user = wp_get_current_user();
		$message = "changed package values ".$data_encoded." Previous values ".$per_update_encoded;

		create_cip_logs_entery( $user->ID, $log_type, '', 'sa', $message, true);
		wp_send_json_success(array('message' => 'Your package has been updated.','update' => $updatedata));
    } else {
        // Insert new package
        $result = $wpdb->insert(
            $wpdb->prefix . 'sa_packages',
            array(
				'packageid' => $packageid,
                'euro_amount' => $euro_amount,
                'heading' => $heading,
				'description' => $description,
				'active' => $active,
            ),
            //array('%f', '%d', '%s','%s','%f')
            array('%d', '%f', '%s', '%s', '%d')
        );
        if ($result === false) {

           wp_send_json_success(array('message' => 'Data was not inserted.'));
        } else {


            $data = array(
                'packageid' => $packageid,
                'euro_amount' => $euro_amount,
                'heading' => $heading,
                'description' => $description,
                'active' => $active_value,
            );
            $data_encoded = json_encode($data);
            $log_type = 'packages_csr';
            $user = wp_get_current_user();
            $message = "insert (".$data_encoded.") package";
            create_cip_logs_entery( $user->ID, $log_type, '', 'sa', $message, true);
            wp_send_json_success(array('message' => 'Your package has been add into packages.'));
        }
    }
	// echo $euro_amount;
    wp_die(); // Always use wp_die() at the end of your AJAX callback function
}

//edit package popup
add_action('wp_ajax_sa_get_packages_loader','sa_get_packages_loader_cb');
function sa_get_packages_loader_cb(){
	global $wpdb;
	$logTable = $wpdb->prefix.'sa_packages';
	$getLogs = $wpdb->get_results( "SELECT * FROM $logTable WHERE id = '".$_REQUEST['package_id']."'" );

	$rows = array();
	if( $getLogs ){
		$rowCounter = 1;
		foreach( $getLogs as $getLog ){
			$row = array(
				'id' => $getLog->id,
				'packageid' => $getLog->packageid,
				'euro_amount' => $getLog->euro_amount,
				'heading' => $getLog->heading,
				'description' => $getLog->description,
				'active' => $getLog->active,
				'action' => '<a id="editpackagesButton" data-packages-id="' . $getLog->id . '" class="mr-1" ><i class="fa fa-edit"></i></a><a id="delete_sa_package" data-packages-id="' . $getLog->id . '"><i class=" fa fa-trash"></i></a>'
			);
			if( !empty($getLog->active) ){

				if( $getLog->active == 1 ){
					$row['active_inactive'] = '<div class="form-check form-switch custom-control custom-switch"><input class="form-check-input custom-control-input packages-change" login_auth="yes" type="checkbox" data-id="'.$getLog->id.'" role="switch" id="packages_id_'.$getLog->id.'" checked="checked"><label class="form-check-label" for="packages_id_'.$getLog->id.'">Active</label></div>';
				}else{
					$row['active_inactive'] = '<div class="form-check form-switch custom-control custom-switch"><input class="form-check-input custom-control-input packages-change" login_auth="yes" type="checkbox" data-id="'.$getLog->id.'" role="switch" id="packages_id_'.$getLog->id.'"><label class="form-check-label" for="packages_id_'.$getLog->id.'">Inactive</label></div>';
				}
			}else{
				$row['active_inactive'] = '<div class="form-check form-switch custom-control custom-switch"><input class="form-check-input custom-control-input packages-change" login_auth="yes" type="checkbox" data-id="'.$getLog->id.'" role="switch" id="packages_id_'.$getLog->id.'"><label class="form-check-label" for="packages_id_'.$getLog->id.'">Inactive</label></div>';
			}
			$rows[] = $row;
			$rowCounter++;
		}
	}
	$out = array(
		'total'		=>	$total_items,
		'row'		=>	$row
	);
	echo wp_send_json_success( $row );
	exit;
}

//Delete package
add_action('wp_ajax_delete_sa_package', 'delete_sa_package');
add_action('wp_ajax_nopriv_delete_sa_package', 'delete_sa_package'); // For non-logged-in users
function delete_sa_package() {
    global $wpdb;
    $package_id = isset($_POST['package_id']) ? intval($_POST['package_id']) : 0;
	$per_result = $wpdb->get_results($wpdb->prepare(
		"SELECT * FROM {$wpdb->prefix}sa_packages WHERE id = ".$package_id.""
	));
	foreach($per_result as $row){
		$package_info = array(
			'Package id'=> $row->packageid,
			'Euro amount' => $row->euro_amount,
			'Description'=> $row->description
		);
	}
    if ($package_id > 0) {
        $wpdb->delete(
            $wpdb->prefix . 'sa_packages',
            array('ID' => $package_id),
            array('%d')
        );
        // Handle success or error messages as needed
        // echo 'Package deleted successfully!';
		$log_type = 'packages_csr';
		$user = wp_get_current_user();
		$message = "deleted ".json_encode($package_info)." package";
        create_cip_logs_entery( $user->ID, $log_type, '', 'sa', $message, true);
		wp_send_json_success(array('id' => $package_id,'message' => 'Your package has been remove form packages.'));
    } else {
        echo 'Invalid package ID!';
    }
    wp_die(); // Always use wp_die() at the end of your AJAX callback function
}

//Active/Inactive
add_action('wp_ajax_update_checkbox_packages_auth', 'update_checkbox_packages_auth');
add_action('wp_ajax_nopriv_update_checkbox_packages_auth', 'update_checkbox_packages_auth');
function update_checkbox_packages_auth() {
	global $wpdb;
    if (isset($_POST['user_id']) && isset($_POST['checkbox_value'])) {
        $package_id = sanitize_text_field($_POST['user_id']);
		$per_result = $wpdb->get_results($wpdb->prepare(
			"SELECT * FROM {$wpdb->prefix}sa_packages WHERE id = ".$package_id.""
		));
		foreach($per_result as $row){
			$package_info = array(
				'Package id'=> $row->packageid,
				'Euro amount' => $row->euro_amount,
				'Description'=> $row->description
			);
		}
        $checkbox_value = sanitize_text_field($_POST['checkbox_value']);

		$wpdb->update(
            $wpdb->prefix . 'sa_packages',
            array(
                'active' => $checkbox_value,
            ),
            array('id' => $package_id),
            array('%f'),
            array('%d')
        );
		if($checkbox_value == 1){
			$log_type = 'packages_csr';
			$user = wp_get_current_user();
			$message = "Activated ".json_encode($package_info)." package";
            create_cip_logs_entery( $user->ID, $log_type, '', 'sa', $message, true);
			wp_send_json_success(array('message' => 'Your package has been Activated.'));
		}else{
			$log_type = 'packages_csr';
			$user = wp_get_current_user();
			$message = "In-activated ".json_encode($package_info)." package";
            create_cip_logs_entery( $user->ID, $log_type, '', 'sa', $message, true);
			wp_send_json_success(array('message' => 'Your package has been In-Activated.'));
		}
        die(); // Important to terminate the AJAX request properly.
    }
}

add_action('wp_footer', 'acc_bsdatatable_script');
function acc_bsdatatable_script(){
	$sa_packages_listing_list_url = add_query_arg( [
		'action'	=>	'sa_packages_listing_list_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	?>
	<script>
	jQuery(document).ready(function($){
		if( $('#sa_packages_listing_list').length > 0 ){
			var sa_packages_listing_list_url = "<?php echo $sa_packages_listing_list_url ?>";
			var $tablePendinReview = $('#sa_packages_listing_list');
			$tablePendinReview.bootstrapTable({
				method: 'post',
				contentType: 'application/x-www-form-urlencoded',
				url: sa_packages_listing_list_url,
				queryParams: function (p) {
					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);
				}
			});
		}
	});
  	</script>
  <?php
}
add_action('wp_ajax_sa_packages_listing_list_loader','sa_packages_listing_list_loader_cb');
function sa_packages_listing_list_loader_cb(){
	global $wpdb;

	$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';

	$logTable = $wpdb->prefix.'sa_packages';
	$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';

	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $logTable WHERE 1=1");


	$filter_qry = "";
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == 'user_type'  ){
				$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
			}elseif($filterKey == 'active_inactive'){
				$filter_qry .= " AND `active` = '" . $filterData . "'";
			}else{
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $logTable WHERE 1=1 $filter_qry");
	}
	$filterByConditionPoolRef = json_decode( stripslashes( $_REQUEST['filterByConditionPoolRef'] ), true );

	if( !empty( $filterByConditionPoolRef ) ){
		foreach( $filterByConditionPoolRef as $filterKey => $filterData ){
			if($filterData != ''){
				$filter_qry .= " AND `logs` like '%" . $filterData . "%'";
			}
		}
	}
	if($filter_qry != ""){
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $logTable WHERE 1=1 $filter_qry");
	}
	$getLogs = $wpdb->get_results( "SELECT * FROM $logTable WHERE 1=1 $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset" );

	$rows = array();
	if( $getLogs ){
		$rowCounter = 1;
		foreach( $getLogs as $getLog ){

            // echo'<pre>';
            // print_r($getLog);
            // echo'</pre>';

			$description_array = explode("[BR]",$getLog->description);
			$getLogdescription = '';
			foreach($description_array as $description_item){
				if($description_item != ''){
					$getLogdescription .= sprintf( __('<span><strong class="text-danger">*</strong>  %s</span><br>', CIP_TXTDOMAIN), trim($description_item) );
				}
			}

			$row = array(
				'id' => $getLog->id,
				'packageid' => $getLog->packageid,
				'euro_amount' => number_format( $getLog->euro_amount ),
				'heading' => $getLog->heading,
				'description' => $getLogdescription,
				'action' => '<a id="editpackagesButton" data-packages-id="' . $getLog->id . '" class="mr-1" ><i class="fa fa-edit"></i></a><a id="delete_sa_package" data-packages-id="' . $getLog->id . '"><i class=" fa fa-trash"></i></a>'
			);
			if( !empty($getLog->active) ){
				if( $getLog->active == 1 ){
					$row['active_inactive'] = '<div class="form-check form-switch custom-control custom-switch"><input class="form-check-input custom-control-input packages-change" login_auth="yes" type="checkbox" data-id="'.$getLog->id.'" role="switch" id="packages_id_'.$getLog->id.'" checked="checked"><label class="form-check-label" for="packages_id_'.$getLog->id.'">Active</label></div>';
				}else{
					$row['active_inactive'] = '<div class="form-check form-switch custom-control custom-switch"><input class="form-check-input custom-control-input packages-change" login_auth="yes" type="checkbox" data-id="'.$getLog->id.'" role="switch" id="packages_id_'.$getLog->id.'"><label class="form-check-label" for="packages_id_'.$getLog->id.'">Inactive</label></div>';
				}
			}else{
				$row['active_inactive'] = '<div class="form-check form-switch custom-control custom-switch"><input class="form-check-input custom-control-input packages-change" login_auth="yes" type="checkbox" data-id="'.$getLog->id.'" role="switch" id="packages_id_'.$getLog->id.'"><label class="form-check-label" for="packages_id_'.$getLog->id.'">Inactive</label></div>';
			}
			$rows[] = $row;
			$rowCounter++;
		}
	}
	$out = array(
		'total'		=>	$total_items,
		'rows'		=>	$rows
	);
	echo wp_json_encode( $out );
	exit;
}