<?php
/**
 * Admin UI.
 *
 * @package FailedOrderRescueForWooCommerce
 */

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

class FORD_Admin {
	/**
	 * Initialize admin hooks.
	 *
	 * @return void
	 */
	public static function init() {
		add_action( 'admin_menu', array( __CLASS__, 'add_menu' ) );
		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue' ) );
		add_action( 'admin_post_ford_ignore_order', array( __CLASS__, 'handle_ignore_order' ) );
	}

	/**
	 * Add WooCommerce submenu.
	 *
	 * @return void
	 */
	public static function add_menu() {
		add_submenu_page(
			'woocommerce',
			__( 'Failed Order Rescue', 'failed-order-rescue-for-woocommerce' ),
			__( 'Failed Order Rescue', 'failed-order-rescue-for-woocommerce' ),
			'manage_woocommerce',
			'ford-recovery',
			array( __CLASS__, 'render_page' )
		);
	}

	/**
	 * Load admin assets.
	 *
	 * @param string $hook Current admin hook.
	 * @return void
	 */
	public static function enqueue( $hook ) {
		if ( false === strpos( $hook, 'ford-recovery' ) ) {
			return;
		}

		wp_enqueue_style( 'ford-admin', FORD_PLUGIN_URL . 'assets/css/admin.css', array(), FORD_VERSION );
	}

	/**
	 * Ignore order action.
	 *
	 * @return void
	 */
	public static function handle_ignore_order() {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( esc_html__( 'You do not have permission to ignore orders.', 'failed-order-rescue-for-woocommerce' ) );
		}

		$order_id = isset( $_GET['order_id'] ) ? absint( $_GET['order_id'] ) : 0;
		check_admin_referer( 'ford_ignore_order_' . $order_id );

		$order = wc_get_order( $order_id );

		if ( $order instanceof WC_Order ) {
			$order->update_meta_data( '_ford_ignored', 'yes' );
			$order->save();
		}

