<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://wpiron.com/
 * @since      1.0.0
 *
 * @package    Cost_Of_Goods_For_Woocommerce
 * @subpackage Cost_Of_Goods_For_Woocommerce/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Cost_Of_Goods_For_Woocommerce
 * @subpackage Cost_Of_Goods_For_Woocommerce/admin
 * @author     WPiron <info@wpiron.com>
 */
class Cost_Of_Goods_For_Woocommerce_Admin {

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string $plugin_name The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string $version The current version of this plugin.
	 */
	private $version;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @param string $plugin_name The name of this plugin.
	 * @param string $version The version of this plugin.
	 *
	 * @since    1.0.0
	 */
	public function __construct( $plugin_name, $version ) {
		$this->plugin_name = $plugin_name;
		$this->version     = $version;
	}

	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles() {
		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Cost_Of_Goods_For_Woocommerce_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Cost_Of_Goods_For_Woocommerce_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */

		wp_enqueue_style(
			$this->plugin_name,
			plugin_dir_url( __FILE__ ) . 'css/cost-of-goods-for-woocommerce-admin.min.css',
			array(),
			$this->version,
			'all'
		);
	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts() {
		wp_enqueue_script(  // jQuery
			$this->plugin_name,
			plugin_dir_url( __FILE__ ) . 'js/cost-of-goods-for-woocommerce-admin.min.js',
			array( 'jquery' ),
			$this->version,
			true
		);
	}

	public function save_fields( $postId ) {
		// Check if nonce is set and verify it
		if (!isset($_POST['cost_of_goods_nonce']) || !wp_verify_nonce($_POST['cost_of_goods_nonce'], 'cost_of_goods_save_data')) {
			return;
		}

		// Check user permissions
		if (!current_user_can('edit_post', $postId)) {
			return;
		}
        
		$product = wc_get_product( $postId );
		
		// Check if POST variables exist before accessing them
		$costOfGoodPrice = isset($_POST['cost_of_goods']) ? sanitize_text_field($_POST['cost_of_goods']) : '';
		$profitFinalPrice = isset($_POST['profit']) ? sanitize_text_field($_POST['profit']) : '';
		$rewriteRegularPriceChecked = isset( $_POST['rewrite_regular_price'] ) ? 'yes' : 'no';
		$regularMinusVat = isset($_POST['regular_price_vat']) ? sanitize_text_field($_POST['regular_price_vat']) : '';

		// Validate numeric values
		$costOfGoodPriceFiltered = $this->validate_price($costOfGoodPrice);
		$profitPriceFiltered = $this->validate_price($profitFinalPrice);
		$regularMinusVatFiltered = $this->validate_price($regularMinusVat);

		$error = false;
		$error_type = null;

		if ( $costOfGoodPriceFiltered === false ) {
			$error      = true;
			$error_type = new \WP_Error(
				'cog_for_woocommerce_string_error',
				__( "Cost Of Good price is not correct", 'cost-of-goods-for-woocommerce' ),
				array( 'status' => 400 )
			);
		}

		if ( $profitPriceFiltered === false ) {
			$error      = true;
			$error_type = new \WP_Error(
				'cog_for_woocommerce_number_error',
				__( "Cost Of Goods profit price is not correct", 'cost-of-goods-for-woocommerce' ),
				array( 'status' => 400 )
			);
		}

		if ( ! $error ) {
			$product->update_meta_data( 'cost_of_goods', $costOfGoodPriceFiltered );
			$product->update_meta_data( 'profit', $profitPriceFiltered );
			$product->update_meta_data( 'regular_price_vat', $regularMinusVatFiltered );
			$product->update_meta_data( 'rewrite_regular_price', $rewriteRegularPriceChecked );
			$product->save();
		} else {
			return $error_type;
		}
	}

	/**
	 * Validate price input
	 *
	 * @since    1.0.0
	 * @param    string    $price    Price to validate
	 * @return   string|bool    Formatted price or false if invalid
	 */
	private function validate_price($price) {
		// Remove any non-numeric characters except decimal point
		$price = preg_replace('/[^0-9.]/', '', $price);
		
		// Check if the result is a valid number
		if (is_numeric($price)) {
			// Format it to ensure proper decimal format
			return wc_format_decimal($price);
		}
		
		return false;
	}

	/**
	 * Display custom fields in the product edit page
	 *
	 * @since    1.0.0
	 * @return   void
	 */
	public function product_custom_fields() {
		global $woocommerce, $post;
		echo '<div class="product_custom_field">';
		echo '<br/>';
		
		// Add nonce field for security
		wp_nonce_field('cost_of_goods_save_data', 'cost_of_goods_nonce');

		woocommerce_wp_text_input(
			array(
				'id'    => 'cost_of_goods',
				'label' => __( 'Cost Of Good', 'cost-of-goods-for-woocommerce' ),
				'value' => get_post_meta( $post->ID, 'cost_of_goods', true ),
			)
		);

		$rewrite_regular_price_checked = get_post_meta( $post->ID, 'rewrite_regular_price', true ) === 'yes';
		woocommerce_wp_checkbox( array(
			'id'    => 'rewrite_regular_price',
			'label' => __( 'Rewrite Regular Price?', 'cost-of-goods-for-woocommerce' ),
			'value' => $rewrite_regular_price_checked ? 'yes' : 'no',
			'checked' => $rewrite_regular_price_checked, // This ensures the checkbox is checked if needed
		) );

		// Determine if the Regular Price - VAT field should be disabled
		$regular_price_vat_disabled = $rewrite_regular_price_checked ? array() : array( 'disabled' => 'disabled' );
		woocommerce_wp_text_input(
			array(
				'id'                => 'regular_price_vat',
				'label'             => __( 'Regular Price - VAT', 'cost-of-goods-for-woocommerce' ),
				'custom_attributes' => $regular_price_vat_disabled,
				'value'             => get_post_meta( $post->ID, 'regular_price_vat', true ),
			)
		);

		woocommerce_wp_text_input(
			array(
				'id'                => 'profit',
				'custom_attributes' => array( 'readonly' => 'readonly' ),
				'label'             => __( 'Profit', 'cost-of-goods-for-woocommerce' ),
				'desc_tip'          => 'true',
				'value'             => get_post_meta( $post->ID, 'profit', true ),
			)
		);

		// Better approach: Output the script directly within the form context
		// This ensures it runs after the elements are in the DOM
		?>
		<script type="text/javascript">
		jQuery(document).ready(function($) {
			// Define our toggle function
			function toggleRegularPriceVatField() {
				if ($("#rewrite_regular_price").is(":checked")) {
					$("#regular_price_vat").prop("disabled", false);
				} else {
					$("#regular_price_vat").prop("disabled", true);
				}
			}
			
			// Run on page load
			toggleRegularPriceVatField();
			
			// Attach event listener directly to the element
			$("#rewrite_regular_price").on("change", toggleRegularPriceVatField);
		});
		</script>
		<?php

		echo '</div>';
	}

	/**
	 * Add premium link to plugin actions
	 *
	 * @since    1.0.0
	 * @param    array    $links    Plugin action links
	 * @return   array    Modified action links
	 */
	public function premium_link( $links ) {
		$url  = "https://wpiron.com/products/cost-of-goods-for-woocommerce/#pricing";
		$url2 = "admin.php?page=cost-of-goods-for-wc";

		$settings_link = "<a href='$url2' >" . __( 'Settings' ) . '</a> | ';
		$settings_link .= "<a href='$url' style='font-weight: bold; color: green;' target='_blank'>" . __( 'Get Premium' ) . '</a>';

		$links[] = $settings_link;

		return $links;
	}

	/**
	 * Add admin menu page for the plugin
	 *
	 * @since    1.0.0
	 * @return   void
	 */
	public function wc_markup_admin_menu_page() {
		add_menu_page(
			$this->plugin_name,
			'COG For WC',
			'administrator',
			$this->plugin_name,
			array( $this, 'displayPluginAdminDashboard' ),
			'dashicons-money',
			26
		);
	}

	/**
	 * Add custom column to the products list
	 *
	 * @since    1.0.0
	 * @param    array    $columns    Product columns
	 * @return   array    Modified columns
	 */
	public function custom_product_column_wpiron($columns) {
		$columns['cogs_column'] = __( 'Cost Of Goods', 'wpiron_cogs' );
		return $columns;
	}

	/**
	 * Display content for the custom column
	 *
	 * @since    1.0.0
	 * @param    string    $column    Column name
	 * @param    int       $postid    Product ID
	 * @return   void
	 */
	public function custom_product_column_content_wpiron($column, $postid) {
		if ( 'cogs_column' === $column ) {
			$custom_field_value = get_post_meta( $postid, 'cost_of_goods', true );
			if ( $custom_field_value ) {
				echo wc_price( $custom_field_value );
			} else {
				echo '-';
			}
		}
	}

	/**
	 * Make the custom column sortable
	 *
	 * @since    1.0.0
	 * @param    array    $columns    Sortable columns
	 * @return   array    Modified sortable columns
	 */
	public function custom_product_column_sortable_wpiron($columns) {
		$columns['cogs_column'] = 'cogs_column';
		return $columns;
	}

	/**
	 * Handle the custom column ordering
	 *
	 * @since    1.0.0
	 * @param    WP_Query    $query    The query
	 * @return   void
	 */
	public function custom_product_column_orderby_wpiron($query) {
		if ( ! is_admin() )
			return;

		$orderby = $query->get( 'orderby' );

		if ( 'cogs_column' === $orderby ) {
			$query->set( 'meta_key', 'cost_of_goods' );
			$query->set( 'orderby', 'meta_value' );
		}
	}

	/**
	 * Display the admin dashboard
	 *
	 * @since    1.0.0
	 * @return   void
	 */
	public function displayPluginAdminDashboard() {
		// Define the file path with proper security checks
		$file_path = plugin_dir_path( __FILE__ ) . 'partials/' . $this->plugin_name . '-admin-display.php';
		
		// Check if file exists and is readable before including
		if (file_exists($file_path) && is_readable($file_path)) {
			require_once $file_path;
		} else {
			wp_die(esc_html__('Required file not found or not readable.', 'cost-of-goods-for-woocommerce'));
		}
	}

	public function displayPluginAdminSettings() {
		// Check if tab parameter exists before accessing it
		$tab = isset($_GET['tab']) ? sanitize_key($_GET['tab']) : 'general';

		$active_tab = $tab;
		if ( isset( $_GET['error_message'] ) ) {
			$error_message = sanitize_text_field($_GET['error_message']);
			add_action( 'admin_notices', array( $this, 'pluginNameSettingsMessages' ) );
			do_action( 'admin_notices', $error_message );
		}
		
		// Define the file path with proper security checks
		$file_path = plugin_dir_path( __FILE__ ) . 'partials/' . $this->plugin_name . '-admin-settings-display.php';
		
		// Check if file exists and is readable before including
		if (file_exists($file_path) && is_readable($file_path)) {
			require_once $file_path;
		} else {
			wp_die(esc_html__('Required settings file not found or not readable.', 'cost-of-goods-for-woocommerce'));
		}
	}

	/**
	 * Display admin notices from the API
	 *
	 * @since    1.0.0
	 * @return   void
	 */
	public function wpiron_costofgoods_admin_notice() {
		// Only show notices to administrators
		if (!current_user_can('manage_options')) {
			return;
		}
		
		global $current_user;

		$siteUrl      = site_url();
		$uniqueUserId = md5( $siteUrl );

		$api_url = 'https://uwozfs6rgi.execute-api.us-east-1.amazonaws.com/prod/notifications';
		
		try {
			$body = wp_json_encode( [
				'pluginName' => 'wpiron-wc-cog-free',
				'status'     => true,
				'user_id'    => $uniqueUserId
			] );

			$args = [
				'body'        => $body,
				'headers'     => [
					'Content-Type' => 'application/json',
				],
				'method'      => 'POST',
				'data_format' => 'body',
				'timeout'     => 15, // Add reasonable timeout
				'blocking'    => true,
			];

			$response = wp_remote_post( $api_url, $args );

			if ( is_wp_error( $response ) ) {
				error_log('Cost of Goods plugin API error: ' . $response->get_error_message());
				return;
			}

			$body = wp_remote_retrieve_body( $response );
			
			// Check for valid JSON before processing
			if (empty($body) || !$this->is_json($body)) {
				return;
			}
			
			$data = json_decode( $body, true );
			
			// Validate the response structure before proceeding
			if (!isset($data['statusCode']) || !isset($data['body'])) {
				return;
			}
			
			$status_code = $data['statusCode'];

			if ( !empty( $data ) && $status_code === 200 && $data['body'] !== '[]' ) {
				// Validate data structure before processing
				$parsed_body = json_decode( $data['body'], true );
				if (!is_array($parsed_body) || empty($parsed_body)) {
					return;
				}
				
				$dataEncoded = $parsed_body[0];
				
				// Validate required fields exist
				if (!isset($dataEncoded['content']) || !isset($dataEncoded['dismissed']) || !isset($dataEncoded['message_id'])) {
					return;
				}
				
				if ($dataEncoded['content'] && $dataEncoded['dismissed'] === false) {
					// Sanitize content
					$content = wp_kses_post($dataEncoded['content']);
					$message_id = sanitize_text_field($dataEncoded['message_id']);

					?>
					<div class="notice notice-success is-dismissible">
						<?php echo $content; ?>
						<hr>
						<a style="margin-bottom: 10px; position: relative; display: block;"
						   href="?cost_of_goods_-notice&message_id=<?php echo esc_attr($message_id); ?>">
							<b><?php esc_html_e('Dismiss this notice', 'cost-of-goods-for-woocommerce'); ?></b>
						</a>
					</div>
					<?php
				}
			}
		} catch (Exception $e) {
			error_log('Cost of Goods plugin exception: ' . $e->getMessage());
			return;
		}
	}
	
	/**
	 * Utility function to check if a string is valid JSON
	 *
	 * @param string $string The string to check
	 * @return boolean
	 */
	private function is_json($string) {
		json_decode($string);
		return (json_last_error() == JSON_ERROR_NONE);
	}

	/**
	 * Handle dismissing API notices
	 *
	 * @since    1.0.0
	 * @return   void
	 */
	public function wpiron_costofgoods_ignore_notice_wcmarkup() {
		// Verify user has proper permissions
		if (!current_user_can('manage_options')) {
			return;
		}
		
		global $current_user;

		$siteUrl      = site_url();
		$uniqueUserId = md5( $siteUrl );

		if ( isset( $_GET['cost_of_goods_-notice'] ) && isset( $_GET['message_id'] ) ) {
			// Sanitize and validate the message_id
			$message_id = sanitize_text_field( $_GET['message_id'] );
			
			// Additional validation if needed
			if (empty($message_id)) {
				return;
			}
			
			$apiRequestBody = wp_json_encode( array(
				'user_id'     => $uniqueUserId,
				'plugin_name' => 'wpiron-wc-cog-free',
				'message_id'  => $message_id,
			) );

			$apiResponse = wp_remote_post(
				'https://uwozfs6rgi.execute-api.us-east-1.amazonaws.com/prod/notifications',
				array(
					'body'    => $apiRequestBody,
					'headers' => array(
						'Content-Type' => 'application/json',
					),
					'timeout' => 30, // Add timeout for the request
				)
			);

			if ( is_wp_error( $apiResponse ) ) {
				// Log the error without exposing details
				error_log('Error in Cost of Goods notice dismissal: ' . $apiResponse->get_error_message());
				return;
			}
		}
	}

}