<?php
defined( 'ABSPATH' ) || exit;

class Woocom_Pay_Admin {

	public static function init(): void {
		add_action( 'admin_menu', [ __CLASS__, 'add_menu_pages' ] );
		add_action( 'admin_init', [ __CLASS__, 'handle_settings_save' ] );
		add_action( 'admin_init', [ __CLASS__, 'handle_verification_action' ] );
		add_action( 'admin_enqueue_scripts', [ __CLASS__, 'enqueue_assets' ] );

		// Order detail meta-box.
		add_action( 'add_meta_boxes', [ __CLASS__, 'add_order_meta_box' ] );

		// Order list column — HPOS.
		add_filter( 'manage_woocommerce_page_wc-orders_columns', [ __CLASS__, 'add_order_column' ] );
		add_action( 'manage_woocommerce_page_wc-orders_custom_column', [ __CLASS__, 'render_order_column' ], 10, 2 );
		// Order list column — legacy CPT.
		add_filter( 'manage_edit-shop_order_columns', [ __CLASS__, 'add_order_column' ] );
		add_action( 'manage_shop_order_posts_custom_column', [ __CLASS__, 'render_order_column_legacy' ], 10, 2 );
	}

	public static function add_menu_pages(): void {
		add_submenu_page(
			'woocommerce',
			__( 'Woocom-Pay Settings', 'woocom-pay' ),
			__( 'Woocom-Pay', 'woocom-pay' ),
			'manage_woocommerce',
			'woocom-pay-settings',
			[ __CLASS__, 'render_settings_page' ]
		);

		add_submenu_page(
			'woocommerce',
			__( 'Woocom-Pay Verification', 'woocom-pay' ),
			__( 'UPI Verification', 'woocom-pay' ),
			'manage_woocommerce',
			'woocom-pay-verify',
			[ __CLASS__, 'render_verification_page' ]
		);
	}

	public static function enqueue_assets( string $hook ): void {
		if ( strpos( $hook, 'woocom-pay' ) === false ) {
			return;
		}
		wp_enqueue_style( 'woocom-pay-admin', WOOCOM_PAY_PLUGIN_URL . 'admin/css/admin.css', [], WOOCOM_PAY_VERSION );
		wp_enqueue_media();
	}

	// -------------------------------------------------------------------------
	// Settings page
	// -------------------------------------------------------------------------

	public static function handle_settings_save(): void {
		if ( ! isset( $_POST['wcp_settings_nonce'] ) ) {
			return;
		}
		if ( ! wp_verify_nonce( sanitize_text_field( $_POST['wcp_settings_nonce'] ), 'wcp_save_settings' ) ) {
			wp_die( esc_html__( 'Security check failed.', 'woocom-pay' ) );
		}
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( esc_html__( 'Permission denied.', 'woocom-pay' ) );
		}

		// ── License activate / deactivate ───────────────────────────────────────
		if ( ! empty( $_POST['wcp_activate_license'] ) ) {
			$key = sanitize_text_field( $_POST['wcp_license_key_input'] ?? '' );
			if ( WCP_License::activate( $key ) ) {
				add_settings_error( 'woocom_pay', 'license_activated', __( 'Pro license activated. All Pro features are now unlocked.', 'woocom-pay' ), 'success' );
			} else {
				add_settings_error( 'woocom_pay', 'license_invalid', __( 'Invalid license key. Please check the key and try again.', 'woocom-pay' ), 'error' );
			}
			return;
		}

		if ( ! empty( $_POST['wcp_deactivate_license'] ) && '1' === $_POST['wcp_deactivate_license'] ) {
			WCP_License::deactivate();
			add_settings_error( 'woocom_pay', 'license_deactivated', __( 'License deactivated.', 'woocom-pay' ), 'updated' );
			return;
		}

		// Preserve merchant_name/upi_id/qr_image — owned by WooCommerce gateway settings.
		$existing = get_option( 'woocom_pay_settings', [] );

		// ── Gateway configs ──────────────────────────────────────────────────
		// phpcs:disable WordPress.Security.NonceVerification.Missing
		$posted_gw = $_POST['gateways'] ?? [];
		// phpcs:enable WordPress.Security.NonceVerification.Missing

