<?php
/**
 * Redirect Manager Admin Page
 *
 * Handles AJAX endpoints, CSV export/import, and the redirect table rendering
 * within the General Settings page's "Redirects" vertical tab.
 *
 * @package SEOvaultSEO\RedirectManager
 */

namespace SEOvaultSEO\RedirectManager;

use SEOvaultSEO\Utils\Logger;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Admin page handler for the redirect manager.
 */
class AdminPage {

	/**
	 * Initialize hooks.
	 *
	 * @return void
	 */
	public static function init() {
		// AJAX handlers.
		add_action( 'wp_ajax_seovaultseo_redirect_add', array( __CLASS__, 'ajax_add' ) );
		add_action( 'wp_ajax_seovaultseo_redirect_update', array( __CLASS__, 'ajax_update' ) );
		add_action( 'wp_ajax_seovaultseo_redirect_delete', array( __CLASS__, 'ajax_delete' ) );
		add_action( 'wp_ajax_seovaultseo_redirect_bulk_delete', array( __CLASS__, 'ajax_bulk_delete' ) );

		// CSV export/import (admin_init so we can send headers early).
		add_action( 'admin_init', array( __CLASS__, 'handle_csv_export' ) );
		add_action( 'admin_init', array( __CLASS__, 'handle_csv_import' ) );
		add_action( 'wp_ajax_seovaultseo_redirect_import_csv', array( __CLASS__, 'ajax_import_csv' ) );
	}

