<?php

if ( !defined( 'ABSPATH' ) ) {
    exit;
}
// Save sync frequency setting
if ( isset( $_POST['a1wb_save_sync_freq'] ) && isset( $_POST['a1wb_sync_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['a1wb_sync_nonce'] ) ), 'a1wb_sync_settings' ) && current_user_can( 'manage_woocommerce' ) ) {
    // Scheduled sync is available on both plans - see class-a1woobay-sync.php's
    // class docblock for why this isn't a code-stripped Pro feature.
    $freq = sanitize_text_field( wp_unslash( $_POST['a1woobay_sync_frequency'] ?? 'hourly' ) );
    if ( in_array( $freq, array(
        'hourly',
        'twicedaily',
        'daily',
        'disabled'
    ), true ) ) {
        update_option( A1WooBay_Sync::OPT_FREQ, $freq );
        // Force cron reschedule by clearing then re-running schedule_cron
        A1WooBay_Sync::get_instance()->clear_cron();
        if ( 'disabled' !== $freq ) {
            wp_schedule_event( time(), $freq, A1WooBay_Sync::CRON_HOOK );
        }
    }
    update_option( A1WooBay_Sync::OPT_PULL_PRICE, ( isset( $_POST['a1woobay_sync_pull_price'] ) ? '1' : '0' ) );
    wp_safe_redirect( add_query_arg( array(
        'page'       => 'a1woobay-settings',
        'sync_saved' => '1',
    ), admin_url( 'admin.php' ) ) );
    exit;
}
// Clear deletion log
if ( isset( $_POST['a1wb_clear_deletion_log'] ) && isset( $_POST['a1wb_compliance_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['a1wb_compliance_nonce'] ) ), 'a1wb_compliance_settings' ) && current_user_can( 'manage_woocommerce' ) ) {
    delete_option( A1WooBay_Compliance::OPT_DELETION_LOG );
    wp_safe_redirect( add_query_arg( array(
        'page'        => 'a1woobay-settings',
        'log_cleared' => '1',
    ), admin_url( 'admin.php' ) ) );
    exit;
}
// Save compliance / verification token
if ( isset( $_POST['a1wb_save_compliance'] ) && isset( $_POST['a1wb_compliance_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['a1wb_compliance_nonce'] ) ), 'a1wb_compliance_settings' ) && current_user_can( 'manage_woocommerce' ) ) {
    update_option( A1WooBay_Compliance::OPT_VERIFICATION_TOKEN, sanitize_text_field( wp_unslash( $_POST['a1woobay_verification_token'] ?? '' ) ) );
    wp_safe_redirect( add_query_arg( array(
        'page'             => 'a1woobay-settings',
        'compliance_saved' => '1',
    ), admin_url( 'admin.php' ) ) );
    exit;
}
/**
 * A1-WooBay - Settings Page View
 *
 * @package A1WooBay_Bridge
 * @since   0.2.0
 */
$is_connected = $auth->is_connected();
$has_credentials = $auth->has_credentials();
$app_id_display = '';
if ( $auth->get_app_id() ) {
    $raw = $auth->get_app_id();
    $app_id_display = ( strlen( $raw ) > 6 ? str_repeat( 'x', strlen( $raw ) - 6 ) . substr( $raw, -6 ) : $raw );
}
?>
<div class="wrap">
	<h1><?php 
esc_html_e( 'A1 Marketplace Sync with eBay for WooCommerce - Settings', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></h1>

	<div style="display:flex;align-items:center;gap:12px;padding:12px 16px;margin:16px 0;border-radius:4px;background:<?php 
echo ( $is_connected ? '#edfaef' : '#fef8e7' );
?>;border-left:4px solid <?php 
echo ( $is_connected ? '#46b450' : '#f0b849' );
?>;">
		<span style="font-size:20px;"><?php 
echo ( $is_connected ? '&#x2705;' : '&#x26A0;&#xFE0F;' );
?></span>
		<div>
			<strong>
			<?php 
if ( $is_connected ) {
    esc_html_e( 'Connected to eBay', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
} elseif ( $has_credentials ) {
    esc_html_e( 'Credentials saved - not yet connected to eBay', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
} else {
    esc_html_e( 'Not connected - enter your eBay API credentials below', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
}
?>
			</strong>
			<?php 
if ( $is_connected ) {
    ?>
				<br><small style="color:#555;"><?php 
    esc_html_e( 'Access token is valid. Use the button below to disconnect.', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
    ?></small>
			<?php 
}
?>
		</div>
	</div>

	<div style="display:flex;gap:24px;flex-wrap:wrap;align-items:flex-start;">

		<div style="flex:1 1 420px;max-width:560px;">
			<h2><?php 
esc_html_e( 'eBay API Credentials', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></h2>
			<p class="description">
				<?php 
printf( 
    /* translators: %s: link to the eBay Developer Portal */
    esc_html__( 'Get these from your app on the %s.', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
    '<a href="https://developer.ebay.com/my/keys" target="_blank" rel="noopener">' . esc_html__( 'eBay Developer Portal', 'a1-marketplace-sync-with-ebay-for-woocommerce' ) . '</a>'
 );
?>
			</p>

			<form method="post" action="<?php 
echo esc_url( admin_url( 'admin-post.php' ) );
?>">
				<input type="hidden" name="action" value="a1woobay_save_settings">
				<?php 
wp_nonce_field( 'a1woobay_save_settings' );
?>

				<table class="form-table" role="presentation">
					<tr>
						<th scope="row"><label for="a1woobay_app_id"><?php 
esc_html_e( 'App ID (Client ID)', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></label></th>
						<td>
							<input type="text" id="a1woobay_app_id" name="a1woobay_app_id" class="regular-text"
								placeholder="<?php 
echo ( $app_id_display ? esc_attr( $app_id_display ) : 'YourName-AppName-PRD-xxxxxxxx-xxxxxxxx' );
?>"
								autocomplete="off">
							<?php 
if ( $auth->get_app_id() ) {
    ?>
								<p class="description"><?php 
    esc_html_e( 'Leave blank to keep the saved value.', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
    ?></p>
							<?php 
}
?>
						</td>
					</tr>
					<tr>
						<th scope="row"><label for="a1woobay_cert_id"><?php 
esc_html_e( 'Cert ID (Client Secret)', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></label></th>
						<td>
							<input type="password" id="a1woobay_cert_id" name="a1woobay_cert_id" class="regular-text"
								placeholder="<?php 
echo ( $auth->get_cert_id() ? 'xxxxxxxxxxxxxxxxxx' : 'PRD-xxxxxxxxxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' );
?>"
								autocomplete="new-password">
							<?php 
if ( $auth->get_cert_id() ) {
    ?>
								<p class="description"><?php 
    esc_html_e( 'Leave blank to keep the saved value.', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
    ?></p>
							<?php 
}
?>
						</td>
					</tr>
					<tr>
						<th scope="row"><label for="a1woobay_env"><?php 
esc_html_e( 'Environment', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></label></th>
						<td>
							<?php 
$current_env = get_option( A1WooBay_Auth::OPT_ENV, 'production' );
?>
							<select id="a1woobay_env" name="a1woobay_env">
								<option value="production" <?php 
selected( $current_env, 'production' );
?>><?php 
esc_html_e( 'Production', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></option>
								<option value="sandbox" <?php 
selected( $current_env, 'sandbox' );
?>><?php 
esc_html_e( 'Sandbox (testing)', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></option>
							</select>
							<p class="description"><?php 
esc_html_e( 'Use Sandbox for development and testing. Switch to Production when going live.', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></p>
						</td>
					</tr>
					<tr>
						<th scope="row"><label for="a1woobay_runame"><?php 
esc_html_e( 'RuName', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></label></th>
						<td>
							<input type="text" id="a1woobay_runame" name="a1woobay_runame" class="regular-text"
								value="<?php 
echo esc_attr( $auth->get_runame() );
?>"
								placeholder="YourName-AppName-PRD-xxxxxxxx"
								autocomplete="off">
							<p class="description"><?php 
esc_html_e( 'The RuName from your eBay Developer Portal - User Tokens page.', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></p>
						</td>
					</tr>
					<tr>
						<th scope="row"><label><?php 
esc_html_e( 'Auth Accepted URL', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></label></th>
						<td>
							<code style="user-select:all;"><?php 
echo esc_html( $auth->get_redirect_uri() );
?></code>
							<p class="description"><?php 
esc_html_e( 'Register this as the "Auth Accepted URL" for your RuName in the eBay Developer Portal.', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></p>
						</td>
					</tr>
				</table>

				<?php 
submit_button(
    __( 'Save Credentials', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
    'primary',
    'submit',
    false
);
?>
			</form>
		</div>

		<div style="flex:0 0 280px;">
			<h2><?php 
esc_html_e( 'eBay Connection', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></h2>

			<?php 
if ( $is_connected ) {
    ?>
				<p><?php 
    esc_html_e( 'Your store is connected to eBay. Disconnect to re-authorize or switch accounts.', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
    ?></p>
				<form method="post" action="<?php 
    echo esc_url( admin_url( 'admin-post.php' ) );
    ?>">
					<input type="hidden" name="action" value="a1woobay_disconnect">
					<?php 
    wp_nonce_field( 'a1woobay_disconnect' );
    ?>
					<?php 
    submit_button(
        __( 'Disconnect from eBay', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
        'secondary',
        'submit',
        false
    );
    ?>
				</form>
			<?php 
} elseif ( $has_credentials ) {
    ?>
				<p><?php 
    esc_html_e( 'Credentials are saved. Click below to authorize with your eBay account.', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
    ?></p>
				<a href="<?php 
    echo esc_url( $auth->get_authorization_url() );
    ?>"
					class="button button-primary button-hero"
					style="display:inline-flex;align-items:center;gap:6px;text-decoration:none;">
					&#x1F517; <?php 
    esc_html_e( 'Connect to eBay', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
    ?>
				</a>
			<?php 
} else {
    ?>
				<p style="color:#777;"><?php 
    esc_html_e( 'Save your credentials first, then you can connect to eBay.', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
    ?></p>
				<button class="button button-primary button-hero" disabled>&#x1F517; <?php 
    esc_html_e( 'Connect to eBay', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
    ?></button>
			<?php 
}
?>

			<hr style="margin:24px 0;">
			<h3><?php 
esc_html_e( 'OAuth2 Scopes', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></h3>
			<ul style="list-style:disc;padding-left:1.2em;color:#444;font-size:12px;line-height:1.8;">
				<?php 
foreach ( A1WooBay_Auth::SCOPES as $scope ) {
    ?>
					<li><?php 
    echo esc_html( ( str_replace( 'https://api.ebay.com/oauth/api_scope', '', $scope ) ?: 'api_scope (base)' ) );
    ?></li>
				<?php 
}
?>
			</ul>
		</div>

	</div>

	<!-- ===== Order Import Settings ===== -->
	<div class="postbox" style="margin-top:20px;">
		<div class="postbox-header"><h2 class="hndle"><?php 
esc_html_e( 'Order Import Settings', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></h2></div>
		<div class="inside">

			<?php 
$order_pricing_url = admin_url( 'admin.php?page=a1woobay-settings-pricing' );
?>
			<?php 
?>
				<div style="padding:10px 14px;background:#fff8e5;border-left:4px solid #ffb900;font-size:13px;">
					🔒 <?php 
esc_html_e( 'Order import is a Pro feature.', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?>
					<a href="<?php 
echo esc_url( $order_pricing_url );
?>"><?php 
esc_html_e( 'Upgrade to A1 Marketplace Sync with eBay for WooCommerce Pro', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></a>
				</div>
			<?php 
?>

		</div>
	</div>


	<!-- ===== Sync Settings ===== -->
	<div class="postbox" style="margin-top:20px;">
		<div class="postbox-header"><h2 class="hndle"><?php 
esc_html_e( 'Sync Settings', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></h2></div>
		<div class="inside">

			<form method="post" action="<?php 
echo esc_url( admin_url( 'admin.php?page=a1woobay-settings' ) );
?>">
				<?php 
wp_nonce_field( 'a1wb_sync_settings', 'a1wb_sync_nonce' );
?>
				<table class="form-table" style="margin-bottom:0;">
					<tr>
						<th scope="row"><?php 
esc_html_e( 'Pull Sync Frequency', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></th>
						<td>
							<?php 
$sync_freq = get_option( A1WooBay_Sync::OPT_FREQ, 'hourly' );
?>
							<select name="a1woobay_sync_frequency" id="a1wb-sync-freq">
								<option value="hourly"     <?php 
selected( $sync_freq, 'hourly' );
?>><?php 
esc_html_e( 'Every Hour', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></option>
								<option value="twicedaily" <?php 
selected( $sync_freq, 'twicedaily' );
?>><?php 
esc_html_e( 'Twice Daily', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></option>
								<option value="daily"      <?php 
selected( $sync_freq, 'daily' );
?>><?php 
esc_html_e( 'Once Daily', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></option>
								<option value="disabled"   <?php 
selected( $sync_freq, 'disabled' );
?>><?php 
esc_html_e( 'Disabled', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></option>
							</select>
							<p class="description" style="margin-top:4px;"><?php 
esc_html_e( 'How often to pull qty updates from eBay into WooCommerce.', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php 
esc_html_e( 'Pull Price from eBay', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></th>
						<td>
							<?php 
$pull_price = get_option( A1WooBay_Sync::OPT_PULL_PRICE, '0' );
?>
							<label>
								<input type="checkbox" name="a1woobay_sync_pull_price" value="1" <?php 
checked( $pull_price, '1' );
?>>
								<?php 
esc_html_e( 'Also update WooCommerce regular price when eBay price differs', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?>
							</label>
							<p class="description"><?php 
esc_html_e( 'Leave unchecked if you use a price markup in your profile — enabling this would create a feedback loop.', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></p>
						</td>
					</tr>
					<tr>
						<th></th>
						<td>
							<button type="submit" name="a1wb_save_sync_freq" class="button button-secondary"><?php 
esc_html_e( 'Save Sync Settings', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></button>
						</td>
					</tr>
				</table>
			</form>

			<table class="form-table" style="margin-top:0;margin-bottom:0;">
				<tr>
					<th scope="row"><?php 
esc_html_e( 'Last Sync', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></th>
					<td>
						<?php 
$last = get_option( A1WooBay_Sync::OPT_LAST, null );
if ( $last ) {
    printf(
        /* translators: 1: last sync time, 2: number of products updated, 3: total products checked, 4: number of errors */
        esc_html__( '%1$s &mdash; %2$d of %3$d products updated, %4$d errors', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
        esc_html( $last['time'] ),
        (int) $last['updated'],
        (int) $last['total'],
        (int) $last['errors']
    );
} else {
    esc_html_e( 'Never run', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
}
?>
					</td>
				</tr>
			</table>

			<div style="margin-top:12px;">
				<button type="button" id="a1wb-sync-now-btn" class="button button-secondary">
					<?php 
esc_html_e( 'Sync Now', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?>
				</button>
				<span id="a1wb-sync-now-msg" style="margin-left:10px;font-size:13px;color:#555;"></span>
			</div>

		</div>
	</div>



	<!-- ===== eBay Compliance ===== -->
	<div class="postbox" style="margin-top:20px;">
		<div class="postbox-header"><h2 class="hndle"><?php 
esc_html_e( 'eBay Compliance — Marketplace Account Deletion', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></h2></div>
		<div class="inside">

			<p style="margin-top:0;"><?php 
esc_html_e( 'eBay requires all apps using their APIs to handle account deletion notifications. Register the endpoint URL below in your eBay Developer Portal app settings. The verification token is one you create — any random 32–80 character string — which you save here and also paste into the eBay Developer Portal.', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></p>

			<table class="form-table" style="margin-bottom:12px;">
				<tr>
					<th scope="row"><?php 
esc_html_e( 'Notification Endpoint URL', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></th>
					<td>
						<code id="a1wb-endpoint-url" style="user-select:all;font-size:13px;"><?php 
echo esc_html( A1WooBay_Compliance::get_endpoint_url() );
?></code>
						<button type="button" class="button button-secondary" style="margin-left:8px;vertical-align:middle;" onclick="navigator.clipboard.writeText(document.getElementById('a1wb-endpoint-url').textContent).then(function(){this.textContent='Copied!';}.bind(this));"><?php 
esc_html_e( 'Copy', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></button>
						<p class="description"><?php 
esc_html_e( 'Register this as the Notification Delivery URL in your eBay Developer Portal → Application Keys → Notifications.', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></p>
					</td>
				</tr>
			</table>

			<form method="post" action="<?php 
echo esc_url( admin_url( 'admin.php?page=a1woobay-settings' ) );
?>">
				<?php 
wp_nonce_field( 'a1wb_compliance_settings', 'a1wb_compliance_nonce' );
?>
				<table class="form-table" style="margin-bottom:0;">
					<tr>
						<th scope="row"><label for="a1woobay_verification_token"><?php 
esc_html_e( 'Verification Token', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></label></th>
						<td>
							<input type="text" id="a1woobay_verification_token" name="a1woobay_verification_token"
								class="regular-text"
								value="<?php 
echo esc_attr( get_option( A1WooBay_Compliance::OPT_VERIFICATION_TOKEN, '' ) );
?>"
								placeholder="<?php 
esc_attr_e( 'Enter a random 32–80 character string you create', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?>">
							<p class="description"><?php 
esc_html_e( 'Create a random 32–80 character string (you make this up). Save it here first, then paste the same value into the eBay Developer Portal notification endpoint settings.', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></p>
						</td>
					</tr>
					<tr>
						<th></th>
						<td>
							<button type="submit" name="a1wb_save_compliance" class="button button-secondary"><?php 
esc_html_e( 'Save Token', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></button>
							<button type="submit" name="a1wb_clear_deletion_log" class="button button-secondary" style="margin-left:8px;" onclick="return confirm('Clear all deletion log entries?');"><?php 
esc_html_e( 'Clear Log', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
?></button>
							<?php 
if ( isset( $_GET['compliance_saved'] ) ) {
    ?>
								<span style="margin-left:10px;color:#2a7a2a;">&#10003; <?php 
    esc_html_e( 'Saved.', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
    ?></span>
							<?php 
}
?>
							<?php 
if ( isset( $_GET['log_cleared'] ) ) {
    ?>
								<span style="margin-left:10px;color:#2a7a2a;">&#10003; <?php 
    esc_html_e( 'Log cleared.', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
    ?></span>
							<?php 
}
?>
						</td>
					</tr>
				</table>
			</form>

			<?php 
$del_log = get_option( A1WooBay_Compliance::OPT_DELETION_LOG, array() );
if ( $del_log ) {
    $del_log = array_reverse( $del_log );
    // newest first
    ?>
			<hr style="margin:16px 0;">
			<h3 style="margin-top:0;"><?php 
    esc_html_e( 'Deletion Request Log', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
    ?></h3>
			<table class="widefat striped" style="font-size:12px;">
				<thead>
					<tr>
						<th><?php 
    esc_html_e( 'Time', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
    ?></th>
						<th><?php 
    esc_html_e( 'eBay Username', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
    ?></th>
						<th><?php 
    esc_html_e( 'User ID', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
    ?></th>
						<th><?php 
    esc_html_e( 'Orders Anonymized', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
    ?></th>
					</tr>
				</thead>
				<tbody>
				<?php 
    foreach ( $del_log as $entry ) {
        ?>
					<tr>
						<td><?php 
        echo esc_html( $entry['time'] );
        ?></td>
						<td><?php 
        echo esc_html( $entry['username'] );
        ?></td>
						<td><?php 
        echo esc_html( $entry['userId'] );
        ?></td>
						<td><?php 
        echo esc_html( $entry['anonymized'] );
        ?></td>
					</tr>
				<?php 
    }
    ?>
				</tbody>
			</table>
			<?php 
} else {
    ?>
			<p style="color:#888;font-size:12px;margin-top:12px;"><?php 
    esc_html_e( 'No deletion requests received yet.', 'a1-marketplace-sync-with-ebay-for-woocommerce' );
    ?></p>
			<?php 
}
?>

		</div>
	</div>

</div>