		$razorpay = [
			'enabled'        => ! empty( $posted_gw['razorpay']['enabled'] ) ? '1' : '',
			'test_mode'      => ! empty( $posted_gw['razorpay']['test_mode'] ) ? '1' : '',
			'key_id'         => sanitize_text_field( $posted_gw['razorpay']['key_id'] ?? '' ),
			'key_secret'     => sanitize_text_field( $posted_gw['razorpay']['key_secret'] ?? '' ),
			'webhook_secret' => sanitize_text_field( $posted_gw['razorpay']['webhook_secret'] ?? '' ),
		];

		$cashfree = [
			'enabled'        => ! empty( $posted_gw['cashfree']['enabled'] ) ? '1' : '',
			'test_mode'      => ! empty( $posted_gw['cashfree']['test_mode'] ) ? '1' : '',
			'app_id'         => sanitize_text_field( $posted_gw['cashfree']['app_id'] ?? '' ),
			'secret_key'     => sanitize_text_field( $posted_gw['cashfree']['secret_key'] ?? '' ),
			'webhook_secret' => sanitize_text_field( $posted_gw['cashfree']['webhook_secret'] ?? '' ),
		];

		$custom = [
			'enabled'          => ! empty( $posted_gw['custom']['enabled'] ) ? '1' : '',
			'name'             => sanitize_text_field( $posted_gw['custom']['name'] ?? '' ),
			'payment_url'      => esc_url_raw( $posted_gw['custom']['payment_url'] ?? '' ),
			'api_key_header'   => sanitize_text_field( $posted_gw['custom']['api_key_header'] ?? '' ),
			'api_key_value'    => sanitize_text_field( $posted_gw['custom']['api_key_value'] ?? '' ),
			'webhook_secret'   => sanitize_text_field( $posted_gw['custom']['webhook_secret'] ?? '' ),
			'success_param'    => sanitize_key( $posted_gw['custom']['success_param'] ?? 'status' ),
			'success_value'    => sanitize_text_field( $posted_gw['custom']['success_value'] ?? 'success' ),
		];

		$upi_enabled = ! empty( $posted_gw['upi']['enabled'] ) ? '1' : '';

		// Preserve secrets if a masked placeholder was posted (empty = no change).
		foreach ( [ 'key_secret', 'webhook_secret' ] as $field ) {
			if ( empty( $razorpay[ $field ] ) && ! empty( $existing['gateways']['razorpay'][ $field ] ) ) {
				$razorpay[ $field ] = $existing['gateways']['razorpay'][ $field ];
			}
		}
		foreach ( [ 'secret_key', 'webhook_secret' ] as $field ) {
			if ( empty( $cashfree[ $field ] ) && ! empty( $existing['gateways']['cashfree'][ $field ] ) ) {
				$cashfree[ $field ] = $existing['gateways']['cashfree'][ $field ];
			}
		}
		foreach ( [ 'api_key_value', 'webhook_secret' ] as $field ) {
			if ( empty( $custom[ $field ] ) && ! empty( $existing['gateways']['custom'][ $field ] ) ) {
				$custom[ $field ] = $existing['gateways']['custom'][ $field ];
			}
		}

		// phpcs:disable WordPress.Security.NonceVerification.Missing
		$settings = array_merge( $existing, [
			'admin_email'       => sanitize_email( $_POST['admin_email'] ?? get_option( 'admin_email' ) ),
			'enable_full'            => ! empty( $_POST['enable_full'] ) ? '1' : '',
			'enable_partial'         => ! empty( $_POST['enable_partial'] ) ? '1' : '',
			'partial_default_type'   => in_array( $_POST['partial_default_type'] ?? '', [ 'percentage', 'fixed' ], true ) ? $_POST['partial_default_type'] : 'percentage',
			'partial_default_value'  => (float) ( $_POST['partial_default_value'] ?? 50 ),
			'enable_txn_id'     => ! empty( $_POST['enable_txn_id'] ) ? '1' : '',
			'enable_screenshot' => ! empty( $_POST['enable_screenshot'] ) ? '1' : '',
			'enable_approval'   => ! empty( $_POST['enable_approval'] ) ? '1' : '',
			'enable_emails'     => ! empty( $_POST['enable_emails'] ) ? '1' : '',
			'enable_balance'    => ! empty( $_POST['enable_balance'] ) ? '1' : '',
			'gateways'          => [
				'upi'       => [ 'enabled' => $upi_enabled ],
				'razorpay'  => $razorpay,
				'cashfree'  => $cashfree,
				'custom'    => $custom,
			],
		] );
		// phpcs:enable WordPress.Security.NonceVerification.Missing

