<?php if ( ! defined( 'ABSPATH' ) ) exit; ?>

<?php $amazingaffiliates_page = "edit";  ?>

<main class="amazingaffiliates_admin_page" data-ajax="<?php echo esc_url( get_site_url() ); ?>/wp-admin/admin-ajax.php" data-nonce="<?php echo esc_attr( wp_create_nonce( 'workshop-warehouse' ) ); ?>" >
	
	<nav id="amazingaffiliates_navbar">
		<?php do_action('amazingaffiliates_navbar', $amazingaffiliates_page ); ?>
	</nav>
	
	<?php do_action('amazingaffiliates_is_debugger_mode'); ?>
		
	<details id="header" >
		
		<summary><h1 class="amazingaffiliates_admin_page_title" title="Click for more info about this tool">Amazing Affiliates Warehouse <span>ⓘ</span></h1></summary>
		<h2>Here you can customize info of the products such as the default product title.</h2>
		<p>Just click <img alt="" width="18" height="18" src="<?php echo esc_attr( AMAZINGAFFILIATES_PLUGIN_URL . '/admin/img/edit.jpg' ); ?>" > the edit button next to the product title and put your new customized title on the green "Custom Title" Field.</p>
		<p>In this way, the product title will be automatically updated on all the blog posts where the product is inserted.</p>
		<p>All the customizable fields are <b style="color:darkgreen;">green</b>, while the others might still be customizable but will be overwritten when the product is updated through the APIs.</p>
		
	</details>
	
	<i style="display:block;width:calc(100% - 0.5em);text-align:center;">Enjoying <strong>Amazing Affiliates</strong>? Please rate <a href="https://wordpress.org/plugins/amazingaffiliates/#reviews" target="_blank" rel="noopener noreferrer">★★★★★</a> on <a <a="" href="https://wordpress.org/plugins/amazingaffiliates/#reviews" target="_blank" rel="noopener">WordPress.org</a> to help us spread the word. Thank you!</i>
	