		wp_safe_redirect( add_query_arg( array( 'page' => 'ford-recovery', 'ford_notice' => 'order_ignored' ), admin_url( 'admin.php' ) ) );
		exit;
	}

	/**
	 * Render admin page.
	 *
	 * @return void
	 */
	public static function render_page() {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			return;
		}

		$tab = filter_input( INPUT_GET, 'tab', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		$tab = $tab ? sanitize_key( $tab ) : 'dashboard';

		echo '<div class="wrap ford-wrap">';
		echo '<h1>' . esc_html__( 'Failed Order Rescue', 'failed-order-rescue-for-woocommerce' ) . '</h1>';
		self::render_notice();
		self::render_tabs( $tab );

		if ( 'settings' === $tab ) {
			self::render_settings();
		} elseif ( 'automation' === $tab ) {
			FORD_Pro::render_automation_settings();
		} elseif ( 'reports' === $tab ) {
			FORD_Pro::render_reports();
		} elseif ( 'export' === $tab ) {
			FORD_Pro::render_export();
		} else {
			self::render_dashboard();
		}

		echo '</div>';
	}

	/**
	 * Render notices.
	 *
	 * @return void
	 */
	private static function render_notice() {
		$notice = filter_input( INPUT_GET, 'ford_notice', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		$notice = $notice ? sanitize_key( $notice ) : '';

		$messages = array(
			'email_sent'    => __( 'Recovery email sent.', 'failed-order-rescue-for-woocommerce' ),
			'email_failed'  => __( 'Recovery email could not be sent. Check that the order has a valid billing email.', 'failed-order-rescue-for-woocommerce' ),
			'order_ignored' => __( 'Order hidden from the recovery list.', 'failed-order-rescue-for-woocommerce' ),
		);

		if ( isset( $messages[ $notice ] ) ) {
			echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( $messages[ $notice ] ) . '</p></div>';
		}
	}

	/**
	 * Render nav tabs.
	 *
	 * @param string $active Active tab.
	 * @return void
	 */
	private static function render_tabs( $active ) {
		$tabs = array(
			'dashboard'  => __( 'Dashboard', 'failed-order-rescue-for-woocommerce' ),
			'settings'   => __( 'Settings', 'failed-order-rescue-for-woocommerce' ),
			'automation' => __( 'Automation', 'failed-order-rescue-for-woocommerce' ),
			'reports'    => __( 'Reports', 'failed-order-rescue-for-woocommerce' ),
			'export'     => __( 'Export', 'failed-order-rescue-for-woocommerce' ),
		);

		echo '<nav class="nav-tab-wrapper ford-tabs">';

		foreach ( $tabs as $slug => $label ) {
			$url   = add_query_arg( array( 'page' => 'ford-recovery', 'tab' => $slug ), admin_url( 'admin.php' ) );
			$class = $active === $slug ? ' nav-tab-active' : '';
			echo '<a class="nav-tab' . esc_attr( $class ) . '" href="' . esc_url( $url ) . '">' . esc_html( $label ) . '</a>';
		}

		echo '</nav>';
	}

	/**
	 * Render dashboard.
	 *
	 * @return void
	 */
	private static function render_dashboard() {
		$stats  = FORD_Orders::get_dashboard_stats();
		$orders = FORD_Orders::get_recoverable_orders( 25 );

		echo '<div class="ford-stat-grid">';
		self::render_stat_card( __( 'Lost Revenue', 'failed-order-rescue-for-woocommerce' ), wc_price( $stats['lost_revenue'] ), __( 'Recoverable order value in the last 30 days.', 'failed-order-rescue-for-woocommerce' ) );
		self::render_stat_card( __( 'Recoverable Orders', 'failed-order-rescue-for-woocommerce' ), number_format_i18n( $stats['recoverable_count'] ), __( 'Failed or pending orders ready for follow-up.', 'failed-order-rescue-for-woocommerce' ) );
		self::render_stat_card( __( 'Recovered Revenue', 'failed-order-rescue-for-woocommerce' ), wc_price( $stats['recovered_revenue'] ), __( 'Orders recovered after a rescue email or status recovery.', 'failed-order-rescue-for-woocommerce' ) );
		echo '</div>';

		echo '<div class="ford-layout">';
		echo '<section class="ford-panel ford-panel-main">';
		echo '<h2>' . esc_html__( 'Orders To Recover', 'failed-order-rescue-for-woocommerce' ) . '</h2>';
		self::render_orders_table( $orders );
		echo '</section>';

		echo '<aside class="ford-panel">';
		echo '<h2>' . esc_html__( 'Recovery Tips', 'failed-order-rescue-for-woocommerce' ) . '</h2>';
		echo '<p>' . esc_html__( 'Start with recent failed and pending orders that have a valid billing email, a clear payment method, and a meaningful order value.', 'failed-order-rescue-for-woocommerce' ) . '</p>';
		echo '<ul class="ford-checklist">';
		echo '<li>' . esc_html__( 'Send recovery links while the customer still remembers the order.', 'failed-order-rescue-for-woocommerce' ) . '</li>';
		echo '<li>' . esc_html__( 'Review payment methods with repeated failed orders.', 'failed-order-rescue-for-woocommerce' ) . '</li>';
		echo '<li>' . esc_html__( 'Use the ignore action for test orders or orders that should not be contacted.', 'failed-order-rescue-for-woocommerce' ) . '</li>';
		echo '<li>' . esc_html__( 'Keep email wording short and focused on completing payment safely.', 'failed-order-rescue-for-woocommerce' ) . '</li>';
		echo '</ul>';
		echo '</aside>';
		echo '</div>';
	}

	/**
	 * Render stat card.
	 *
	 * @param string $label Label.
	 * @param string $value Value.
	 * @param string $help Help text.
	 * @return void
	 */
	private static function render_stat_card( $label, $value, $help ) {
		self::render_public_stat_card( $label, $value, $help );
	}

	/**
	 * Render stat card for Pro modules.
	 *
	 * @param string $label Label.
	 * @param string $value Value.
	 * @param string $help Help text.
	 * @return void
	 */
	public static function render_public_stat_card( $label, $value, $help ) {
		echo '<div class="ford-stat-card">';
		echo '<span>' . esc_html( $label ) . '</span>';
		echo '<strong>' . wp_kses_post( $value ) . '</strong>';
		echo '<p>' . esc_html( $help ) . '</p>';
		echo '</div>';
	}

	/**
	 * Render recoverable orders table.
	 *
	 * @param array $orders Orders.
	 * @return void
	 */
	private static function render_orders_table( $orders ) {
		if ( empty( $orders ) ) {
			echo '<p class="ford-empty">' . esc_html__( 'No recoverable failed or pending orders found.', 'failed-order-rescue-for-woocommerce' ) . '</p>';
			return;
		}

		echo '<table class="widefat striped ford-orders-table">';
		echo '<thead><tr>';
		echo '<th>' . esc_html__( 'Order', 'failed-order-rescue-for-woocommerce' ) . '</th>';
		echo '<th>' . esc_html__( 'Customer', 'failed-order-rescue-for-woocommerce' ) . '</th>';
		echo '<th>' . esc_html__( 'Status', 'failed-order-rescue-for-woocommerce' ) . '</th>';
		echo '<th>' . esc_html__( 'Total', 'failed-order-rescue-for-woocommerce' ) . '</th>';
		echo '<th>' . esc_html__( 'Payment', 'failed-order-rescue-for-woocommerce' ) . '</th>';
		echo '<th>' . esc_html__( 'Last Email', 'failed-order-rescue-for-woocommerce' ) . '</th>';
		echo '<th>' . esc_html__( 'Actions', 'failed-order-rescue-for-woocommerce' ) . '</th>';
		echo '</tr></thead><tbody>';

		foreach ( $orders as $order ) {
			if ( ! $order instanceof WC_Order ) {
				continue;
			}

			$order_id = $order->get_id();
			$send_url = wp_nonce_url(
				add_query_arg(
					array(
						'action'   => 'ford_send_recovery_email',
						'order_id' => $order_id,
					),
					admin_url( 'admin-post.php' )
				),
				'ford_send_recovery_email_' . $order_id
			);
			$ignore_url = wp_nonce_url(
				add_query_arg(
					array(
						'action'   => 'ford_ignore_order',
						'order_id' => $order_id,
					),
					admin_url( 'admin-post.php' )
				),
				'ford_ignore_order_' . $order_id
			);

			echo '<tr>';
			echo '<td><a href="' . esc_url( $order->get_edit_order_url() ) . '">#' . esc_html( $order->get_order_number() ) . '</a></td>';
			echo '<td>' . esc_html( $order->get_billing_email() ? $order->get_billing_email() : __( 'No email', 'failed-order-rescue-for-woocommerce' ) ) . '</td>';
			echo '<td><span class="ford-status">' . esc_html( wc_get_order_status_name( $order->get_status() ) ) . '</span></td>';
			echo '<td>' . wp_kses_post( $order->get_formatted_order_total() ) . '</td>';
			echo '<td>' . esc_html( $order->get_payment_method_title() ? $order->get_payment_method_title() : __( 'Unknown', 'failed-order-rescue-for-woocommerce' ) ) . '</td>';
			echo '<td>' . esc_html( $order->get_meta( '_ford_recovery_email_sent_at', true ) ? $order->get_meta( '_ford_recovery_email_sent_at', true ) : __( 'Never', 'failed-order-rescue-for-woocommerce' ) ) . '</td>';
			echo '<td class="ford-actions"><a class="button button-primary" href="' . esc_url( $send_url ) . '">' . esc_html__( 'Send Pay Link', 'failed-order-rescue-for-woocommerce' ) . '</a> <a class="button" href="' . esc_url( $ignore_url ) . '">' . esc_html__( 'Ignore', 'failed-order-rescue-for-woocommerce' ) . '</a></td>';
			echo '</tr>';
		}

		echo '</tbody></table>';
	}

	/**
	 * Render settings form.
	 *
	 * @return void
	 */
	private static function render_settings() {
		$settings = FORD_Settings::get_all();
		$statuses = array(
			'failed'    => __( 'Failed', 'failed-order-rescue-for-woocommerce' ),
			'pending'   => __( 'Pending payment', 'failed-order-rescue-for-woocommerce' ),
			'cancelled' => __( 'Cancelled', 'failed-order-rescue-for-woocommerce' ),
			'on-hold'   => __( 'On hold', 'failed-order-rescue-for-woocommerce' ),
		);

		echo '<form method="post" action="' . esc_url( admin_url( 'options.php' ) ) . '" class="ford-settings-form">';
		settings_fields( 'ford_settings_group' );
		echo '<input type="hidden" name="ford_settings[settings_context]" value="general">';

		echo '<table class="form-table" role="presentation"><tbody>';
		echo '<tr><th scope="row">' . esc_html__( 'Recoverable statuses', 'failed-order-rescue-for-woocommerce' ) . '</th><td>';
		foreach ( $statuses as $status => $label ) {
			echo '<label class="ford-checkbox"><input type="checkbox" name="ford_settings[enabled_statuses][]" value="' . esc_attr( $status ) . '" ' . checked( in_array( $status, $settings['enabled_statuses'], true ), true, false ) . '> ' . esc_html( $label ) . '</label>';
		}
		echo '</td></tr>';

		echo '<tr><th scope="row"><label for="ford_email_subject">' . esc_html__( 'Email subject', 'failed-order-rescue-for-woocommerce' ) . '</label></th><td><input id="ford_email_subject" type="text" class="regular-text" name="ford_settings[email_subject]" value="' . esc_attr( $settings['email_subject'] ) . '"></td></tr>';
		echo '<tr><th scope="row"><label for="ford_email_heading">' . esc_html__( 'Email heading', 'failed-order-rescue-for-woocommerce' ) . '</label></th><td><input id="ford_email_heading" type="text" class="regular-text" name="ford_settings[email_heading]" value="' . esc_attr( $settings['email_heading'] ) . '"></td></tr>';
		echo '<tr><th scope="row"><label for="ford_email_body">' . esc_html__( 'Email body', 'failed-order-rescue-for-woocommerce' ) . '</label></th><td><textarea id="ford_email_body" class="large-text" rows="6" name="ford_settings[email_body]">' . esc_textarea( $settings['email_body'] ) . '</textarea><p class="description">' . esc_html__( 'Available tokens: {site_name}, {customer_name}, {first_name}, {order_number}, {order_total}, {payment_url}', 'failed-order-rescue-for-woocommerce' ) . '</p></td></tr>';
		echo '<tr><th scope="row"><label for="ford_from_name">' . esc_html__( 'From name', 'failed-order-rescue-for-woocommerce' ) . '</label></th><td><input id="ford_from_name" type="text" class="regular-text" name="ford_settings[from_name]" value="' . esc_attr( $settings['from_name'] ) . '"></td></tr>';
		echo '<tr><th scope="row"><label for="ford_from_email">' . esc_html__( 'From email', 'failed-order-rescue-for-woocommerce' ) . '</label></th><td><input id="ford_from_email" type="email" class="regular-text" name="ford_settings[from_email]" value="' . esc_attr( $settings['from_email'] ) . '"></td></tr>';
		echo '<tr><th scope="row">' . esc_html__( 'Uninstall cleanup', 'failed-order-rescue-for-woocommerce' ) . '</th><td><label><input type="checkbox" name="ford_settings[delete_data_on_uninstall]" value="yes" ' . checked( 'yes', $settings['delete_data_on_uninstall'], false ) . '> ' . esc_html__( 'Delete plugin settings when the plugin is uninstalled.', 'failed-order-rescue-for-woocommerce' ) . '</label></td></tr>';
		echo '</tbody></table>';

		submit_button();
		echo '</form>';
	}
}
