<?php
if (! defined('ABSPATH') ) { exit; // Exit if accessed directly
}
include_once dirname(__FILE__) . '/class-quotes-list-table.php';
class SCCQuoteListView {
	public $quotes_from_id;
	public $quote_status;
	private $disableIPandBrowserColumn;
	public function get_calculator_name() {
		global $wpdb;
		$name = $wpdb->get_results("SELECT formname FROM `{$wpdb->prefix}scc_forms` WHERE id={$this->quotes_from_id}");
		return $name[0];
	}
	public function __construct() {
		add_action('admin_menu', array( $this,'admin_menu' ), 90);
		add_action('wp_ajax_scc_save_quote_management_table_columns_filter', array( $this,'saveQuoteManagementTableColumnsFilter' ) );
		add_action('wp_ajax_scc_save_individual_quote_status', array( $this,'saveIndividualQuoteStatus' ) );
		add_action('wp_ajax_scc_delete_quote', array( $this,'handleDbQuoteDeletion' ) );
		add_action(
			'admin_head', function () {
				remove_submenu_page('scc-tabs', 'df-scc-view-quotes');
			}
		);
        // add_action('wp_ajax_scc_stripe_action', array( $this,'handleSubmit' ) );
        // add_action('wp_ajax_nopriv_scc_stripe_action', array( $this,'handleSubmit' ) );
	}
	function page() {
		wp_register_style('scc-select2', SCC_URL . 'assets/lib/tom-select.css', array(), STYLISH_COST_CALCULATOR_PREMIUM_VERSION);
		wp_register_script('scc-select2', SCC_URL . 'assets/lib/tom-select.complete.min.js', array(), STYLISH_COST_CALCULATOR_PREMIUM_VERSION);
		wp_register_style('scc-sweetalert', SCC_URL . 'assets/lib/sweetalert2.min.css', array(), STYLISH_COST_CALCULATOR_PREMIUM_VERSION);
		wp_register_script('scc-sweetalert', SCC_URL . 'assets/lib/sweetalert2.min.js', array(), STYLISH_COST_CALCULATOR_PREMIUM_VERSION);
		wp_register_style('scc-bootstrap-min', SCC_URL . 'assets/lib/bootstrap-3.4.1/dist/css/bootstrap.min.css');
		wp_register_script('scc-boottrap-min', SCC_URL . 'assets/lib/bootstrap-3.4.1/dist/js/bootstrap.min.js', array('jquery'), STYLISH_COST_CALCULATOR_PREMIUM_VERSION, true);
        wp_register_style('gf-admin-style', SCC_URL  . 'styles/scc-back-end.css', array(), STYLISH_COST_CALCULATOR_PREMIUM_VERSION);
		
		wp_enqueue_script('wp-util');
		wp_enqueue_script('scc-bootstrap-min');
		wp_enqueue_style('scc-bootstrap-min');
		wp_enqueue_style('gf-admin-style');
		wp_enqueue_style('dashicons');
		wp_enqueue_style('scc-select2');
		wp_enqueue_script('scc-select2');
		wp_enqueue_style('scc-sweetalert');
		wp_enqueue_script('scc-sweetalert');
		wp_enqueue_script('jquery-ui-dialog');
		wp_enqueue_style('wp-jquery-ui-dialog');
		if (isset($_GET['id'])) {
			$this->quotes_from_id = absint($_GET['id']);
			// setting up status
			$this->quote_status = array(
				array("closed" => "New (Not Connected)"),
				array("replied-nconnected" => "Replied (Not Connected)"),
				array("unqualified-nconnected" => "UnQualified (Not Connected)"),
				array("qualified-connected" => "Qualified (Connected)"),
				array("qualified-unassigned" => "Qualified (Un-Assigned)"),
				array("qualified-assigned" => "Qualified (Assigned)"),
				array("in-discussion-connected" => "In-Neogotiation (Connected)"),
				array("follow-up-later" => "Follow-Up Later (Connected)"),
				array("closed-won" => "Closed (Won)"),
				array("closed-lost" => "Closed (Lost)")
			);
		} else {
			echo "Bad parameters";
			return;
		}
		add_action( 'scc_get_quote_form_fields', array( $this, 'get_field_params' ), 7, 1 );
		// get table column data from the quote fields
		do_action('scc_get_quote_form_fields', 'placeholder');
		// load the entries
		$this->load_entries_list_table($this->quotes_from_id);
		?>
		<?php include_once SCC_DIR . '/admin/logo-header.php'; ?>
		<link rel="preconnect" href="https://fonts.gstatic.com">
		<link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
		<div style="background-color: #314af3;margin: 0px 0px 10px -20px;display: flex;"><h1 style="color:white;padding-left:35px;margin: 30px 0;">Quotes from <?php echo $this->get_calculator_name()->formname; ?></h1></div>
		<?php
		?>
		<div id="quotes" class="container-fluid">
			<?php if ( true ) : ?>
				<div id="table" style="margin-top: 30px;">
					<?php
					echo wp_kses(
						sprintf( /* translators: %s - number of entries found. */
							_n(
								'Found <strong>%s entry</strong>',
								'Found <strong>%s entries</strong>',
								absint( $this->crm_table->total_items ),
								'scc'
							),
							absint( $this->crm_table->total_items )
						),
						[
							'strong' => [],
						]
					);
					?>
				</div>
				<div class="row">
					<div class="col-xs-12 col-md-12 col-lg-12">
						<a class="btn btn-settings-bar" style="color:white;background-color: #20319f;padding: 10px 30px;font-weight: 500;text-transform: uppercase;
						font-size: 15px;letter-spacing: 0.5px;" href="<?php echo admin_url("admin.php?page=edit_sccbyid&id={$_GET['id']}") ?>">Edit Calculator</a>
					</div>
				</div>
			<?php endif ?>
			<?php $this->crm_table->display(); ?>
		</div>
		<div id="filter-fields-options" style="display: none;" title="choose fields you want to show in the table">
		</div>
		<style>
			.swal2-actions {
				z-index: unset !important;
			}
			.swal2-title {
				font-size: 1.575rem!important;
			}
			.swal2-content .items.ts-input.full.has-items {
				text-align: left;
			}
			.input-hidden .items input {
				display: none !important;
			}
			#the-list tr > td {
				vertical-align: middle;
			}
			th#actions, td.actions.column-actions {
				width: 10%;
			}
			#date_created, .date_created .column-date_created {
				width: 10%;
			}
		</style>
		<script id="page-params"><?php echo 'var settings =' . json_encode(array(
			"id" => $this->quotes_from_id,
			"formFields" => json_encode($this->formFields),
			"formFieldsToShow" => json_encode($this->formFieldsToShow),
			"quoteStatuses" => json_encode($this->quote_status),
			"iPandBrowserColumn" => json_encode(absint($this->disableIPandBrowserColumn || 1))
			)) ?></script>
			<script>
				console.log('xyzzzzzz');
				let formFields = JSON.parse(settings.formFields);
				let formFieldsToShow = JSON.parse(settings.formFieldsToShow);
				formFields = Object.entries(formFields).map(ee => ({value: ee[0], text: ee[1]}))
				// formFieldsShown =
				var pageParameters;
				function handleViewClick($this) {
					let quoteId = jQuery($this).data('submissionId');
					let calculatorId = settings.id;
					jQuery.ajax({
						url: wp.ajax.settings.url,
						type: 'POST', //jQuery('#previewInputsAdd').html().trim()
						context: $this,
						data: {
							action: 'preGeneratedQuoteDownload',
							data: {quoteId, calculatorId}
						},
						success: function(b64){
							const linkSource = `data:application/pdf;base64,${b64.data}`;
							const downloadLink = document.createElement("a");
							let quotePersonName = jQuery(this).closest('tr').find('td.name')[0].innerText;
							let quoteCreationDate = jQuery(this).closest('tr').find('td.date_created')[0].innerText
							const fileName = quotePersonName+' '+ quoteCreationDate+ ".pdf";
							downloadLink.href = linkSource;
							downloadLink.download = fileName;
							downloadLink.click();
						},
					})
					// preGeneratedQuoteDownload
				}
				function handleQuoteDeletion($this) {
					let quoteId = jQuery($this).data('quoteId');
					Swal.fire({
						title: '<strong>Are you sure? You want to delete this quote?</strong>',
						showCancelButton: true
					}).then((result) => {
						var srcQuoteRow = jQuery($this).closest('tr');
						if (result.isConfirmed) {
							jQuery.ajax({
								url: wp.ajax.settings.url,
								type: 'POST', //jQuery('#previewInputsAdd').html().trim()
								data: {
									action: 'scc_delete_quote',
									quoteId
								},
								success: function(status){
									if (status.successful) {
										srcQuoteRow.hide(2000);
									}
								},
							});
						}
					});
				}
				jQuery(document).ready(($) => {
					$('#filter-fields').on('click', ($this) => {
						console.log($this.currentTarget);
						Swal.fire({
							title: '<strong>Columns Customizer</strong><br>',
							html: `<select placeholder="click here to select the columns" class="quote-columns-filter" multiple="multiple">
							</select>
							<input type="checkbox" id="disable-ip-ua" ${parseInt(settings.iPandBrowserColumn) ? 'checked' : ''}>
							<label style="font-size: 0.9rem;" for="disable-ip-ua">Disable Browser and IP address column</label>`,
							didRender: () => {
								let config = {
									plugins: ['remove_button'],
									closeAfterSelect: true,
									options: formFields,
									items: Object.keys(formFieldsToShow)
								};
								new TomSelect('.quote-columns-filter',config);
							},
							showCancelButton: true,
							confirmButtonText: "Save",
							confirmButtonColor: '#314af3',
							cancelButtonText: "Cancel",
							preConfirm: console.log
						}).then((result) => {
							if (result.isConfirmed) {
								let choosenColumns = jQuery('select.quote-columns-filter').val();
								// finding the columns which were not choosen
								let hiddenColumns = formFields.map(fieldItem => fieldItem.value).filter(ee => !choosenColumns.some(e => e == ee));
								let calculatorId = settings.id;
								let disableIPandBrowserColumn = jQuery('#disable-ip-ua').prop('checked') ? 1 : 0;
								jQuery.ajax({
									url: wp.ajax.settings.url,
									type: 'POST', //jQuery('#previewInputsAdd').html().trim()
									data: {
										action: 'scc_save_quote_management_table_columns_filter',
										data: {choosenColumns, hiddenColumns, calculatorId, disableIPandBrowserColumn}
									},
									success: function(b64){
										window.location = window.location
									},
								});
							}
						})
						// $('#filter-fields-options').dialog({
						// 	minWidth: 500,
						// 	open: function () {
						// 		var config = {};
						// 		new TomSelect('.js-example-basic-multiple',config);
						// 	}
						// });
						// $('.js-example-basic-multiple').select2();
					})
					let config = {
						options: JSON.parse(settings.quoteStatuses).map(e => {return {value: Object.keys(e)[0], text: Object.values(e)[0]}}),
						placeholder: "Select a tag",
						hidePlaceholder: true,
						onChange:function(selected){
							let srcQuoteId = jQuery(this.input).data('quoteId');
							jQuery.ajax({
								url: wp.ajax.settings.url,
								type: 'POST', //jQuery('#previewInputsAdd').html().trim()
								data: {
									action: 'scc_save_individual_quote_status',
									data: { statusTag: selected, quoteId: srcQuoteId }
								},
								success: function(status){
								},
							});
						}
					}
					jQuery('select.quote-status-setup').each((index, element) => {
						let selected = jQuery(element).data('selectedKey')
						if (selected.length) {
							config.items = selected
						}
						let select = new TomSelect(element, config);
					})
					// pageParameters = jQuery('#page-params').html().trim();
				})
			</script>
			<?php
        // $this->crm_table->display();
        // $crm_table = new QuoteListTable();
        // $crm_table->prepare_items();
        // $crm_table->display();
		}
		public function get_field_params() {
			global $wpdb;
		// gets custom quote fields and processes them to a key value pairs
			$formParams = stripslashes_deep($wpdb->get_results("SELECT parameters FROM {$wpdb->prefix}scc_form_parameters WHERE {$wpdb->prefix}scc_form_parameters.form_id={$this->quotes_from_id};")[0]->parameters);
			$formParams = json_decode($formParams);
			$disableIPandBrowserColumn = isset($formParams->disableIPandBrowserColumn) ? $formParams->disableIPandBrowserColumn : 1;
			$showReferingPage = isset($formParams->show_referer) ? $formParams->show_referer : 1;
			$this->disableIPandBrowserColumn = $disableIPandBrowserColumn;
		// if the custom fields not found a default set of fields are presented
			if(isset($formParams->formFieldsArray) && count(json_decode($formParams->formFieldsArray)))
			{
				$formFields = json_decode($formParams->formFieldsArray);
			} else {
				$formFields = json_decode('[{"name":{"name":"Your Name","description":"Type in your name","type":"text","isMandatory":null,"trnKey":"Your Name","deletable":false}},{"email":{"name":"Your Email","description":"Type in your email","type":"email","isMandatory":null,"trnKey":"Your Email","deletable":false}},{"phone":{"name":"Your Phone","description":"phone","type":"phone","isMandatory":null,"trnKey":"Your Phone (Optional)","deletable":false}}]');
			}
			if (!function_exists('tableColsKV')) {
				function tableColsKV($cc)
				{
					$key = array_keys(get_object_vars($cc))[0];
					$value = $cc->{$key}->name;
					return [$key => $value];
				}
			}
			// add the ip and browser to the columns
			// $formFields
		// filters and sets the key and name pairs
			$tmp_table_head = array_map('tableColsKV', $formFields);
			$table_cols = array("referer" => "Referring Page");
			for ($i=0; $i < count($tmp_table_head); $i++) {
				$table_cols+= $tmp_table_head[$i];
			};
			if (!function_exists('shownTableHeadKV')) {
				function shownTableHeadKV($cc)
				{
					$key = array_keys(get_object_vars($cc))[0];
					$value = $cc->{$key}->name;
					if (isset($cc->{$key}->showOnTable) && !$cc->{$key}->showOnTable) {
						return;
					}
					return [$key => $value];
				}
			}
		// filters and sets the key and name pairs
			$tmp_table_head_to_show = array_map('shownTableHeadKV', $formFields);
		// $tmp_table_head_to_show = array_filter($tmp_table_head_to_show, function($value) { return !is_null($value) && $value !== ''; });
			$table_cols_to_show = array();
			for ($i=0; $i < count($tmp_table_head_to_show); $i++) {
				if (isset($tmp_table_head_to_show[$i])) {
					$table_cols_to_show+= $tmp_table_head_to_show[$i];
				}
			};
			if (!$disableIPandBrowserColumn) {
				$table_cols_to_show['browser'] = "Browser";
				$table_cols_to_show['user_ip'] = "User IP";
			}
			if ($showReferingPage) {
				$table_cols_to_show['referer'] = "Referring Page";
			}
		// field ID and it's name passed to create column headers
			$this->formFields = $table_cols;
			$this->formFieldsToShow = $table_cols_to_show;

		}
		public function load_entries_list_table($quotes_from_id) {
			$this->crm_table = new QuoteListTable();
			$this->crm_table->form_id = $quotes_from_id;
			$this->crm_table->quote_status = $this->quote_status;
			$this->crm_table->quote_form_fields = $this->formFieldsToShow;
			$this->crm_table->prepare_items();
		}
		function admin_menu() {
			add_submenu_page('scc-tabs', 'Quote Viewer', null, 'manage_options', 'df-scc-view-quotes', array( $this, 'page' ));
        // add_submenu_page('scc-tabs', 'Stripe Test', 'Stripe Testa', 'manage_options', 'stripe-test', array( $this, 'page' ));
		}
		function saveQuoteManagementTableColumnsFilter()
		{
			global $wpdb;
			$data = $_POST['data'];
			$calculatorId = $data['calculatorId'];
			$disableIPandBrowserColumn = isset($data['disableIPandBrowserColumn']) ? $data['disableIPandBrowserColumn'] : 1;
		// fetch form parameters
			$formParams = stripslashes_deep($wpdb->get_results("SELECT parameters FROM {$wpdb->prefix}scc_form_parameters WHERE {$wpdb->prefix}scc_form_parameters.form_id={$calculatorId};")[0]->parameters);
			$rawFormFieldData = json_decode($formParams, true);
			$rawFormFieldData = isset($rawFormFieldData['formFieldsArray']) ? $rawFormFieldData['formFieldsArray'] : '';
			if (empty($rawFormFieldData)) {
				$rawFormFieldData = '[{"name":{"name":"Your Name","description":"Type in your name","type":"text","isMandatory":null,"trnKey":"Your Name","deletable":false}},{"email":{"name":"Your Email","description":"Type in your email","type":"email","isMandatory":null,"trnKey":"Your Email","deletable":false}},{"phone":{"name":"Your Phone","description":"phone","type":"phone","isMandatory":null,"trnKey":"Your Phone (Optional)","deletable":false}}]';
			}
			$formFieldData = json_decode($rawFormFieldData, true);
			for ($i=0; $i < count($formFieldData); $i++) {
			// find the field key
				$fieldKey = array_keys($formFieldData[$i])[0];
			// check if the field key exists in the hidden columns, if matches, we set the 'showOnTable' property false on it
				if (isset($data['hiddenColumns']) && in_array($fieldKey, $data['hiddenColumns'])) {
					$val = $formFieldData[$i][$fieldKey];
					$val['showOnTable'] = false;
					$formFieldData[$i][$fieldKey] = $val;
				} else {
					$val = $formFieldData[$i][$fieldKey];
					$val['showOnTable'] = true;
					$formFieldData[$i][$fieldKey] = $val;
				}
			}
		// flush the newly formed form Table data to the database
			$formParams = json_decode($formParams, true);
			$formParams['formFieldsArray'] = addslashes(json_encode($formFieldData));
			$formParams['disableIPandBrowserColumn'] = $disableIPandBrowserColumn;
			// we set show referer to false if it was included in the hiddencolumns
			if (isset($data['hiddenColumns']) && in_array('referer', $data['hiddenColumns'])) {
				$formParams['show_referer'] = 0;
			} else {
				$formParams['show_referer'] = 1;
			}
		    // json encode it before flushing new parameters
			$formParams = wp_json_encode($formParams);
			// checking for corrupted parameter
			$isValidParams = count(json_decode($formParams, true)) > 10;
			if ($isValidParams) {
				$query = $wpdb->prepare("UPDATE {$wpdb->prefix}scc_form_parameters SET parameters = %s WHERE form_id = %d LIMIT 1", $formParams, $calculatorId);
				$wpdb->query($query);
			}
			wp_send_json($data);
		}
		public function saveIndividualQuoteStatus()
		{
			global $wpdb;
			$data = $_POST['data'];
		// TODO save it to a proper quote submission
			$query = $wpdb->prepare("UPDATE {$wpdb->prefix}scc_quote_submissions SET status = %s WHERE id = %d LIMIT 1", $data['statusTag'], $data['quoteId']);
			$wpdb->query($query);
		}
		public function handleDbQuoteDeletion()
		{
			global $wpdb;
			$quoteId = $_POST['quoteId'];
			$query = $wpdb->prepare("DELETE FROM {$wpdb->prefix}scc_quote_submissions WHERE id = %d", $quoteId);
			$status = $wpdb->query($query);
			if ($status) {
				wp_send_json(array(
					"successful" => true
				));
			}
		}
	}
	new SCCQuoteListView();