<?php if( get_transient('amazingaffiliates_is_debugger_mode') ) : ?>
	
	<section style="border:2px dotted black;">
		
		<h2 style="padding:15px;background-color:yellow;margin:0;">Panel visible to beta testers only</h2>
		
		<?php				
		global $post;
        $product_cache = $post;
		
		// updated products
		$now = time();
		$product_filter = array(
			'post_type'   				=> 'amazing_product',
			'showposts' 				=> -1,
			'no_found_rows' 			=> 'true',
			'update_post_term_cache' 	=> false,  
			'meta_key' 					=> 'last_update',
			'orderby' 					=> 'meta_value_num',
			'order' 					=> 'ASC',
            'meta_query' 				=> array(
										   	array(
												'key' => 'last_update',
												'value' => ($now - 86400),
												'compare' => '>='
											)                   
										   ),
		);
		
		$product = new WP_Query( $product_filter );

		$entries = array();
		$i = 0;
		if( $product->have_posts() ) {
			while( $product->have_posts() )	{
				$product->the_post(); 
				$entries[$i++] = get_the_ID();
			}
		}
		
		$post = $product_cache;
        wp_reset_postdata();
		
		// total products
		$product_filter = array(
			'post_type'   				=> 'amazing_product',
			'showposts' 				=> -1,
			'no_found_rows' 			=> 'true',
			'update_post_term_cache' 	=> false
		);
		
		$product = new WP_Query( $product_filter );

		$total_entries = array();
		$j = 0;
		if( $product->have_posts() ) {
			while( $product->have_posts() )	{
				$product->the_post(); 
				$total_entries[$j++] = get_the_ID();
			}
		}
		
		$post = $product_cache;
        wp_reset_postdata();
		
		// not updateable
		$product_filter = array(
			'post_type'   				=> 'amazing_product',
			'showposts' 				=> -1,
			'no_found_rows' 			=> 'true',
			'update_post_term_cache' 	=> false,
			'meta_query' 				=> array(
										   	array(
												'key' => 'not_updateable',
												'value' => 1,
												'compare' => '='
											)                   
										   ),
			
		);
		
		$product = new WP_Query( $product_filter );

		$total_entries = array();
		$k = 0;
		if( $product->have_posts() ) {
			while( $product->have_posts() )	{
				$product->the_post(); 
				$total_entries[$k++] = get_the_ID();
			}
		}
		
		$post = $product_cache;
        wp_reset_postdata();
		?>
		<?php
		$cron_schedule = get_option('amazingaffiliates_settings_product_pages_auto_update_period');
		$cron_status = 'off';
		if( 1 == get_option('amazingaffiliates_settings_product_pages_auto_update_enabled') ) {
			$cron_status = 'to run every ' . human_time_diff( 0, $cron_schedule );
		}
		
		$last_up_int = get_option( 'amazingaffiliates_settings_product_pages_auto_update_lasttime' );
		$last_up = wp_date( get_option( 'date_format' ), $last_up_int ) . ' at ' . wp_date( get_option( 'time_format' ), $last_up_int );
		$last_up_howmany = get_option( 'amazingaffiliates_settings_product_pages_auto_update_lasttime_howmany' );
		$last_payload = get_option( 'amazingaffiliates_settings_product_pages_auto_update_lastasinpayload' , '[Last ASIN payload not found]' );		
		$last_updatestatus = get_option( 'amazingaffiliates_settings_product_pages_auto_update_lastupdatestatus' , '[Last update status not found]' );
		?>
		<h2>Products in the website inventory - Recap</h2>
		<style>
			.warehouse_recap{border-collapse: collapse;outline:1px solid lightgray;width:100%;border-radius:10px;overflow:hidden;text-align:center;}
			.warehouse_recap tr:first-child { font-weight:bold; }
			.warehouse_recap td {border-bottom:1px solid lightgray;border-right:1px solid lightgray;width:20%;padding:3px;}
			.warehouse_recap td:last-child {border-right:unset;}
			.warehouse_recap tr:last-child td {border-bottom:unset;}
		</style>
		<table class="warehouse_recap">
			<tr>
				<td>Total</td>
				<td>With issues</td>
				<td>Not updated</td>
				<td>Updated</td>
				<td>Updated Ratio</td>
			</tr>
			<tr>
				<td><?php echo esc_html( $j ); ?></td>
				<td><?php echo esc_html( $k ); ?></td>
				<td><?php echo esc_html( ($j - $i) ); ?></td>	
				<td><?php echo esc_html( $i ); ?></td>					
				<td><?php if($j == 0)$j=1; echo esc_html( round( ($i )/$j*100 , 3 ) ) . '%'; ?></td>		
			</tr>
		</table>
		<h2>Product updates - Recap</h2>
		<table class="warehouse_recap">
			<tr>
				<td>Auto Update</td>
				<td>Last cycle</td>
				<td>Last payload</td>
				<td>Issues</td>
			</tr>
			<tr>
				<td><?php echo esc_html( $cron_status ); ?></td>
				<td><?php echo esc_html( $last_up ); ?></td>
				<td><?php echo esc_html( $last_up_howmany ) . ' product'; if($last_up_howmany > 1) echo 's'; ?><br><?php /*echo esc_html( $last_payload );*/ ?></td>
				<td> <?php echo esc_html( $last_updatestatus );?></td>
			</tr>
		</table>
		<br>
		<div>
			<div style="display:flex;">
				<button id="force_update_cycle" style="background-color:green;border-radius:5px;border:none;padding:10px 15px;color:white;font-weight:400;">Force an update cycle</button>
				<span style="margin-left:10px;">Anticipates the update cycle for the next 10 least updated products.<br><i>Should be fast, few seconds.</i></span>
			</div>
			<br><br>
			<div style="display:flex;">
				<button id="total_update" style="background-color:red;border-radius:5px;border:none;padding:10px 15px;color:white;font-weight:400;">Mass update (up to 100 products)</button>
				<?php $rangemax = ceil($j/10 * (1 + $j/10 + 0.5)); ?>

				<span style="margin-left:10px;">Expected a <?php echo esc_html( $rangemax ); ?>s delay due to the size of your database.<br><i>Please wait, it will take a while ;)</i></span>
			</div>
			<p id="force_update_cycle_log" style="color:red;font-weight:600;margin-left:15px;"></p>
		</div>

	</section>
