<?php
	if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
	if(isset($_GET["page"]) == "scc-tabs" || isset($_GET["page"]) == "Stylish_Cost_Calculator_EditItems" || isset($_GET["page"]) == "edit_sccbyid" || isset($_GET["page"]) == "stylish_cost_calculator_Diagnostic" || isset($_GET["page"]) == "stylish_cost_calculator_help" || isset($_GET["page"]) == "stylish_cost_calculator_settings"  || isset($_GET["page"]) == "Stylish_Cost_Calculator_Coupon"){
		// wp_enqueue_style('gf-admin-style', SCC_URL. 'styles/scc-back-end.css', array(), '3.1.6');
	}
	require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
	class Stylish_Cost_Calculator_EditItems {
		// var $license_return ='';
		public function __construct() {
			add_action( 'admin_init', array($this,'admin_init') );
			add_action( 'admin_head', function() {
				remove_submenu_page( 'index.php', 'edit_sccbyid' );
			});
			add_action( 'admin_menu', array($this,'admin_menu'), 90 );
		}
		function admin_init()
		{
			global $wpdb;
			$results = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}scc_forms", OBJECT);
			return $results;
		}
		function editOneItem()
		{
			global $wpdb;
			$id = (int)isset($_GET['id']) ? intval($_GET['id']) : 0;
			if ($id == 0) { echo "<br /><p>ERROR - id $id is not numeric</p>"; die(); }
			$result = $wpdb->get_row($wpdb->prepare("SELECT id, formname, formstored, description,formtranslate FROM {$wpdb->prefix}scc_forms WHERE id = %d LIMIT 1", array($id)));
				$allinputstoadd = $result;//->ajaxform;
				if ($allinputstoadd) {
					$result_2 = $wpdb->get_row($wpdb->prepare("SELECT parameters FROM {$wpdb->prefix}scc_form_parameters WHERE form_id = %d LIMIT 1", array($allinputstoadd->id)));
				}
				// register and enqueue backend script before loading the existing calculator page
				wp_register_script('scc-backend', SCC_URL . 'assets/js/scc-backend.js', array('jquery'), STYLISH_COST_CALCULATOR_VERSION , true);
        		wp_enqueue_script('scc-backend');
				include_once('edit-existing-calculator.php');
			}
			function shortCodeTableExists() {
				global $wpdb;
				$table_name = "scc_shortcodes";
				$table = $wpdb->prefix . $table_name;
				

				if($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table)) != $table) {
					$scctables = "CREATE TABLE IF NOT EXISTS `{$table}` (
					`id` int(11) NOT NULL AUTO_INCREMENT,
					`scc_id` int(11) NOT NULL,
					`url` text NOT NULL,
					`visits` int(11) NOT NULL,
					PRIMARY KEY (`id`)
				) ENGINE=InnoDB  DEFAULT  CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;";
				dbDelta( $scctables);

			}else{
				
			}
		}
		function editItems()
		{
			include_once SCC_DIR . '/admin/logo-header.php';
			wp_enqueue_script('wp-util');
			wp_enqueue_style('scc-admin-style');
			?>
			<link rel="preconnect" href="https://fonts.gstatic.com">
			<link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
			<style>
				.button_show_urls {
					position:relative;
					left:30%;
					right:30%;
					top:30%;
					bottom:30%;
					background: #314af3;
					color:white;
					border-radius:5px;
					padding:10px;
					}thead, tbody { width:100%;display: block; }

					tbody {
						height: 150px;       /* Just for the demo          */
						overflow-y: auto;    /* Trigger vertical scroll    */
						overflow-x: hidden;  /* Hide the horizontal scroll */
					}
					table {
						font-family: arial, sans-serif;
						border-collapse: collapse;
						width: 100%;
					}

					td, th {
						border: 1px solid #dddddd;
						text-align: center;
						padding: 8px;
					}

					tr:nth-child(even) {
						background-color: #dddddd;
					}
					.scc_title_bar {
						background: #314af3;
						padding: 15px;
						padding-left: 45px;
						padding-left: 45px;
						margin-left: -23px;
						font-size: 22px;
						color: #fff;
						letter-spacing: 1px;
						text-transform: uppercase;
						width: 105%;
						margin-bottom: 40px;
						margin-top: 10px;
					}
				</style>
				<?php self::shortCodeTableExists(); ?> 
				<div id="scc-demover" data-demo="<?php echo get_option('scc_licensed');?>"></div>
				<h1 style="height:1px; margin:0px; padding:0px;"></h1>
				<div class="scc_title_bar" style="background: #314af3;max-width: 3000px;">Edit Item Lists</div>
				<div class="panel-group" id="accordion1">
					<div class="scc_wrapper">
						<?php $items = $this->admin_init();   ?>
						<?php
						$ii = 0;
						foreach ($items as $itm){
							$theInputs = json_decode( str_replace('\"', '"', $itm->formstored) ) ;
							?>
							<div class="forms2edit col-xs-12 col-md-5" id="bigforms2edit<?php echo $itm->id; ?>">
								<?php if ( 1 == 2) { ?><a class='forms2edit_a' href="<?php echo get_admin_url();?>?page=edit_sccbyid&id=<?php echo htmlspecialchars(($itm->id),ENT_QUOTES); ?>"><?php echo $itm->formname; ?></a>
								<?php
							}?>
							<h2 class="edith2"><?php echo stripslashes($itm->formname); ?></h2>
							<?php
							$fieldsArray = [];

							?>
							<p class="custom-short-code-p-tag">
								
								Shortcode is <strong>[scc_calculator type='text' idvalue='<?php echo htmlspecialchars(($itm->id),ENT_QUOTES); ?>']</strong>
							</p>
							<div  style="height:100%;min-height:100px;padding:20px;"  >
								<?php 
								global $wpdb;
								$table_name = "scc_shortcodes";
								$table = $wpdb->prefix . $table_name;
								
								$shortcodes = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}scc_shortcodes WHERE scc_id = %d", array($itm->id)));
								if(!empty($shortcodes)){
									?> 
									<table class="scc-urls-table" style="display:none">
										<thead>
											<tr>
												<th >URL</th>
												<th>Visits</th>
											</tr>
										</thead>
										<tbody >
											<?php
											foreach ($shortcodes as $sc) { 
												if(strpos($sc->url, 'preview') !== false) {

												}else{
													?>
													<tr>
														<td> <a target="_blank" href="<?php echo $sc->url ?>"><?php echo $sc->url ?></a></td>
														<td> <?php echo $sc->visits ?></td>
													</tr>
													<?php
												}
											}
											?> 
										</tbody>
									</table> 
									<?php
								}else {
									echo "<p style='text-align: center;position:relative;padding-top:20px;'> No pages containing this calculator yet </p>";
								}
								?>
							</div>
							<p style="margin: 0 0 10px 20px;position: absolute;bottom: 20px;">
								<a class="opt-secondary" style="color: orange;" href="<?php echo get_admin_url();?>?page=edit_sccbyid&id=<?php echo htmlspecialchars(($itm->id),ENT_QUOTES); ?>">Edit</a>

								<a style="" class="opt-secondary" onClick="deleteSCC(<?php echo $itm->id; ?>)" href="javascript:void(0)">Delete</a>
								<?php if(!empty($shortcodes)){ ?>

									<a style="" class="opt-secondary" onclick="showUrlsPopup(this)" href="javascript:void(0)">URLs</a>
								<?php } ?>
							</p>

							<div style="margin-bottom: 70px;margin-left: 20px;" class="yesnoeditscc" id="yesnoeditscc_<?php echo $itm->id; ?>"><span class="yesnoeditINN" id="yesnoeditINN_<?php echo $itm->id; ?>">YES</span> | <span class="yesnoeditINN">NO</span></div>
							
						</div>
						<?php
						$ii++;
					} ?>

					<div id="renderForm"></div>
					<div  class="modal df-scc-modal fade in" role="dialog" id="show-calc-urls-container"></div>
					<?php
					include_once SCC_DIR . '/admin/logo-footer.php';
					?>
					</div>    
					<!-- add template here -->
					<script type="text/html" id="tmpl-show-calc-urls">
					<div class="df-scc-euiOverlayMask df-scc-euiOverlayMask--aboveHeader">
					<div class="df-scc-euiModal df-scc-euiModal--maxWidth-default df-scc-euiModal--confirmation">
					<button class="df-scc-euiButtonIcon df-scc-euiButtonIcon--text df-scc-euiModal__closeIcon" type="button" data-dismiss="modal"><svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" class="df-scc-euiIcon df-scc-euiIcon--medium df-scc-euiButtonIcon__icon" focusable="false" role="img" aria-hidden="true">
					<path d="M7.293 8L3.146 3.854a.5.5 0 11.708-.708L8 7.293l4.146-4.147a.5.5 0 01.708.708L8.707 8l4.147 4.146a.5.5 0 01-.708.708L8 8.707l-4.146 4.147a.5.5 0 01-.708-.708L7.293 8z">
					</path>
					</svg></button>
					<div class="df-scc-euiModal__flex">
					<div class="df-scc-euiModalHeader">
					<div class="df-scc-euiModalHeader__title">{{data.title}}</div>
					</div>
					<div class="df-scc-euiModalBody">
					<div class="df-scc-euiModalBody__overflow">
					<div class="df-scc-euiText df-scc-euiText--medium">
					<div id="table-data-container"></div>
					<p class="trn text-danger" style="display:none;">There has been an error. Try again</p>
					</div>
					</div>
					</div>
					</div>
					</div>
					</div>
					</script>
					<script>
					async function showUrlsPopup($this) {
						let srcElement = jQuery($this);
						window.srcElement = srcElement;
						let tableHtml = srcElement.closest('.forms2edit').find('.scc-urls-table')[0];
						let urlPopupContainer = scc_jQuery('#show-calc-urls-container');
						let urlPopupHtml = await wp.template("show-calc-urls")({title: "Please Fill up this form"});
						if(urlPopupHtml) {
							urlPopupContainer.html(urlPopupHtml);
							urlPopupContainer.on("show.bs.modal", function () {
								jQuery('#table-data-container').html(tableHtml).children('table').show();
								setTimeout(() => {
									alignTableColumns();
								}, 1000);
							}).modal('show');
						}
					}
					function showUrl(element) {
						jQuery(element).closest('.forms2edit').find('table').show();
			// jQuery(element).next().css("display","block")
			// jQuery(element).remove()
						alignTableColumns()
					}
					function alignTableColumns() {
						var $table = jQuery('table'),
						$bodyCells = $table.find('tbody tr:first').children(),
						colWidth;

			// Get the tbody columns width array
						colWidth = $bodyCells.map(function() {
							return jQuery(this).width();
						}).get();

			// Set the width of thead columns
						$table.find('thead tr').children().each(function(i, v) {
							jQuery(v).width(colWidth[i]);
						});   
					}
					function deleteSCC(id)
					{
						jQuery('.yesnoeditscc').fadeOut();
						jQuery('#yesnoeditscc_' + id).fadeIn();
					}
					jQuery('.yesnoeditINN').click(function()
					{
						var opt = jQuery(this).html();
						if (opt.toLowerCase() == 'no') {  }
							else
							{
								var theid = jQuery(this).parent().attr('id').replace('yesnoeditscc_', '');
								$fragment_refresh =
								{
									url: rt_vars.rt_urlajax,
									type: 'POST',
									data: { action: 'sccSaveDel', id: theid },
									success: function( data ) { }
								};
								jQuery.ajax( $fragment_refresh );
								jQuery('#bigforms2edit' + theid).remove();
							}
							jQuery('.yesnoeditscc').fadeOut();
						} );
					</script>
					<?php
				}
				function admin_menu()
				{
					add_submenu_page('index.php', __( 'Edit Calculator Item', 'scc' ), __( 'Edit Calculator Item', 'scc' ), 'manage_options', 'edit_sccbyid', array( $this, 'editOneItem' ) );
					$submenu_edit_existing = add_submenu_page( 'scc-tabs', __( 'Edit Existing', 'scc' ), __( 'Edit Existing', 'scc' ), 'manage_options', 'Stylish_Cost_Calculator_EditItems', array( $this, 'editItems' ) );

					add_action( 'admin_print_styles-' . $submenu_edit_existing, array($this, 'edit_existing_page_style') );
		//        add_submenu_page( 'scc-tabs', __( 'Diagnostic', 'scc' ), __( 'Diagnostic', 'scc' ), 'manage_options', 'Stylish_Cost_Calculator_Diagnostic', array( $this, 'diagnostic' ) );
				}
				function edit_existing_page_style() {
					wp_enqueue_style('gf-admin-style', SCC_URL. 'styles/scc-back-end.css', array(), '3.1.7');
				}
			}
			$stylish_cost_calculator_edititems = new Stylish_Cost_Calculator_EditItems();
			?>