<?php
/**
 * Google Merchant Feed Admin Tab
 *
 * Settings and management interface for Google Merchant feeds.
 *
 * @package GGM_Commerce
 * @since 1.0.0
 */

defined( 'ABSPATH' ) || exit;

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
// phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter

/**
 * Render the Google Merchant Feed settings tab.
 */
function ggm_commerce_render_google_merchant_tab() {
	// Check if feature is activated.
	$is_activated = GGM_Commerce_Google_Merchant_Feed::is_activated();

	// Get instances.
	$settings     = GGM_Commerce_Google_Merchant_Settings::instance();
	$feed_manager = GGM_Commerce_Google_Merchant_Feed_Manager::instance();
	$scheduler    = GGM_Commerce_Google_Merchant_Scheduler::instance();

	// Handle form submissions.
	if ( isset( $_POST['ggm_google_merchant_action'] ) && check_admin_referer( 'ggm_google_merchant_settings' ) ) {
		$action = sanitize_text_field( wp_unslash( $_POST['ggm_google_merchant_action'] ) );

		if ( 'save_settings' === $action ) {
			$new_settings = array(
				'default_brand'        => isset( $_POST['default_brand'] ) ? sanitize_text_field( wp_unslash( $_POST['default_brand'] ) ) : '',
				'brand_attribute_id'   => isset( $_POST['brand_attribute_id'] ) ? absint( $_POST['brand_attribute_id'] ) : 0,
				'default_condition'    => isset( $_POST['default_condition'] ) ? sanitize_key( wp_unslash( $_POST['default_condition'] ) ) : 'new',
				'include_variations'   => isset( $_POST['include_variations'] ),
				'id_format'            => isset( $_POST['id_format'] ) ? sanitize_key( wp_unslash( $_POST['id_format'] ) ) : 'sku',
				'description_field'    => isset( $_POST['description_field'] ) ? sanitize_key( wp_unslash( $_POST['description_field'] ) ) : 'description',
				'currency'             => isset( $_POST['currency'] ) ? strtoupper( sanitize_text_field( wp_unslash( $_POST['currency'] ) ) ) : 'USD',
				'gtin_barcode_type'    => isset( $_POST['gtin_barcode_type'] ) ? sanitize_text_field( wp_unslash( $_POST['gtin_barcode_type'] ) ) : 'EAN-13',
				'shipping_country'     => isset( $_POST['shipping_country'] ) ? sanitize_text_field( wp_unslash( $_POST['shipping_country'] ) ) : '',
				'shipping_price'       => isset( $_POST['shipping_price'] ) ? sanitize_text_field( wp_unslash( $_POST['shipping_price'] ) ) : '',
			);
			$settings->save( $new_settings );
			echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Settings saved.', 'ggm-commerce' ) . '</p></div>';
		} elseif ( 'create_feed' === $action ) {
			$feed_data = array(
				'name' => isset( $_POST['feed_name'] ) ? sanitize_text_field( wp_unslash( $_POST['feed_name'] ) ) : '',
			);
			$result = $feed_manager->create_feed( $feed_data );
			if ( is_wp_error( $result ) ) {
				echo '<div class="notice notice-error is-dismissible"><p>' . esc_html( $result->get_error_message() ) . '</p></div>';
			} else {
				echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Feed created.', 'ggm-commerce' ) . '</p></div>';
			}
		} elseif ( 'delete_feed' === $action ) {
			$feed_id = isset( $_POST['feed_id'] ) ? sanitize_key( wp_unslash( $_POST['feed_id'] ) ) : '';
			if ( $feed_manager->delete_feed( $feed_id ) ) {
				echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Feed deleted.', 'ggm-commerce' ) . '</p></div>';
			}
		} elseif ( 'regenerate_feed' === $action ) {
			$feed_id   = isset( $_POST['feed_id'] ) ? sanitize_key( wp_unslash( $_POST['feed_id'] ) ) : '';
			$generator = GGM_Commerce_Google_Merchant_Feed::instance();
			$validator = GGM_Commerce_Google_Merchant_Validator::instance();
			$validator->reset();
			$generator->set_validator( $validator );
			$result = $generator->generate_feed( $feed_id );
			if ( is_wp_error( $result ) ) {
				echo '<div class="notice notice-error is-dismissible"><p>' . esc_html( $result->get_error_message() ) . '</p></div>';
			} else {
				echo '<div class="notice notice-success is-dismissible"><p>' . sprintf(
					/* translators: %d: product count */
					esc_html__( 'Feed regenerated. %d products exported.', 'ggm-commerce' ),
					intval( $result['product_count'] )
				) . '</p></div>';
			}
		}
	}

	// Ensure default feed exists.
	$feed_manager->maybe_create_default_feed();

	// Get current data.
	$feeds           = $feed_manager->get_feeds();
	$current_settings = $settings->get_settings();

	// Get attributes for brand selection.
	global $wpdb;
	$attributes = $wpdb->get_results(
		"SELECT id, name FROM {$wpdb->prefix}ggmc_attributes WHERE status = 'active' ORDER BY name"
	);
	?>

	<div class="ggmc-google-merchant-wrap">
		<?php if ( ! $is_activated ) : ?>
			<!-- Feature Not Activated -->
			<div class="ggmc-premium-locked">
				<span class="dashicons dashicons-lock" style="font-size: 48px; margin-bottom: 15px;"></span>
				<h2><?php esc_html_e( 'Google Merchant Feed', 'ggm-commerce' ); ?></h2>
				<p><?php esc_html_e( 'Generate product feeds for Google Merchant Center with automatic scheduling and multi-feed support.', 'ggm-commerce' ); ?></p>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=ggmc-settings&tab=premium-components' ) ); ?>" class="button button-large">
					<?php esc_html_e( 'Activate Feature', 'ggm-commerce' ); ?>
				</a>
			</div>
		<?php else : ?>

			<!-- Feed List -->
			<div class="card">
				<h2 style="margin-top: 0;"><?php esc_html_e( 'Product Feeds', 'ggm-commerce' ); ?></h2>

				<table class="ggmc-feed-table">
					<thead>
						<tr>
							<th><?php esc_html_e( 'Feed Name', 'ggm-commerce' ); ?></th>
							<th><?php esc_html_e( 'Status', 'ggm-commerce' ); ?></th>
							<th><?php esc_html_e( 'Products', 'ggm-commerce' ); ?></th>
							<th><?php esc_html_e( 'Last Generated', 'ggm-commerce' ); ?></th>
							<th><?php esc_html_e( 'Feed URL', 'ggm-commerce' ); ?></th>
							<th><?php esc_html_e( 'Actions', 'ggm-commerce' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php if ( empty( $feeds ) ) : ?>
							<tr>
								<td colspan="6" style="text-align: center; color: #666;">
									<?php esc_html_e( 'No feeds created yet.', 'ggm-commerce' ); ?>
								</td>
							</tr>
						<?php else : ?>
							<?php foreach ( $feeds as $feed_id => $feed ) : ?>
								<tr>
									<td>
										<strong><?php echo esc_html( $feed['name'] ); ?></strong>
										<br>
										<small style="color: #666;">ID: <?php echo esc_html( $feed_id ); ?></small>
									</td>
									<td>
										<span class="ggmc-feed-status <?php echo esc_attr( $feed['status'] ); ?>">
											<?php echo esc_html( ucfirst( $feed['status'] ) ); ?>
										</span>
									</td>
									<td>
										<?php echo esc_html( $feed['product_count'] ); ?>
										<?php if ( $feed['error_count'] > 0 ) : ?>
											<br><small style="color: #dc3545;"><?php echo esc_html( $feed['error_count'] ); ?> errors</small>
										<?php endif; ?>
									</td>
									<td>
										<?php if ( $feed['last_generated'] ) : ?>
											<?php echo esc_html( human_time_diff( strtotime( $feed['last_generated'] ), current_time( 'timestamp' ) ) ); ?> ago
											<br><small style="color: #666;"><?php echo esc_html( $feed['last_generated'] ); ?></small>
										<?php else : ?>
											<span class="ggmc-feed-status never"><?php esc_html_e( 'Never', 'ggm-commerce' ); ?></span>
										<?php endif; ?>
									</td>
									<td>
										<div class="ggmc-feed-url" id="feed-url-<?php echo esc_attr( $feed_id ); ?>">
											<?php echo esc_html( $feed_manager->get_feed_url( $feed_id ) ); ?>
										</div>
										<button type="button" class="button ggmc-copy-btn" onclick="copyFeedUrl('<?php echo esc_attr( $feed_id ); ?>')">
											<?php esc_html_e( 'Copy', 'ggm-commerce' ); ?>
										</button>
									</td>
									<td>
										<form method="post" style="display: inline;">
											<?php wp_nonce_field( 'ggm_google_merchant_settings' ); ?>
											<input type="hidden" name="ggm_google_merchant_action" value="regenerate_feed">
											<input type="hidden" name="feed_id" value="<?php echo esc_attr( $feed_id ); ?>">
											<button type="submit" class="button"><?php esc_html_e( 'Regenerate', 'ggm-commerce' ); ?></button>
										</form>
										<a href="<?php echo esc_url( admin_url( 'admin.php?page=ggmc-settings&tab=google-merchant&feed=' . $feed_id ) ); ?>" class="button">
											<?php esc_html_e( 'Edit', 'ggm-commerce' ); ?>
										</a>
										<?php if ( 'default' !== $feed_id ) : ?>
											<form method="post" style="display: inline;" onsubmit="return confirm('<?php esc_attr_e( 'Are you sure you want to delete this feed?', 'ggm-commerce' ); ?>');">
												<?php wp_nonce_field( 'ggm_google_merchant_settings' ); ?>
												<input type="hidden" name="ggm_google_merchant_action" value="delete_feed">
												<input type="hidden" name="feed_id" value="<?php echo esc_attr( $feed_id ); ?>">
												<button type="submit" class="button" style="color: #dc3545;"><?php esc_html_e( 'Delete', 'ggm-commerce' ); ?></button>
											</form>
										<?php endif; ?>
									</td>
								</tr>
							<?php endforeach; ?>
						<?php endif; ?>
					</tbody>
				</table>

				<!-- Create New Feed -->
				<div style="margin-top: 20px; padding-top: 20px; border-top: 1px solid #ddd;">
					<h3><?php esc_html_e( 'Create New Feed', 'ggm-commerce' ); ?></h3>
					<form method="post" style="display: flex; gap: 10px; align-items: end;">
						<?php wp_nonce_field( 'ggm_google_merchant_settings' ); ?>
						<input type="hidden" name="ggm_google_merchant_action" value="create_feed">
						<div>
							<label for="feed_name"><?php esc_html_e( 'Feed Name', 'ggm-commerce' ); ?></label><br>
							<input type="text" name="feed_name" id="feed_name" placeholder="e.g., Sale Items Feed" required style="width: 300px;">
						</div>
						<button type="submit" class="button button-primary"><?php esc_html_e( 'Create Feed', 'ggm-commerce' ); ?></button>
					</form>
				</div>
			</div>

			<!-- Global Settings -->
			<div class="card">
				<h2 style="margin-top: 0;"><?php esc_html_e( 'Global Settings', 'ggm-commerce' ); ?></h2>
				<p class="description"><?php esc_html_e( 'These settings apply to all feeds.', 'ggm-commerce' ); ?></p>

				<form method="post">
					<?php wp_nonce_field( 'ggm_google_merchant_settings' ); ?>
					<input type="hidden" name="ggm_google_merchant_action" value="save_settings">

					<div class="ggmc-settings-grid">
						<div>
							<h3><?php esc_html_e( 'Brand Settings', 'ggm-commerce' ); ?></h3>

							<div class="form-field">
								<label for="brand_attribute_id"><?php esc_html_e( 'Brand Attribute', 'ggm-commerce' ); ?></label>
								<select name="brand_attribute_id" id="brand_attribute_id">
									<option value="0"><?php esc_html_e( '-- None --', 'ggm-commerce' ); ?></option>
									<?php foreach ( $attributes as $attr ) : ?>
										<option value="<?php echo esc_attr( $attr->id ); ?>" <?php selected( $current_settings['brand_attribute_id'], $attr->id ); ?>>
											<?php echo esc_html( $attr->name ); ?>
										</option>
									<?php endforeach; ?>
								</select>
								<p class="description"><?php esc_html_e( 'Select product attribute to use for brand.', 'ggm-commerce' ); ?></p>
							</div>

							<div class="form-field">
								<label for="default_brand"><?php esc_html_e( 'Default Brand', 'ggm-commerce' ); ?></label>
								<input type="text" name="default_brand" id="default_brand" value="<?php echo esc_attr( $current_settings['default_brand'] ); ?>">
								<p class="description"><?php esc_html_e( 'Used when product has no brand attribute.', 'ggm-commerce' ); ?></p>
							</div>

							<div class="form-field">
								<label for="default_condition"><?php esc_html_e( 'Default Condition', 'ggm-commerce' ); ?></label>
								<select name="default_condition" id="default_condition">
									<?php foreach ( $settings->get_condition_options() as $value => $label ) : ?>
										<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $current_settings['default_condition'], $value ); ?>>
											<?php echo esc_html( $label ); ?>
										</option>
									<?php endforeach; ?>
								</select>
							</div>
						</div>

						<div>
							<h3><?php esc_html_e( 'Product Data', 'ggm-commerce' ); ?></h3>

							<div class="form-field">
								<label for="id_format"><?php esc_html_e( 'Product ID Format', 'ggm-commerce' ); ?></label>
								<select name="id_format" id="id_format">
									<?php foreach ( $settings->get_id_format_options() as $value => $label ) : ?>
										<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $current_settings['id_format'], $value ); ?>>
											<?php echo esc_html( $label ); ?>
										</option>
									<?php endforeach; ?>
								</select>
							</div>

							<div class="form-field">
								<label for="description_field"><?php esc_html_e( 'Description Source', 'ggm-commerce' ); ?></label>
								<select name="description_field" id="description_field">
									<?php foreach ( $settings->get_description_field_options() as $value => $label ) : ?>
										<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $current_settings['description_field'], $value ); ?>>
											<?php echo esc_html( $label ); ?>
										</option>
									<?php endforeach; ?>
								</select>
							</div>

							<div class="form-field">
								<label for="gtin_barcode_type"><?php esc_html_e( 'GTIN Barcode Type', 'ggm-commerce' ); ?></label>
								<select name="gtin_barcode_type" id="gtin_barcode_type">
									<option value="EAN-13" <?php selected( $current_settings['gtin_barcode_type'], 'EAN-13' ); ?>>EAN-13</option>
									<option value="UPC-A" <?php selected( $current_settings['gtin_barcode_type'], 'UPC-A' ); ?>>UPC-A</option>
									<option value="EAN-8" <?php selected( $current_settings['gtin_barcode_type'], 'EAN-8' ); ?>>EAN-8</option>
									<option value="GTIN-14" <?php selected( $current_settings['gtin_barcode_type'], 'GTIN-14' ); ?>>GTIN-14</option>
								</select>
								<p class="description"><?php esc_html_e( 'Primary barcode type to use for GTIN.', 'ggm-commerce' ); ?></p>
							</div>
						</div>

						<div>
							<h3><?php esc_html_e( 'Pricing', 'ggm-commerce' ); ?></h3>

							<div class="form-field">
								<label for="currency"><?php esc_html_e( 'Currency Code', 'ggm-commerce' ); ?></label>
								<input type="text" name="currency" id="currency" value="<?php echo esc_attr( $current_settings['currency'] ); ?>" maxlength="3" style="width: 80px;">
								<p class="description"><?php esc_html_e( 'ISO 4217 currency code (e.g., USD, EUR, GBP).', 'ggm-commerce' ); ?></p>
							</div>
						</div>

						<div>
							<h3><?php esc_html_e( 'Shipping', 'ggm-commerce' ); ?></h3>

							<div class="form-field">
								<label for="shipping_country"><?php esc_html_e( 'Shipping Country', 'ggm-commerce' ); ?></label>
								<input type="text" name="shipping_country" id="shipping_country" value="<?php echo esc_attr( $current_settings['shipping_country'] ); ?>" placeholder="US" maxlength="2" style="width: 80px;">
								<p class="description"><?php esc_html_e( 'ISO country code for default shipping.', 'ggm-commerce' ); ?></p>
							</div>

							<div class="form-field">
								<label for="shipping_price"><?php esc_html_e( 'Default Shipping Price', 'ggm-commerce' ); ?></label>
								<input type="text" name="shipping_price" id="shipping_price" value="<?php echo esc_attr( $current_settings['shipping_price'] ); ?>" placeholder="0.00" style="width: 100px;">
								<p class="description"><?php esc_html_e( 'Leave empty to omit shipping info.', 'ggm-commerce' ); ?></p>
							</div>
						</div>
					</div>

					<p style="margin-top: 20px;">
						<button type="submit" class="button button-primary"><?php esc_html_e( 'Save Settings', 'ggm-commerce' ); ?></button>
					</p>
				</form>
			</div>

		<?php endif; ?>
	</div>

	<script>
	function copyFeedUrl(feedId) {
		var urlElement = document.getElementById('feed-url-' + feedId);
		var url = urlElement.textContent.trim();
		navigator.clipboard.writeText(url).then(function() {
			alert('Feed URL copied to clipboard!');
		});
	}
	</script>
	<?php
}