<?php endif; ?>
	
	<div id="workshop_forge"  style="display:none;">
		<input id="asin_purifier" type="text" placeholder="Paste the ASIN or the link">
		<button onclick="clearAsinCrucible();">Clear</button>
		<ol id="asins_crucible" data-asin >
		</ol>
		<button id="insert_products" >Insert products</button>
	</div>
	<div id="consolebox"  style="display:none;">
		<div id="console">			
		</div>
		<button id="expand" >+ More +</button>
	</div>
	
	<section class="warehouse_selectors">
		<div class="warehouse_selector_wrapper" >
			<div class="warehouse_selector labeled" >
				<label for="warehouse_issues_selector">Status:</label>
				<select name="warehouse_issues_selector" id="warehouse_issues_selector" >
					<option value="All" selected >All Products</option>
					<option value="Ok" >Only Fine Products</option>
					<option value="Out" >Only Discontinued Products</option>
				</select>
			</div>
			<div class="warehouse_selector labeled" >
				<label for="warehouse_asin_selector">ASIN:</label>
				<input name="warehouse_asin_selector" id="warehouse_asin_selector" type="text" placeholder="Search by ASIN:" >
			</div>
			<div class="warehouse_selector labeled" >
				<label for="warehouse_title_selector">Title:</label>
				<input name="warehouse_title_selector" id="warehouse_title_selector" type="text" placeholder="Search by title:" >
			</div>
		</div>
		<div class="warehouse_selector_wrapper" >
            
			<?php foreach(AmazingAffiliates_Admin::$amazingaffiliates_tax_index as $taxonomy) : ?>
			
			    <?php
                $tax_args = array(
                    'taxonomy' => $taxonomy['taxSlug'],
                    'orderby' => 'name',
                    'order' => 'ASC',
                    'hide_empty' => false
                );
                $taxonomy_entries = get_terms( $tax_args );
                ?>
                
                <?php if(!empty($taxonomy_entries)): ?>
                
                    <div class="warehouse_selector labeled" >
                        
                        <label><?php echo esc_html( $taxonomy['taxNameSingular'] ); ?>:</label>
                        <div id="warehouse_<?php echo esc_attr( $taxonomy['taxSlug'] ); ?>_selector" >
                            
                            <?php foreach  ($taxonomy_entries as $taxonomy_entry) : ?>
                                
                                <input  type="checkbox"
                                    name="warehouse_<?php echo esc_attr( $taxonomy['taxSlug'] ); ?>_selector"
                                    id="<?php echo esc_html( $taxonomy_entry->slug ); ?>_checkbox"
                                    value="<?php echo esc_attr( $taxonomy_entry->term_id ); ?>"
                                >
                                
                                <label for="<?php echo esc_html( $taxonomy_entry->slug ); ?>_checkbox">
                                    <?php echo esc_html( $taxonomy_entry->name ); ?>
                                </label>
                                
                            <?php endforeach; ?>
                            
                        </div>
                        
                    </div>
                    
                <?php endif; ?>
				
			<?php endforeach; ?>
			
		</div>
	</section>

	<style>
		.warehouse_legend {display:flex;flex-wrap:wrap;gap:10px;align-items:center;}
		.warehouse_legend .labeltag {border-radius:6px;display:flex;align-items:center;gap:5px;}
		.warehouse_legend .labeltag div {padding:5px;margin:17px 2px 2px 2px;border-radius:5px;background-color:white;}
		
	</style>
	<section class="warehouse_legend">
		<b>Legend:</b>
		<div class="labeltag" style="background-color:limegreen;"><div><span>Available</span></div></div>
		<div class="labeltag" style="background-color:gold;"><div><span>Limited Stock</span></div></div>
		<div class="labeltag" style="background-color:tomato;"><div><span>Unavailable</span></div></div>	
		<div class="labeltag" style="background-color:black;"><div><span>With Issues</span></div></div>	
		<div class="labeltag" style="background-color:lightgray;"><div><span>Not up-to-date</span></div></div>
	</section>
	
	<section>
		
		<div id="product_display" ></div>
		
	</section>

	<section>
		<div class="warehouse_selector_wrapper" >
			<div class="warehouse_selector labeledx" style="justify-content:center;" >
				<label for="warehouse_entries_selector">Show page </label>
				<select name="warehouse_entries_selector" id="warehouse_entries_selector" >
					<option value="1" selected >1</option>
					<option value="2" >2</option>
					<option value="3" >3</option>
				</select>
				<span id="pagecounter"></span>
			</div>
		</div>
	</section>

</main>