	/**
	 * Render the Redirects tab content (called from Dashboard::render_general).
	 *
	 * @return void
	 */
	public static function render_tab() {
		$manager   = new RedirectManager();
		$redirects = $manager->get_all();
		$types     = Redirect::get_type_labels();
		?>
		<h2><?php esc_html_e( 'Redirect Manager', 'seovault-ai' ); ?></h2>
		<p class="description"><?php esc_html_e( 'Create and manage URL redirects with support for plain and regex matching, multiple redirect types (301, 302, 307, 410, 451), and CSV import/export.', 'seovault-ai' ); ?></p>

		<div id="seovaultseo-redirect-manager">
			<table class="widefat striped" id="seovaultseo-redirect-table" style="margin-bottom:20px;">
				<thead>
					<tr>
						<th style="width:30px;"><label class="seovaultseo-check"><input type="checkbox" id="seovaultseo-redirect-select-all" /><span></span></label></th>
						<th><?php esc_html_e( 'Origin (Source)', 'seovault-ai' ); ?></th>
						<th><?php esc_html_e( 'Target (Destination)', 'seovault-ai' ); ?></th>
						<th style="width:80px;"><?php esc_html_e( 'Type', 'seovault-ai' ); ?></th>
						<th style="width:70px;"><?php esc_html_e( 'Format', 'seovault-ai' ); ?></th>
						<th style="width:120px;"><?php esc_html_e( 'Actions', 'seovault-ai' ); ?></th>
					</tr>
				</thead>
				<tbody id="seovaultseo-redirect-rows">
					<?php if ( empty( $redirects ) ) : ?>
						<tr class="seovaultseo-redirect-empty">
							<td colspan="6"><?php esc_html_e( 'No redirects configured yet.', 'seovault-ai' ); ?></td>
						</tr>
					<?php else : ?>
						<?php foreach ( $redirects as $redirect ) : ?>
							<tr data-id="<?php echo esc_attr( $redirect->get_id() ); ?>">
								<td><label class="seovaultseo-check"><input type="checkbox" class="seovaultseo-redirect-check" value="<?php echo esc_attr( $redirect->get_id() ); ?>" /><span></span></label></td>
								<td class="origin"><?php echo esc_html( $redirect->get_origin() ); ?></td>
								<td class="target"><?php echo esc_html( $redirect->get_target() ); ?></td>
								<td class="type"><?php echo esc_html( (string) $redirect->get_type() ); ?></td>
								<td class="format"><?php echo esc_html( $redirect->get_format() ); ?></td>
								<td>
									<button type="button" class="button button-small seovaultseo-redirect-edit"><?php esc_html_e( 'Edit', 'seovault-ai' ); ?></button>
									<button type="button" class="button button-small seovaultseo-redirect-delete" style="color:#a00;"><?php esc_html_e( 'Delete', 'seovault-ai' ); ?></button>
								</td>
							</tr>
						<?php endforeach; ?>
					<?php endif; ?>
				</tbody>
			</table>

			<div style="margin-bottom:20px;">
				<button type="button" class="button button-secondary" id="seovaultseo-redirect-bulk-delete" style="color:#a00;">
					<?php esc_html_e( 'Delete Selected', 'seovault-ai' ); ?>
				</button>
			</div>

			<h3><?php esc_html_e( 'Add New Redirect', 'seovault-ai' ); ?></h3>
			<table class="form-table">
				<tr>
					<th scope="row"><label for="seovaultseo-redirect-origin"><?php esc_html_e( 'Origin (Source URL)', 'seovault-ai' ); ?></label></th>
					<td>
						<input type="text" id="seovaultseo-redirect-origin" class="regular-text" placeholder="/old-page" />
						<p class="description"><?php esc_html_e( 'The URL path that should be redirected. For plain redirects, enter a relative path (e.g. old-page). For regex redirects, enter a valid regex pattern.', 'seovault-ai' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="seovaultseo-redirect-target"><?php esc_html_e( 'Target (Destination URL)', 'seovault-ai' ); ?></label></th>
					<td>
						<input type="text" id="seovaultseo-redirect-target" class="regular-text" placeholder="/new-page" />
						<p class="description"><?php esc_html_e( 'The URL to redirect to. Can be a relative path or a full URL. Not required for 410 and 451 redirect types.', 'seovault-ai' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="seovaultseo-redirect-type"><?php esc_html_e( 'Redirect Type', 'seovault-ai' ); ?></label></th>
					<td>
						<select id="seovaultseo-redirect-type" class="seovaultseo-select">
							<?php foreach ( $types as $code => $label ) : ?>
								<option value="<?php echo esc_attr( (string) $code ); ?>"><?php echo esc_html( $label ); ?></option>
							<?php endforeach; ?>
						</select>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="seovaultseo-redirect-format"><?php esc_html_e( 'Match Type', 'seovault-ai' ); ?></label></th>
					<td>
						<select id="seovaultseo-redirect-format" class="seovaultseo-select">
							<option value="plain"><?php esc_html_e( 'Plain (exact match)', 'seovault-ai' ); ?></option>
							<option value="regex"><?php esc_html_e( 'Regex (pattern match)', 'seovault-ai' ); ?></option>
						</select>
					</td>
				</tr>
			</table>
			<p>
				<button type="button" class="button button-primary" id="seovaultseo-redirect-add-btn"><?php esc_html_e( 'Add Redirect', 'seovault-ai' ); ?></button>
				<span id="seovaultseo-redirect-msg" style="margin-left:12px;"></span>
			</p>

			<hr>

			<h3><?php esc_html_e( 'Import / Export', 'seovault-ai' ); ?></h3>
			<p>
				<a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin.php?page=seovault-ai-general&seovaultseo_redirect_export=1' ), 'seovaultseo_redirect_export' ) ); ?>" class="button button-secondary">
					<?php esc_html_e( 'Export to CSV', 'seovault-ai' ); ?>
				</a>
			</p>

			<div style="margin-top:15px;">
				<input type="file" id="seovaultseo-redirect-csv-file" accept=".csv" />
				<button type="button" class="button button-secondary" id="seovaultseo-redirect-import-btn"><?php esc_html_e( 'Import CSV', 'seovault-ai' ); ?></button>
				<span id="seovaultseo-redirect-import-msg" style="margin-left:12px;"></span>
				<p class="description"><?php esc_html_e( 'CSV format: Origin, Target, Type (301/302/307/410/451), Format (plain/regex). Existing origins will be skipped.', 'seovault-ai' ); ?></p>
			</div>
		</div>

		<?php
	}

	/**
	 * AJAX handler: Add a new redirect.
	 *
	 * @return void
	 */
	public static function ajax_add() {
		check_ajax_referer( 'seovaultseo_redirect_admin', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			Logger::error( 'AJAX redirect_add: capability check failed' );
			wp_send_json_error( array( 'message' => __( 'Unauthorized.', 'seovault-ai' ) ), 403 );
		}

		$origin = isset( $_POST['origin'] ) ? sanitize_text_field( wp_unslash( $_POST['origin'] ) ) : '';
		$target = isset( $_POST['target'] ) ? sanitize_text_field( wp_unslash( $_POST['target'] ) ) : '';
		$type   = isset( $_POST['type'] ) ? absint( wp_unslash( $_POST['type'] ) ) : 301;
		$format = isset( $_POST['format'] ) ? sanitize_text_field( wp_unslash( $_POST['format'] ) ) : 'plain';

		Logger::log(
			'AJAX redirect_add: inputs',
			array(
				'origin' => $origin,
				'target' => $target,
				'type'   => $type,
				'format' => $format,
			)
		);

		$redirect = new Redirect( $origin, $target, $type, $format );
		$manager  = new RedirectManager();

		$id = $manager->create( $redirect );

		if ( $id ) {
			Logger::log( 'AJAX redirect_add: success', array( 'id' => $id ) );
			wp_send_json_success(
				array(
					'id'      => $id,
					'message' => __( 'Redirect created.', 'seovault-ai' ),
				)
			);
		} else {
			Logger::error( 'AJAX redirect_add: failed', array( 'error' => $manager->get_error() ) );
			wp_send_json_error( array( 'message' => $manager->get_error() ?: __( 'Failed to create redirect.', 'seovault-ai' ) ) );
		}
	}

	/**
	 * AJAX handler: Update an existing redirect.
	 *
	 * @return void
	 */
	public static function ajax_update() {
		check_ajax_referer( 'seovaultseo_redirect_admin', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			Logger::error( 'AJAX redirect_update: capability check failed' );
			wp_send_json_error( array( 'message' => __( 'Unauthorized.', 'seovault-ai' ) ), 403 );
		}

		$id     = isset( $_POST['id'] ) ? absint( wp_unslash( $_POST['id'] ) ) : 0;
		$origin = isset( $_POST['origin'] ) ? sanitize_text_field( wp_unslash( $_POST['origin'] ) ) : '';
		$target = isset( $_POST['target'] ) ? sanitize_text_field( wp_unslash( $_POST['target'] ) ) : '';
		$type   = isset( $_POST['type'] ) ? absint( wp_unslash( $_POST['type'] ) ) : 301;
		$format = isset( $_POST['format'] ) ? sanitize_text_field( wp_unslash( $_POST['format'] ) ) : 'plain';

		if ( ! $id ) {
			Logger::error( 'AJAX redirect_update: invalid redirect ID' );
			wp_send_json_error( array( 'message' => __( 'Invalid redirect ID.', 'seovault-ai' ) ) );
		}

		Logger::log(
			'AJAX redirect_update: inputs',
			array(
				'id'     => $id,
				'origin' => $origin,
				'target' => $target,
				'type'   => $type,
				'format' => $format,
			)
		);

		$redirect = new Redirect( $origin, $target, $type, $format );
		$manager  = new RedirectManager();

		$success = $manager->update( $id, $redirect );

		if ( $success ) {
			Logger::log( 'AJAX redirect_update: success', array( 'id' => $id ) );
			wp_send_json_success( array( 'message' => __( 'Redirect updated.', 'seovault-ai' ) ) );
		} else {
			Logger::error(
				'AJAX redirect_update: failed',
				array(
					'id'    => $id,
					'error' => $manager->get_error(),
				)
			);
			wp_send_json_error( array( 'message' => $manager->get_error() ?: __( 'Failed to update redirect.', 'seovault-ai' ) ) );
		}
	}

	/**
	 * AJAX handler: Delete a redirect.
	 *
	 * @return void
	 */
	public static function ajax_delete() {
		check_ajax_referer( 'seovaultseo_redirect_admin', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			Logger::error( 'AJAX redirect_delete: capability check failed' );
			wp_send_json_error( array( 'message' => __( 'Unauthorized.', 'seovault-ai' ) ), 403 );
		}

		$id = isset( $_POST['id'] ) ? absint( wp_unslash( $_POST['id'] ) ) : 0;

		if ( ! $id ) {
			Logger::error( 'AJAX redirect_delete: invalid redirect ID' );
			wp_send_json_error( array( 'message' => __( 'Invalid redirect ID.', 'seovault-ai' ) ) );
		}

		Logger::log( 'AJAX redirect_delete: inputs', array( 'id' => $id ) );

		$manager = new RedirectManager();
		$success = $manager->delete( $id );

		if ( $success ) {
			Logger::log( 'AJAX redirect_delete: success', array( 'id' => $id ) );
			wp_send_json_success( array( 'message' => __( 'Redirect deleted.', 'seovault-ai' ) ) );
		} else {
			Logger::error( 'AJAX redirect_delete: failed', array( 'id' => $id ) );
			wp_send_json_error( array( 'message' => __( 'Failed to delete redirect.', 'seovault-ai' ) ) );
		}
	}

	/**
	 * AJAX handler: Bulk delete redirects.
	 *
	 * @return void
	 */
	public static function ajax_bulk_delete() {
		check_ajax_referer( 'seovaultseo_redirect_admin', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			Logger::error( 'AJAX redirect_bulk_delete: capability check failed' );
			wp_send_json_error( array( 'message' => __( 'Unauthorized.', 'seovault-ai' ) ), 403 );
		}

		$ids_raw = isset( $_POST['ids'] ) ? sanitize_text_field( wp_unslash( $_POST['ids'] ) ) : '';
		$ids     = array_filter( array_map( 'absint', explode( ',', $ids_raw ) ) );

		if ( empty( $ids ) ) {
			Logger::error( 'AJAX redirect_bulk_delete: no redirects selected' );
			wp_send_json_error( array( 'message' => __( 'No redirects selected.', 'seovault-ai' ) ) );
		}

		Logger::log( 'AJAX redirect_bulk_delete: inputs', array( 'count' => count( $ids ) ) );

		$manager = new RedirectManager();
		$deleted = $manager->delete_many( $ids );

		Logger::log( 'AJAX redirect_bulk_delete: success', array( 'deleted' => $deleted ) );
		wp_send_json_success(
			array(
				'deleted' => $deleted,
				'message' => sprintf(
					/* translators: %d: number of redirects deleted */
					__( '%d redirects deleted.', 'seovault-ai' ),
					$deleted
				),
			)
		);
	}

	/**
	 * Handle CSV export download.
	 *
	 * @return void
	 */
	public static function handle_csv_export() {
		if ( ! isset( $_GET['seovaultseo_redirect_export'] ) ) {
			return;
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		check_admin_referer( 'seovaultseo_redirect_export' );

		$manager = new RedirectManager();
		$csv     = $manager->export_csv();

		// Clean any buffered output.
		if ( ob_get_contents() ) {
			ob_clean();
		}

		header( 'Content-Type: text/csv; charset=utf-8' );
		header( 'Content-Disposition: attachment; filename="seovault-redirects.csv"' );
		header( 'Pragma: no-cache' );
		header( 'Expires: 0' );

		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- CSV data.
		echo $csv;
		exit;
	}

	/**
	 * Handle CSV import upload.
	 *
	 * @return void
	 */
	public static function handle_csv_import() {
		if ( ! isset( $_POST['seovaultseo_redirect_import_submit'] ) ) {
			return;
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			Logger::error( 'CSV import: capability check failed' );
			return;
		}

		check_admin_referer( 'seovaultseo_redirect_import' );

		$tmp_name = isset( $_FILES['seovaultseo_redirect_csv']['tmp_name'] )
			? sanitize_text_field( wp_unslash( $_FILES['seovaultseo_redirect_csv']['tmp_name'] ) )
			: '';
		if ( '' === $tmp_name || ! is_uploaded_file( $tmp_name ) ) {
			Logger::error( 'CSV import: no file uploaded' );
			add_settings_error( 'seovault_seo_redirects', 'no_file', __( 'No CSV file uploaded.', 'seovault-ai' ), 'error' );
			return;
		}

		$file_name = isset( $_FILES['seovaultseo_redirect_csv']['name'] )
			? sanitize_file_name( wp_unslash( $_FILES['seovaultseo_redirect_csv']['name'] ) )
			: '';

		// Validate file type.
		$ext = strtolower( pathinfo( $file_name, PATHINFO_EXTENSION ) );
		if ( 'csv' !== $ext ) {
			Logger::error( 'CSV import: wrong file type', array( 'ext' => $ext ) );
			add_settings_error( 'seovault_seo_redirects', 'wrong_type', __( 'Please upload a .csv file.', 'seovault-ai' ), 'error' );
			return;
		}

		Logger::log( 'CSV import: processing file', array( 'filename' => $file_name ) );

		$manager = new RedirectManager();
		$result  = $manager->import_csv( $tmp_name );

		Logger::log(
			'CSV import: complete',
			array(
				'total'    => $result['total'],
				'imported' => $result['imported'],
				'skipped'  => $result['skipped'],
			)
		);

		add_settings_error(
			'seovault_seo_redirects',
			'import_complete',
			sprintf(
				/* translators: 1: total rows, 2: imported, 3: skipped */
				__( 'Import complete: %1$d total, %2$d imported, %3$d skipped.', 'seovault-ai' ),
				$result['total'],
				$result['imported'],
				$result['skipped']
			),
			'updated'
		);
	}

	/**
	 * AJAX handler: Import CSV redirects.
	 *
	 * @return void
	 */
	public static function ajax_import_csv() {
		check_ajax_referer( 'seovaultseo_redirect_admin', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			Logger::error( 'AJAX redirect_import_csv: capability check failed' );
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'seovault-ai' ) ) );
		}

		$tmp_name = isset( $_FILES['seovaultseo_redirect_csv']['tmp_name'] )
			? sanitize_text_field( wp_unslash( $_FILES['seovaultseo_redirect_csv']['tmp_name'] ) )
			: '';
		if ( '' === $tmp_name || ! is_uploaded_file( $tmp_name ) ) {
			Logger::error( 'AJAX redirect_import_csv: no file uploaded' );
			wp_send_json_error( array( 'message' => __( 'No CSV file uploaded.', 'seovault-ai' ) ) );
		}

		$file_name = isset( $_FILES['seovaultseo_redirect_csv']['name'] )
			? sanitize_file_name( wp_unslash( $_FILES['seovaultseo_redirect_csv']['name'] ) )
			: '';

		$ext = strtolower( pathinfo( $file_name, PATHINFO_EXTENSION ) );
		if ( 'csv' !== $ext ) {
			Logger::error( 'AJAX redirect_import_csv: wrong file type', array( 'ext' => $ext ) );
			wp_send_json_error( array( 'message' => __( 'Please upload a .csv file.', 'seovault-ai' ) ) );
		}

		Logger::log( 'AJAX redirect_import_csv: processing', array( 'filename' => $file_name ) );

		$manager = new RedirectManager();
		$result  = $manager->import_csv( $tmp_name );

		Logger::log(
			'AJAX redirect_import_csv: complete',
			array(
				'total'    => $result['total'],
				'imported' => $result['imported'],
				'skipped'  => $result['skipped'],
			)
		);

		wp_send_json_success(
			array(
				'message' => sprintf(
				/* translators: 1: total rows, 2: imported, 3: skipped */
					__( 'Import complete: %1$d total, %2$d imported, %3$d skipped.', 'seovault-ai' ),
					$result['total'],
					$result['imported'],
					$result['skipped']
				),
				'result'  => $result,
			)
		);
	}
}
