<?php // phpcs:ignore WordPress.Files.FileName.NotHyphenatedLowercase, WordPress.Files.FileName.InvalidClassFileName
/**
 * Wholesale pricing admin hook handler.
 *
 * @package Autoship\Modules\WholesalePricing\Services
 * @since   2.13.0
 */

namespace Autoship\Modules\WholesalePricing\Services;

use Autoship\Repositories\WholesaleDiscountRepositoryInterface;

/**
 * Handles admin-area hook callbacks for wholesale pricing.
 *
 * Covers product edit fields, save handlers, and export file download.
 *
 * @package Autoship\Modules\WholesalePricing\Services
 * @since   2.13.0
 */
class WholesaleAdminHandler {

	/**
	 * The discount repository.
	 *
	 * @var WholesaleDiscountRepositoryInterface
	 */
	private WholesaleDiscountRepositoryInterface $discount_repository;

	/**
	 * Constructor.
	 *
	 * @param WholesaleDiscountRepositoryInterface $discount_repository The discount repository.
	 */
	public function __construct( WholesaleDiscountRepositoryInterface $discount_repository ) {
		$this->discount_repository = $discount_repository;
	}

	/**
	 * Outputs the Wholesale Discount Field for simple products.
	 *
	 * Hooked to autoship_after_print_product_custom_fields.
	 *
	 * @param \WC_Product $_product The current WooCommerce product.
	 *
	 * @return void
	 */
	public function schedule_order_wholesale_discount( $_product ) {
		?>
		<div class="autoship_scheduled_order_wholesale_extension_settings autoship-sync-active-option-group">

			<h4><?php echo esc_html( __( 'Autoship Cloud Wholesale Settings', 'autoship' ) ); ?></h4>

			<div class="options_group autoship_scheduled_order_wholesale_extension">

				<?php
				woocommerce_wp_text_input(
					array(
						'id'          => '_autoship_schedule_order_wholesale_discount',
						'label'       => __( 'Discount Percentage', 'autoship' ),
						'description' => __( 'Enter an additional discount percentage to apply to the checkout & recurring price for Wholesale Autoship products.', 'autoship' ),
						'placeholder' => __( '(Optional)', 'autoship' ),
						'data_type'   => 'decimal',
						'value'       => $this->get_product_wholesale_discount( $_product->get_id() ),
						'desc_tip'    => true,
					)
				);
				?>
			</div>

		</div>

		<?php
	}

	/**
	 * Outputs the Wholesale Discount Field for variations.
	 *
	 * Hooked to autoship_after_print_variable_product_custom_fields.
	 *
	 * @param int      $loop           The current loop index.
	 * @param array    $variation_data The current variation data.
	 * @param \WP_Post $variation      The current variation post object.
	 *
	 * @return void
	 */
	public function schedule_order_variation_wholesale_discount( $loop, $variation_data, $variation ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassAfterLastUsed
		?>
		<div class="autoship_scheduled_order_wholesale_extension_settings data">

			<h4><?php echo esc_html( __( 'Autoship Cloud Wholesale Settings', 'autoship' ) ); ?></h4>

			<div class="options_group autoship_scheduled_order_wholesale_extension">

				<?php
				woocommerce_wp_text_input(
					array(
						'id'          => '_autoship_schedule_order_wholesale_discount' . $loop,
						'name'        => "_autoship_schedule_order_wholesale_discount[{$loop}]",
						'label'       => __( 'Discount Percentage', 'autoship' ),
						'description' => __( 'Enter an additional discount percentage to apply to the checkout & recurring price for Wholesale Autoship products.', 'autoship' ),
						'placeholder' => __( '(Optional)', 'autoship' ),
						'data_type'   => 'decimal',
						'value'       => $this->get_product_wholesale_discount( $variation->ID ),
						'desc_tip'    => true,
					)
				);
				?>
			</div>
		</div>
		<?php
	}

	/**
	 * Saves the Autoship Custom Field(s) for Products and Variations.
	 *
	 * Hooked to woocommerce_process_product_meta and woocommerce_save_product_variation.
	 *
	 * @param int      $id    The product/variation ID.
	 * @param int|null $index The current variation index. Default null.
	 *
	 * @return void
	 */
	public function save_product_custom_options( $id, $index = null ) {
		if ( null === $index ) {
			$value = isset( $_POST['_autoship_schedule_order_wholesale_discount'] ) ? floatval( $_POST['_autoship_schedule_order_wholesale_discount'] ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing,WordPress.Security.ValidatedSanitizedInput.MissingUnslash,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		} else {
			$value = isset( $_POST['_autoship_schedule_order_wholesale_discount'] ) && isset( $_POST['_autoship_schedule_order_wholesale_discount'][ $index ] ) ? floatval( $_POST['_autoship_schedule_order_wholesale_discount'][ $index ] ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing,WordPress.Security.ValidatedSanitizedInput.MissingUnslash,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		}

		$this->discount_repository->set_discount( $id, (float) $value );
	}

	/**
	 * Checks for download init and echoes the file.
	 *
	 * Hooked to admin_init.
	 *
	 * @return void
	 */
	public function download_export_file() {
		if ( ! isset( $_GET['autoship_download_wholesale_pricing_export_file'] ) || empty( $_GET['autoship_download_wholesale_pricing_export_file'] ) || ! current_user_can( 'export' ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			return;
		}

		$file = $_GET['autoship_download_wholesale_pricing_export_file']; // phpcs:ignore WordPress.Security.NonceVerification.Recommended,WordPress.Security.ValidatedSanitizedInput.MissingUnslash,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		$path = trailingslashit( autoship_get_export_directory() );

		if ( ! file_exists( realpath( $path . $file ) ) ) {
			return;
		}

		header( 'Content-Type: application/csv' );
		header( 'Content-Disposition: attachment;filename="' . $file . '"' );
		header( 'Cache-Control: max-age=0' );
		header( 'Expires: Mon, 26 Jul 1997 05:00:00 GMT' );
		header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
		header( 'Cache-Control: private, max-age=0, must-revalidate' );
		header( 'Pragma: public' );
		$contents = file_get_contents( $path . $file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
		echo $contents; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		exit();
	}

	/**
	 * Gets the product wholesale discount from the repository.
	 *
	 * @param int $product_id The product ID.
	 *
	 * @return float|null
	 */
	private function get_product_wholesale_discount( $product_id ) {
		return $this->discount_repository->get_discount( (int) $product_id );
	}
}
