<?php

namespace Discountify\Core\Admin;

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

use Discountify\Utils\Singleton;

/**
 * Import/Export Discount Rules
 *
 * @since 1.0.86
 */
class ImportExport {

	use Singleton;

	/**
	 * Meta keys to export/import for each rule
	 */
	private $meta_keys = array(
		'rules_type',
		'enable_rules',
		'discount_type',
		'discount_in',
		'filter_by_products',
		'filter_by_category',
		'discount_number',
		'discount_label',
		'bogo_discount_type',
		'multi_discounts',
		'bogo_discount_in',
		'enable_user_discount',
		'disc_user_roles',
		'user_discount_condition',
		'specific_customers',
		'discount_valid',
		'free_shipping_based_on',
		'free_shipping_products',
		'free_shipping_categories',
		'free_shipping_min_amount',
		'cart_discount_on',
	);

	/**
	 * Initialize hooks
	 */
	public function init() {
		add_action( 'admin_init', array( $this, 'handle_export' ) );
		add_action( 'admin_init', array( $this, 'handle_import' ) );
		add_action( 'admin_notices', array( $this, 'import_notices' ) );
	}

	/**
	 * Handle export request
	 */
	public function handle_export() {
		if ( empty( $_GET['discountify_action'] ) || $_GET['discountify_action'] !== 'export_rules' ) {
			return;
		}

		if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_GET['_wpnonce'] ), 'discountify_export_rules' ) ) {
			wp_die( esc_html__( 'Security check failed.', 'discountify' ) );
		}

		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( esc_html__( 'You do not have permission to export rules.', 'discountify' ) );
		}

		$rules = $this->get_export_data();

		if ( empty( $rules ) ) {
			wp_die( esc_html__( 'No discount rules found to export.', 'discountify' ) );
		}

		$export_data = array(
			'plugin'      => 'discountify',
			'version'     => \Discountify::get_version(),
			'export_date' => current_time( 'mysql' ),
			'rules_count' => count( $rules ),
			'rules'       => $rules,
		);

		$filename = 'discountify-rules-' . gmdate( 'Y-m-d-His' ) . '.json';

		nocache_headers();
		header( 'Content-Type: application/json; charset=utf-8' );
		header( 'Content-Disposition: attachment; filename=' . $filename );
		header( 'Expires: 0' );

		echo wp_json_encode( $export_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE );
		exit;
	}

	/**
	 * Get all rules data for export
	 */
	private function get_export_data() {
		$all_rules = get_posts(
			array(
				'post_type'      => 'discountify_rules',
				'posts_per_page' => -1,
				'post_status'    => 'publish',
			)
		);

		$export_rules = array();

		foreach ( $all_rules as $rule_post ) {
			$rule_data = array(
				'discount_name' => $rule_post->post_title,
			);

			foreach ( $this->meta_keys as $meta_key ) {
				$value = get_post_meta( $rule_post->ID, $meta_key, true );
				$rule_data[ $meta_key ] = $value;
			}

			$export_rules[] = $rule_data;
		}

		return $export_rules;
	}

	/**
	 * Handle import request
	 */
	public function handle_import() {
		if ( empty( $_POST['discountify_action'] ) || $_POST['discountify_action'] !== 'import_rules' ) {
			return;
		}

		if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['_wpnonce'] ), 'discountify_import_rules' ) ) {
			wp_die( esc_html__( 'Security check failed.', 'discountify' ) );
		}

		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( esc_html__( 'You do not have permission to import rules.', 'discountify' ) );
		}

		if ( empty( $_FILES['discountify_import_file'] ) || empty( $_FILES['discountify_import_file']['tmp_name'] ) ) {
			$this->set_import_notice( 'error', __( 'Please select a JSON file to import.', 'discountify' ) );
			$this->redirect_back();
			return;
		}

		$file = $_FILES['discountify_import_file'];

		// Validate file type
		$file_ext = pathinfo( $file['name'], PATHINFO_EXTENSION );
		if ( strtolower( $file_ext ) !== 'json' ) {
			$this->set_import_notice( 'error', __( 'Invalid file type. Please upload a JSON file.', 'discountify' ) );
			$this->redirect_back();
			return;
		}

		// Read and parse JSON
		$file_contents = file_get_contents( $file['tmp_name'] ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
		$import_data   = json_decode( $file_contents, true );

		if ( json_last_error() !== JSON_ERROR_NONE || empty( $import_data ) ) {
			$this->set_import_notice( 'error', __( 'Invalid JSON file. Could not parse the file contents.', 'discountify' ) );
			$this->redirect_back();
			return;
		}

		// Validate structure - accept both free and pro exports
		if ( empty( $import_data['plugin'] ) || ! in_array( $import_data['plugin'], array( 'discountify', 'discountify-pro' ), true ) ) {
			$this->set_import_notice( 'error', __( 'Invalid export file. This file was not exported from Discountify.', 'discountify' ) );
			$this->redirect_back();
			return;
		}

		if ( empty( $import_data['rules'] ) || ! is_array( $import_data['rules'] ) ) {
			$this->set_import_notice( 'error', __( 'No discount rules found in the import file.', 'discountify' ) );
			$this->redirect_back();
			return;
		}

		// Import rules
		$imported = 0;
		$failed   = 0;

		foreach ( $import_data['rules'] as $rule_data ) {
			$result = $this->import_single_rule( $rule_data );
			if ( $result ) {
				$imported++;
			} else {
				$failed++;
			}
		}

		$message = sprintf(
			/* translators: %1$d: imported count */
			__( 'Import complete. %1$d rules imported successfully.', 'discountify' ),
			$imported
		);
		if ( $failed > 0 ) {
			$message .= ' ' . sprintf(
				/* translators: %d: failed count */
				__( '%d rules failed to import.', 'discountify' ),
				$failed
			);
		}

		$this->set_import_notice( 'success', $message );
		$this->redirect_back();
	}

	/**
	 * Import a single rule
	 */
	private function import_single_rule( $rule_data ) {
		$discount_name = ! empty( $rule_data['discount_name'] ) ? sanitize_text_field( $rule_data['discount_name'] ) : __( 'Imported Rule', 'discountify' );

		$post_id = wp_insert_post(
			array(
				'post_title'   => $discount_name,
				'post_type'    => 'discountify_rules',
				'post_content' => '',
				'post_status'  => 'publish',
			)
		);

		if ( is_wp_error( $post_id ) || empty( $post_id ) ) {
			return false;
		}

		foreach ( $this->meta_keys as $meta_key ) {
			if ( isset( $rule_data[ $meta_key ] ) ) {
				$value = $rule_data[ $meta_key ];
				// Sanitize string values
				if ( is_string( $value ) ) {
					$value = sanitize_text_field( $value );
				}
				update_post_meta( $post_id, $meta_key, $value );
			}
		}

		return true;
	}

	/**
	 * Store import notice in transient
	 */
	private function set_import_notice( $type, $message ) {
		set_transient(
			'discountify_import_notice',
			array(
				'type'    => $type,
				'message' => $message,
			),
			60
		);
	}

	/**
	 * Redirect back to rules page
	 */
	private function redirect_back() {
		wp_safe_redirect( admin_url( 'admin.php?page=discountify-rules' ) );
		exit;
	}

	/**
	 * Display import notices
	 */
	public function import_notices() {
		$notice = get_transient( 'discountify_import_notice' );
		if ( empty( $notice ) ) {
			return;
		}

		delete_transient( 'discountify_import_notice' );

		$type = $notice['type'] === 'success' ? 'success' : 'error';
		?>
		<div class="notice notice-<?php echo esc_attr( $type ); ?> is-dismissible">
			<p><?php echo esc_html( $notice['message'] ); ?></p>
		</div>
		<?php
	}
}
