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

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

<main
    class="amazingaffiliates_admin_page amazingaffiliates_setup"
    data-ajax="<?php echo esc_url( get_site_url() ); ?>/wp-admin/admin-ajax.php"
    data-nonce="<?php echo esc_attr( wp_create_nonce( 'setup' ) ); ?>"
>

	<nav id="amazingaffiliates_navbar">
		<?php do_action('amazingaffiliates_navbar', $amazingaffiliates_page ); ?>
	</nav>
	
	<?php do_action('amazingaffiliates_setupnotice' ); ?>
	<?php do_action('amazingaffiliates_is_debugger_mode'); ?>
	
	<details id="header" >
		
		<summary><h1 class="amazingaffiliates_admin_page_title" >Amazon APIs Connection Setup <span>ⓘ</span></h1></summary>
		<h2>Here you can setup the APIs and check for any connectivity issue</h2>
		<p>Once you have inserted correctly your credentials you can test the connection.</p>		
		<p>The test is a REST call for the keyword "Echo" (A common Amazon product available always and everywhere) and what you see is the exact response of their servers.</p>
		<p>If everything is fine, the answer of the APIs is a JSON payload with the data of the products and it means that everything is fine</p>
		<p>If not, you can either get a failed response or a response with the culprit of the problem directly from Amazon.</p>
		<p>Since Amazon has recently raised 10x the requirements for the use of the APIs it is very likely that the error message is this: 
			<br><i>[{"Code":"AssociateNotEligible","Message":"Your account does not currently meet the eligibility requirements to access the Product Advertising API."}]</i>
			<br>This means you need to have at least 10 successful transactions in the last 30 days otherwise they will not give you access to their data in an automatic way.
			<br>There is no other solution than selling more to get the access or enter the products data by hand...
		</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 require( AMAZINGAFFILIATES_PLUGIN_URI . '/admin/partials/settings_settings.php' ); ?>
	
	<section class="amazingaffiliates_setup_step <?php 
                if( ! empty( get_option('amazingaffiliates_settings_api_partner_tag') ) AND
                    ! empty( get_option('amazingaffiliates_settings_api_country') ) AND
                    ! empty( get_option('amazingaffiliates_settings_api_accessKey2') ) AND
                    ! empty( get_option('amazingaffiliates_settings_api_secretKey2') ) ) echo 'allright';
                ?>" >
        
        <div class="amazingaffiliates_tab" >
            
            <details 
                <?php 
                if( empty( get_option('amazingaffiliates_settings_api_partner_tag') ) OR
                    empty( get_option('amazingaffiliates_settings_api_country') ) OR
                    empty( get_option('amazingaffiliates_settings_api_accessKey2') ) OR
                    empty( get_option('amazingaffiliates_settings_api_secretKey2') ) ) echo 'open';
                ?>
            >
                <summary>
                    <div>
                        <h2 style="margin:0;" >Your Amazon APIs credentials</h2>
						<small class="amazingaffiliates_tab_closed_notice"><i>Click to edit</i></small>
                    </div>
                </summary>
                
				<br>
				<i>Please notice that Amazing Affiliates does NOT collect this data in ANY way. This data remains on your Wordpress website database and is only needed to contact the Amazon Servers for product information retrieval</i>
				<br>
				<br>
                <?php $i = 0; ?>
                <div style="padding-bottom:0;">
                    
                    <?php $i = 0; ?>
                    <form method="post" action="options.php" style="margin-bottom:0;">
                        
                        <?php settings_fields( 'amazingaffiliates_settings' ); ?>
                        
                        <?php foreach(array_keys($settings) as $setting_group_key) : ?>
                            
                            <?php if($i++ > 0) continue; ?>
                            
                            <div id="<?php echo esc_attr( $setting_group_key ); ?>" >
                                
                                <p><?php echo esc_html( $settings_groups[$setting_group_key]["desc"] ); ?></p>
                                
                                <div class="form-table">
                                    
                                    <?php $j = 0; ?>
                                    <?php foreach($settings[$setting_group_key] as $setting) : ?>
                                        
                                        <?php $setting_slug = 'amazingaffiliates_settings_' . $setting_group_key . '_' . $setting['name']; ?>
									
										<?php
									
										/* Concealed functionalities under development
										 * Only beta testers should see these
										 * since 1.0.15
										 */
										$is_secret_field = (
											$setting_slug == "amazingaffiliates_settings_api_debug"
										);
										if( $is_secret_field AND ! get_transient('amazingaffiliates_is_debugger_mode') ) {
											continue;
										}
										elseif( $is_secret_field ) {
											?>
											<div style="padding:10px 10px 25px 10px;border-radius:5px;font-weight:600;background-color:yellow;">Field visible only to beta testers:</div>
											<?php
										}
										?>
                                            
                                            <?php if($setting["type"] == "separator") : ?>
                                                
                                                <div class="tr" style="border-bottom:1px dotted gray;" >
                                                    <div class="td" scope="row" colspan="3" style="font-size:150%;">
                                                        <?php echo esc_html( $setting["display"] ); ?>
                                                    </div>
                                                </div>
                                                
                                            <?php else : ?>
                                                <?php if($j++ > 0): ?>
                                                    <div class="lineseparator"><div></div></div>
                                                <?php endif; ?>
                                                
                                                <div data-saved-value="<?php echo esc_attr( get_option($setting_slug) ); ?>" 
													 class="tr <?php if( $setting_slug == 'amazingaffiliates_settings_api_accessKey' OR $setting_slug == 'amazingaffiliates_settings_api_secretKey' ) echo 'legacy'; ?> <?php echo esc_attr( $setting_group_key . '_group' ); ?>" >
                                                    <div class="th" scope="row" ><?php echo esc_html( $setting["display"] ); ?></div>
                                                    <div  class="td field" >
                                                        
                                                    <?php
                                                    
                                                    $value = get_option($setting_slug);
                                                    if( empty( $value ) & !empty( $setting["default"] ) ) $value = $setting["default"];
                                                    if( empty( $value ) ) $value = "";
                                                    
                                                    switch ($setting["type"]) : 
                                                        
                                                        case "text":
                                                            echo '<input type="text" name="' . esc_attr( $setting_slug ) . '" value="' . esc_attr( $value ) . '" data-saved-value="' . esc_attr( get_option($setting_slug) ) . '" />';
                                                        break;
                                                        
                                                        case "number":
                                                            echo '<input type="number" name="' . esc_attr( $setting_slug ) . '" value="' . esc_attr( $value ) . '" data-saved-value="' . esc_attr( get_option($setting_slug) ) . '" />';
                                                        break;
                                                        
                                                        case "password":
                                                            echo '<input type="password" name="' . esc_attr( $setting_slug ) . '" value="' . esc_attr( $value ) . '" data-saved-value="' . esc_attr( get_option($setting_slug) ) . '" />';
                                                        break;
                                                        
                                                        case "color":
                                                            echo '<input type="color" name="' . esc_attr( $setting_slug ) . '" value="' . esc_attr( $value ) . '"  data-saved-value="' . esc_attr( get_option($setting_slug) ) . '" />';
                                                        break;
                                                        
                                                        case "textarea":
                                                            echo '<textarea name="' . esc_attr( $setting_slug ) . '" data-saved-value="' . esc_attr( get_option($setting_slug) ) . '" >' . esc_attr( $value ) . '</textarea>';
                                                        break;
                                                        
                                                        case "select":
                                                            echo '<select name="' . esc_attr( $setting_slug ) . '" >';
                                                            foreach($setting["options"] as $setting_option) {
                                                                $selected_status = '';
                                                                if( get_option($setting_slug) == $setting_option["value"] ) {
                                                                    $selected_status = 'selected';
                                                                }
                                                                echo '<option value="' . esc_attr( $setting_option["value"] ) .'" ' . esc_attr( $selected_status ) . '>'
                                                                .	esc_attr( $setting_option["innerText"] )
                                                                .'</option>';
                                                            }
                                                            echo '</select>';
                                                        break;
                                                        
                                                        case "config":
                                                            echo '<select name="' . esc_attr( $setting_slug ) . '" data-saved-value="' . esc_attr( get_option($setting_slug) ) . '" >';
                                                            foreach($setting["options"] as $setting_option) {
                                                                $selected_status = '';
                                                                $current_option = json_decode(get_option($setting_slug));
                                                                if( $current_option->name == $setting_option["name"] ) {
                                                                    $selected_status = 'selected';
                                                                }
                                                                if( $setting_option["name"] == '- SELECT -' ) {
                                                                    echo '<option value="" ' . esc_attr( $selected_status ) . '>' .	esc_attr( $setting_option["name"] ) .'</option>'; 
                                                                }
                                                                else {
                                                                    $valid_value = array( 
                                                                        "name" => $setting_option["name"] , 
                                                                        "amazon_domain" => $setting_option["amazon_domain"] ,  
                                                                        "pa_endpoint" => $setting_option["pa_endpoint"] , 
                                                                        "region" => $setting_option["region"]  
                                                                    );
                                                                    echo '<option value="' . esc_attr( wp_json_encode( $valid_value ) ) .'" ' . esc_attr( $selected_status ) . '>' .	esc_attr( $setting_option["name"] ) .'</option>';
                                                                }
                                                                
                                                            }
                                                            echo '</select>';
                                                        break;
                                                        
                                                        default:
                                                            echo "Invalid Field";
                                                        break;
                                                        
                                                    endswitch; 
                                                    
                                                    ?>
                                                    
                                                    </div>
                                                    
                                                    <?php if( empty($value) ): ?>
                                                        
                                                        <div  class="td desc" style="padding-top:0;">
                                                            <?php echo wp_kses_post( $setting['desc'] ); ?>
                                                        </div>
                                                        
                                                    <?php else: ?>
                                                        
                                                        <div  class="td desc" style="padding:0;"></div>
                                                        
                                                    <?php endif; ?>
                                                    
                                                </div>
                                                
                                            <?php endif; ?>
                                        
                                    <?php endforeach; ?>
                                    
                                </div>
                                
                            </div>
                            
                        <?php endforeach; ?>
                        
                        <?php submit_button(__("Save", "amazingaffiliates"),'primary amazingaffiliates_submit'); ?>
                        
                    </div>
                    
            </details>
                
            </form>
            
        </div>	    
        
	</section>
	
    <section style="display:flex;flex-direction:column;justify-content:center; align-items:flex-start;<?php 
                if( get_option('amazingaffiliates_api_test_successful') == 1 ) { echo 'border-color:green;border-width:2px;'; }
					else { echo 'border-color:gold;border-width:2px;'; }
                ?>">
        
        <h2 style="margin:0 0 1em 0;">Check your connection with the APIs</h2>

		<details style="padding-left:15px;border:1px solid #eee;width:calc(100% - 15px);">
			<summary><h2>Test PAAPI5 (legacy)</h2></summary>
			<div style="padding:15px;">
				<div style="display:flex;margin:1em 0 1em 0; align-items: center;">            
					<button id="test_api" style="margin:0 10px 0 0;" class="button button-primary amazingaffiliates_submit">Test connection</button>
					<span>with PAAPI5</span>
				</div>

				<div style="padding:10px 0;width:100%;display:flex;align-items:center;">
					<input id="test_api_getitems_asin" type="text" placeholder="ASIN of the product"> 
					<button id="test_api_getitems" class="button button-primary amazingaffiliates_submit">Test getItems</button>
					<span>with PAAPI5</span>
				</div>
				<div style="padding:10px 0;width:100%;display:flex;align-items:center;">
					<input id="test_api_searchitems_search" type="text" placeholder="Search keyword"> 
					<button id="test_api_searchitems" class="button button-primary amazingaffiliates_submit">Test searchItems</button>				
					<span>with PAAPI5</span>
				</div>
			</div>
		</details>
		
		<br>
		
		<details open style="padding-left:15px;border:1px solid #eee;width:calc(100% - 15px);">
			<summary><h2>Test Creators' APIs</h2></summary>
			<div style="padding:15px;">
				<div style="margin-bottom:10px;border:1px solid #eee;padding:20px 10px 10px 10px;border-radius:5px;position:relative;">
					<?php 
					do_action('amazingaffiliates_api_get_the_token'); 
					?>
					<b style="font-size:13px;position:absolute;top:-10px;padding:0 2px;background-color:white;">Current OAuth Token 2: </b>
					<i>
						<code>
						<?php
							$token = get_transient('amazingaffiliates_api_token_cache');
							if(!empty($token) AND is_string($token)) {
								echo '<big>[</big>' 
									. esc_html( substr( $token, 0 , 15) 
									. '... (other ' . (strlen($token) - 30) . 'x characters) ...' 
									.  substr( $token, -15 , 15) ) 
									. '<big>]</big>';
							} 
							else {
								echo '[No valid tokens found, check your Creators API credentials and force a new token]';
							}
							?>
						</code>
					</i>
					<br><br>
					<span style="width:100%;text-align:left;">
						<?php
						$token_expiry = get_transient('amazingaffiliates_api_token_cache_expires');
						if(!empty($token_expiry)) {
							echo '<b>This token expires in: </b>';
							echo esc_html( human_time_diff( current_time('timestamp') , get_transient('amazingaffiliates_api_token_cache_expires') ) );
						}
						?>
					</span>
				</div>
				<button id="force_new_token" style="background-color:SeaGreen;padding:7px 12px;border-radius:3px;color:white;border:none;">Force a new token</button>
				<br><br>

				<div style="display:flex;margin:1em 0 1em 0; align-items: center;">            
					<button id="test_api2" style="margin:0 10px 0 0;" class="button button-primary amazingaffiliates_submit">Test connection</button>
					<span>with Creators' APIs</span>
				</div>		

				<div style="padding:10px 0;width:100%;display:flex;align-items:center;">
					<input id="test_api2_getitems_asin" type="text" placeholder="ASIN of the product"> 
					<button id="test_api2_getitems" class="button button-primary amazingaffiliates_submit">Test getItems</button>
					<span>with Creators' APIs</span>
				</div>
				<div style="padding:10px 0;width:100%;display:flex;align-items:center;">
					<input id="test_api2_searchitems_search" type="text" placeholder="Search keyword"> 
					<button id="test_api2_searchitems" class="button button-primary amazingaffiliates_submit">Test searchItems</button>				
					<span>with Creators' APIs</span>
				</div>									
			</div>
		</details>

		
		<div id="test_api_result_console">
			<span id="test_api_result">APIs answers will be shown here</span>
		</div>
        
        <button 
            id="letsStart"
            class="button button-primary amazingaffiliates_submit <?php if( get_option('amazingaffiliates_api_test_successful') != 1 ) echo 'hidden'; ?>"
            style="margin-top:1em;"
            >
            <a  style="color:white;text-decoration:none;" href="<?php echo esc_url( get_admin_url() ); ?>admin.php?page=amazingaffiliates_menu"
                >Let's Start!</a>
        </button>
        
    </section>
	
</main>

<br>