		update_option( 'woocom_pay_settings', $settings );
		add_settings_error( 'woocom_pay', 'settings_saved', __( 'Settings saved.', 'woocom-pay' ), 'success' );
	}

	public static function render_settings_page(): void {
		$settings = get_option( 'woocom_pay_settings', [] );
		include WOOCOM_PAY_PLUGIN_DIR . 'admin/views/settings.php';
	}

	// -------------------------------------------------------------------------
	// Verification page
	// -------------------------------------------------------------------------

	public static function handle_verification_action(): void {
		if ( empty( $_POST['wcp_verify_nonce'] ) ) {
			return;
		}
		if ( ! wp_verify_nonce( sanitize_text_field( $_POST['wcp_verify_nonce'] ), 'wcp_verify_action' ) ) {
			wp_die( esc_html__( 'Security check failed.', 'woocom-pay' ) );
		}
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( esc_html__( 'Permission denied.', 'woocom-pay' ) );
		}

		$action   = sanitize_text_field( $_POST['wcp_action'] ?? '' );
		$txn_id   = (int) ( $_POST['wcp_txn_id'] ?? 0 );
		$order_id = (int) ( $_POST['wcp_order_id'] ?? 0 );
		$reason   = sanitize_textarea_field( $_POST['rejection_reason'] ?? '' );

		if ( ! in_array( $action, [ 'approve', 'reject' ], true ) || ! $txn_id || ! $order_id ) {
			return;
		}

		$order = wc_get_order( $order_id );
		$txn   = Woocom_Pay_DB::get_by_id( $txn_id );

		if ( ! $order || ! $txn ) {
			return;
		}

		$now = current_time( 'mysql' );

		if ( $action === 'approve' ) {
			Woocom_Pay_DB::update(
				[
					'verification_status' => 'approved',
					'verified_by'         => get_current_user_id(),
					'verified_at'         => $now,
				],
				[ 'id' => $txn_id ]
			);

			$payment_type = $txn['payment_type'];

			if ( $payment_type === 'balance' ) {
				$order->update_meta_data( '_wcp_balance_amount', 0 );
				$order->update_status( 'completed', __( 'Balance payment verified.', 'woocom-pay' ) );
				$order->payment_complete( $txn['transaction_id'] );
			} elseif ( $payment_type === 'partial' ) {
				$order->update_status( 'bal-pending', __( 'Advance payment verified. Balance pending.', 'woocom-pay' ) );
			} else {
				$order->update_status( 'pay-verified', __( 'UPI payment verified by admin.', 'woocom-pay' ) );
				$order->payment_complete( $txn['transaction_id'] );
			}

			$order->save();
			Woocom_Pay_Emails::send_customer_payment_approved( $order );

			if ( ! empty( $_POST['send_balance_link'] ) && $payment_type === 'partial' ) {
				$link = Woocom_Pay_Balance::get_balance_link( $order_id );
				Woocom_Pay_Emails::send_customer_balance_reminder( $order, $link );
			}

			add_settings_error( 'woocom_pay', 'approved', __( 'Payment approved.', 'woocom-pay' ), 'success' );
		} else {
			Woocom_Pay_DB::update(
				[
					'verification_status' => 'rejected',
					'verified_by'         => get_current_user_id(),
					'verified_at'         => $now,
				],
				[ 'id' => $txn_id ]
			);

			$order->update_status( 'pay-rejected', __( 'UPI payment rejected by admin.', 'woocom-pay' ) );
			$order->save();
			Woocom_Pay_Emails::send_customer_payment_rejected( $order, $reason );

			add_settings_error( 'woocom_pay', 'rejected', __( 'Payment rejected.', 'woocom-pay' ), 'error' );
		}
	}

	public static function render_verification_page(): void {
		$order_id = isset( $_GET['order_id'] ) ? (int) $_GET['order_id'] : 0;
		include WOOCOM_PAY_PLUGIN_DIR . 'admin/views/verification.php';
	}

	// -------------------------------------------------------------------------
	// Order meta-box
	// -------------------------------------------------------------------------

	public static function add_order_meta_box(): void {
		$screen = class_exists( '\Automattic\WooCommerce\Internal\DataStores\Orders\CustomOrdersTableController' )
			&& wc_get_container()->get( \Automattic\WooCommerce\Internal\DataStores\Orders\CustomOrdersTableController::class )->custom_orders_table_usage_is_enabled()
			? wc_get_page_screen_id( 'shop-order' )
			: 'shop_order';

		add_meta_box(
			'wcp_order_details',
			__( 'Woocom-Pay Details', 'woocom-pay' ),
			[ __CLASS__, 'render_order_meta_box' ],
			$screen,
			'side',
			'high'
		);
	}

	public static function render_order_meta_box( $post_or_order ): void {
		$order = ( $post_or_order instanceof WC_Order ) ? $post_or_order : wc_get_order( $post_or_order->ID );
		if ( ! $order ) {
			return;
		}

		$paid    = (float) $order->get_meta( '_wcp_paid_amount' );
		$balance = (float) $order->get_meta( '_wcp_balance_amount' );
		$total   = (float) $order->get_meta( '_wcp_product_total' );
		$txns    = Woocom_Pay_DB::get_by_order( $order->get_id() );

		if ( ! $total ) {
			echo '<p>' . esc_html__( 'No Woocom-Pay transaction data.', 'woocom-pay' ) . '</p>';
			return;
		}
		?>
		<table class="widefat striped" style="font-size:12px;">
			<tr><th><?php esc_html_e( 'Product Total', 'woocom-pay' ); ?></th><td><?php echo wc_price( $total ); ?></td></tr>
			<tr><th><?php esc_html_e( 'Amount Paid', 'woocom-pay' ); ?></th><td><?php echo wc_price( $paid ); ?></td></tr>
			<tr><th><?php esc_html_e( 'Balance Due', 'woocom-pay' ); ?></th><td><?php echo wc_price( $balance ); ?></td></tr>
		</table>
		<?php if ( $txns ) : ?>
		<h4 style="margin:10px 0 5px;"><?php esc_html_e( 'Transactions', 'woocom-pay' ); ?></h4>
		<?php foreach ( $txns as $t ) : ?>
			<div style="border:1px solid #ddd;padding:6px;margin-bottom:6px;font-size:11px;">
				<strong><?php echo esc_html( ucfirst( $t['payment_type'] ) ); ?></strong> &mdash;
				<?php echo esc_html( $t['verification_status'] ); ?><br>
				<?php if ( $t['transaction_id'] ) : ?>
				<?php esc_html_e( 'TXN:', 'woocom-pay' ); ?> <?php echo esc_html( $t['transaction_id'] ); ?><br>
				<?php endif; ?>
				<?php if ( $t['screenshot_path'] ) : ?>
				<a href="<?php echo esc_url( $t['screenshot_path'] ); ?>" target="_blank"><?php esc_html_e( 'View Screenshot', 'woocom-pay' ); ?></a>
				<?php endif; ?>
			</div>
		<?php endforeach; ?>
		<?php endif; ?>

		<?php if ( $balance > 0 ) : ?>
		<p><a class="button button-small" href="<?php echo esc_url( Woocom_Pay_Balance::get_balance_link( $order->get_id() ) ); ?>" target="_blank"><?php esc_html_e( 'Balance Payment Link', 'woocom-pay' ); ?></a></p>
		<?php endif; ?>
		<?php
	}

	// -------------------------------------------------------------------------
	// Order list column
	// -------------------------------------------------------------------------

	public static function add_order_column( array $columns ): array {
		$new = [];
		foreach ( $columns as $key => $label ) {
			$new[ $key ] = $label;
			if ( $key === 'order_total' ) {
				$new['wcp_status'] = __( 'UPI Verification', 'woocom-pay' );
			}
		}
		return $new;
	}

	public static function render_order_column( string $column, WC_Order $order ): void {
		if ( $column !== 'wcp_status' ) {
			return;
		}
		$txns = Woocom_Pay_DB::get_by_order( $order->get_id() );
		if ( empty( $txns ) ) {
			echo '&mdash;';
			return;
		}
		$latest = end( $txns );
		$status = $latest['verification_status'];
		$colors = [
			'pending'  => '#e67e22',
			'approved' => '#27ae60',
			'rejected' => '#e74c3c',
		];
		$color = $colors[ $status ] ?? '#999';
		echo '<span style="color:' . esc_attr( $color ) . ';font-weight:600;">' . esc_html( ucfirst( $status ) ) . '</span>';
	}

	public static function render_order_column_legacy( string $column, int $post_id ): void {
		$order = wc_get_order( $post_id );
		if ( $order ) {
			self::render_order_column( $column, $order );
		}
	}
}
