<?php
/**
 * Google Merchant Feed Edit Page
 *
 * Edit individual feed settings.
 *
 * @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 feed edit form.
 *
 * @param string $feed_id Feed ID to edit.
 */
function ggm_commerce_render_google_merchant_feed_edit( $feed_id ) {
	$feed_manager = GGM_Commerce_Google_Merchant_Feed_Manager::instance();
	$feed         = $feed_manager->get_feed( $feed_id );

	if ( ! $feed ) {
		echo '<div class="notice notice-error"><p>' . esc_html__( 'Feed not found.', 'ggm-commerce' ) . '</p></div>';
		return;
	}

	// Handle form submission.
	if ( isset( $_POST['ggm_feed_action'] ) && check_admin_referer( 'ggm_google_merchant_feed_edit' ) ) {
		$action = sanitize_key( wp_unslash( $_POST['ggm_feed_action'] ) );

		if ( 'save_feed' === $action ) {
			$feed_data = array(
				'name'               => isset( $_POST['feed_name'] ) ? sanitize_text_field( wp_unslash( $_POST['feed_name'] ) ) : $feed['name'],
				'status'             => isset( $_POST['feed_status'] ) ? sanitize_key( wp_unslash( $_POST['feed_status'] ) ) : 'active',
				'categories'         => isset( $_POST['categories'] ) ? array_map( 'absint', (array) $_POST['categories'] ) : array(),
				'exclude_categories' => isset( $_POST['exclude_categories'] ) ? array_map( 'absint', (array) $_POST['exclude_categories'] ) : array(),
				'stock_status'       => isset( $_POST['stock_status'] ) ? sanitize_key( wp_unslash( $_POST['stock_status'] ) ) : 'all',
				'sale_only'          => isset( $_POST['sale_only'] ),
				'featured_only'      => isset( $_POST['featured_only'] ),
				'schedule'           => isset( $_POST['schedule'] ) ? sanitize_key( wp_unslash( $_POST['schedule'] ) ) : 'daily',
			);

			$result = $feed_manager->update_feed( $feed_id, $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 {
				$feed = $result;
				echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Feed updated.', 'ggm-commerce' ) . '</p></div>';
			}
		}
	}

	// Get categories for dropdown.
	global $wpdb;
	$categories = $wpdb->get_results(
		"SELECT id, name, parent_id FROM {$wpdb->prefix}ggmc_categories ORDER BY name"
	);

	// Get schedule status.
	$scheduler       = GGM_Commerce_Google_Merchant_Scheduler::instance();
	$next_scheduled  = $scheduler->get_next_scheduled( $feed['schedule'] );

	// Get validation info.
	$generator = GGM_Commerce_Google_Merchant_Feed::instance();
	$validator = GGM_Commerce_Google_Merchant_Validator::instance();
	$products  = $generator->get_products_for_feed( $feed );
	$report    = $validator->validate_products_batch( $products );
	?>

	<div class="ggmc-feed-edit-wrap">
		<p>
			<a href="<?php echo esc_url( admin_url( 'admin.php?page=ggmc-settings&tab=google-merchant' ) ); ?>" class="button">
				&larr; <?php esc_html_e( 'Back to Feeds', 'ggm-commerce' ); ?>
			</a>
		</p>

		<!-- Feed Info -->
		<div class="card">
			<h2><?php
			echo esc_html( sprintf(
				/* translators: %s: feed name */
				__( 'Edit Feed: %s', 'ggm-commerce' ),
				$feed['name']
			) );
		?></h2>

			<p>
				<strong><?php esc_html_e( 'Feed URL:', 'ggm-commerce' ); ?></strong><br>
				<code style="padding: 8px; display: inline-block; background: #f0f0f1; margin-top: 5px;">
					<?php echo esc_html( $feed_manager->get_feed_url( $feed_id ) ); ?>
				</code>
				<button type="button" class="button button-small" onclick="navigator.clipboard.writeText('<?php echo esc_js( $feed_manager->get_feed_url( $feed_id ) ); ?>').then(function() { alert('Copied!'); });">
					<?php esc_html_e( 'Copy', 'ggm-commerce' ); ?>
				</button>
			</p>

			<?php if ( $feed['last_generated'] ) : ?>
				<p>
					<strong><?php esc_html_e( 'Last Generated:', 'ggm-commerce' ); ?></strong>
					<?php echo esc_html( $feed['last_generated'] ); ?>
					(<?php echo esc_html( human_time_diff( strtotime( $feed['last_generated'] ), current_time( 'timestamp' ) ) ); ?> ago)
				</p>
			<?php endif; ?>

			<?php if ( $next_scheduled ) : ?>
				<p>
					<strong><?php esc_html_e( 'Next Scheduled:', 'ggm-commerce' ); ?></strong>
					<?php echo esc_html( gmdate( 'Y-m-d H:i:s', $next_scheduled ) ); ?>
				</p>
			<?php endif; ?>
		</div>

		<!-- Validation Summary -->
		<div class="card">
			<h2><?php esc_html_e( 'Validation Summary', 'ggm-commerce' ); ?></h2>

			<div class="ggmc-validation-summary">
				<div class="ggmc-validation-item success">
					<span class="number"><?php echo esc_html( $report['total_products'] ); ?></span>
					<span class="label"><?php esc_html_e( 'Total Products', 'ggm-commerce' ); ?></span>
				</div>
				<div class="ggmc-validation-item <?php echo $report['products_with_errors'] > 0 ? 'error' : 'success'; ?>">
					<span class="number"><?php echo esc_html( $report['valid_products'] ); ?></span>
					<span class="label"><?php esc_html_e( 'Valid', 'ggm-commerce' ); ?></span>
				</div>
				<div class="ggmc-validation-item <?php echo $report['products_with_errors'] > 0 ? 'error' : ''; ?>">
					<span class="number"><?php echo esc_html( $report['products_with_errors'] ); ?></span>
					<span class="label"><?php esc_html_e( 'With Errors', 'ggm-commerce' ); ?></span>
				</div>
				<div class="ggmc-validation-item <?php echo $report['products_with_warnings'] > 0 ? 'warning' : ''; ?>">
					<span class="number"><?php echo esc_html( $report['products_with_warnings'] ); ?></span>
					<span class="label"><?php esc_html_e( 'With Warnings', 'ggm-commerce' ); ?></span>
				</div>
			</div>

			<p style="display: flex; gap: 20px;">
				<span><strong><?php esc_html_e( 'Missing Images:', 'ggm-commerce' ); ?></strong> <?php echo esc_html( $report['missing_images'] ); ?></span>
				<span><strong><?php esc_html_e( 'Missing Prices:', 'ggm-commerce' ); ?></strong> <?php echo esc_html( $report['missing_prices'] ); ?></span>
				<span><strong><?php esc_html_e( 'Missing GTIN:', 'ggm-commerce' ); ?></strong> <?php echo esc_html( $report['missing_gtin'] ); ?></span>
				<span><strong><?php esc_html_e( 'Missing Brand:', 'ggm-commerce' ); ?></strong> <?php echo esc_html( $report['missing_brand'] ); ?></span>
			</p>
		</div>

		<!-- Feed Settings Form -->
		<div class="card">
			<h2><?php esc_html_e( 'Feed Settings', 'ggm-commerce' ); ?></h2>

			<form method="post">
				<?php wp_nonce_field( 'ggm_google_merchant_feed_edit' ); ?>
				<input type="hidden" name="ggm_feed_action" value="save_feed">

				<table class="form-table">
					<tr>
						<th scope="row">
							<label for="feed_name"><?php esc_html_e( 'Feed Name', 'ggm-commerce' ); ?></label>
						</th>
						<td>
							<input type="text" name="feed_name" id="feed_name" value="<?php echo esc_attr( $feed['name'] ); ?>" class="regular-text" required>
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label for="feed_status"><?php esc_html_e( 'Status', 'ggm-commerce' ); ?></label>
						</th>
						<td>
							<select name="feed_status" id="feed_status">
								<option value="active" <?php selected( $feed['status'], 'active' ); ?>><?php esc_html_e( 'Active', 'ggm-commerce' ); ?></option>
								<option value="paused" <?php selected( $feed['status'], 'paused' ); ?>><?php esc_html_e( 'Paused', 'ggm-commerce' ); ?></option>
							</select>
							<p class="description"><?php esc_html_e( 'Paused feeds will not be accessible and won\'t regenerate.', 'ggm-commerce' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label for="schedule"><?php esc_html_e( 'Schedule', 'ggm-commerce' ); ?></label>
						</th>
						<td>
							<select name="schedule" id="schedule">
								<?php foreach ( $feed_manager->get_schedule_options() as $value => $label ) : ?>
									<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $feed['schedule'], $value ); ?>>
										<?php echo esc_html( $label ); ?>
									</option>
								<?php endforeach; ?>
							</select>
							<p class="description"><?php esc_html_e( 'How often to regenerate this feed.', 'ggm-commerce' ); ?></p>
						</td>
					</tr>
				</table>

				<h3><?php esc_html_e( 'Product Filters', 'ggm-commerce' ); ?></h3>
				<p class="description"><?php esc_html_e( 'Control which products are included in this feed.', 'ggm-commerce' ); ?></p>

				<table class="form-table">
					<tr>
						<th scope="row">
							<label for="categories"><?php esc_html_e( 'Include Categories', 'ggm-commerce' ); ?></label>
						</th>
						<td>
							<select name="categories[]" id="categories" multiple class="ggmc-category-select">
								<?php foreach ( $categories as $cat ) : ?>
									<option value="<?php echo esc_attr( $cat->id ); ?>" <?php echo in_array( (int) $cat->id, $feed['categories'], true ) ? 'selected' : ''; ?>>
										<?php echo esc_html( $cat->name ); ?>
									</option>
								<?php endforeach; ?>
							</select>
							<p class="description"><?php esc_html_e( 'Leave empty to include all categories. Hold Ctrl/Cmd to select multiple.', 'ggm-commerce' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label for="exclude_categories"><?php esc_html_e( 'Exclude Categories', 'ggm-commerce' ); ?></label>
						</th>
						<td>
							<select name="exclude_categories[]" id="exclude_categories" multiple class="ggmc-category-select">
								<?php foreach ( $categories as $cat ) : ?>
									<option value="<?php echo esc_attr( $cat->id ); ?>" <?php echo in_array( (int) $cat->id, $feed['exclude_categories'], true ) ? 'selected' : ''; ?>>
										<?php echo esc_html( $cat->name ); ?>
									</option>
								<?php endforeach; ?>
							</select>
							<p class="description"><?php esc_html_e( 'Products in these categories will be excluded.', 'ggm-commerce' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label for="stock_status"><?php esc_html_e( 'Stock Status', 'ggm-commerce' ); ?></label>
						</th>
						<td>
							<select name="stock_status" id="stock_status">
								<?php foreach ( $feed_manager->get_stock_status_options() as $value => $label ) : ?>
									<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $feed['stock_status'], $value ); ?>>
										<?php echo esc_html( $label ); ?>
									</option>
								<?php endforeach; ?>
							</select>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Additional Filters', 'ggm-commerce' ); ?></th>
						<td>
							<label>
								<input type="checkbox" name="sale_only" value="1" <?php checked( $feed['sale_only'] ); ?>>
								<?php esc_html_e( 'Only include products on sale', 'ggm-commerce' ); ?>
							</label>
							<br>
							<label>
								<input type="checkbox" name="featured_only" value="1" <?php checked( $feed['featured_only'] ); ?>>
								<?php esc_html_e( 'Only include featured products', 'ggm-commerce' ); ?>
							</label>
						</td>
					</tr>
				</table>

				<p>
					<button type="submit" class="button button-primary"><?php esc_html_e( 'Save Feed Settings', 'ggm-commerce' ); ?></button>
				</p>
			</form>
		</div>
	</div>
	<?php
}
