<?php

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

class AIEO_Carts_Frontend {

	const OPT_ENABLED  = 'aieo_carts_save_enabled';
	const OPT_LABEL    = 'aieo_carts_save_label';
	const OPT_TTL_DAYS = 'aieo_carts_saved_ttl_days';
	const QUERY_VAR    = 'aieo_cart';
	const NONCE        = 'aieo_carts';

	
	private static $instance = null;

	
	private $enqueued = false;

	
	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	
	public function register_hooks() {
		add_action( 'wp_enqueue_scripts', array( $this, 'maybe_enqueue' ) );
		add_action( 'wp_ajax_aieo_save_cart', array( $this, 'ajax_save_cart' ) );
		add_action( 'wp_ajax_nopriv_aieo_save_cart', array( $this, 'ajax_save_cart' ) );
		add_action( 'wp_ajax_aieo_resume_cart', array( $this, 'ajax_resume_cart' ) );
		add_action( 'wp_ajax_nopriv_aieo_resume_cart', array( $this, 'ajax_resume_cart' ) );
		add_action( 'template_redirect', array( $this, 'maybe_resume_cart' ), 5 );
		add_shortcode( 'aieo_save_cart', array( $this, 'shortcode_button' ) );

		
		add_action( 'woocommerce_after_cart_table', array( $this, 'render_button_classic' ) );
		add_action( 'woocommerce_widget_shopping_cart_after_buttons', array( $this, 'render_button_minicart' ) );
		
		add_action( 'woocommerce_review_order_before_payment', array( $this, 'render_button_checkout' ) );
	}

	
	
	

	
	public function enabled() {
		return '0' !== (string) get_option( self::OPT_ENABLED, '1' );
	}

	
	public function save_label() {
		$label = (string) get_option( self::OPT_LABEL, '' );
		if ( '' === $label ) {
			$label = __( 'Save / share my cart', 'ai-eshop-optimizer' );
		}
		return $label;
	}

	
	public function show_on_checkout() {
		return '1' === (string) get_option( 'aieo_carts_show_on_checkout', '0' );
	}

	
	public function show_in_sidecart() {
		if ( ! $this->enabled() ) {
			return false;
		}
		if ( class_exists( 'AIEO_DMM_Settings' ) ) {
			return (bool) AIEO_DMM_Settings::get( 'side_cart_show_save_btn', false );
		}
		return false;
	}

	
	private function expiry_datetime() {
		$days = (int) get_option( self::OPT_TTL_DAYS, 60 );
		if ( $days <= 0 ) {
			return null;
		}
		return gmdate( 'Y-m-d H:i:s', time() + ( $days * DAY_IN_SECONDS ) );
	}

	
	private function session_id() {
		if ( function_exists( 'WC' ) && WC()->session && method_exists( WC()->session, 'get_customer_id' ) ) {
			return (string) WC()->session->get_customer_id();
		}
		return '';
	}

	
	public function share_url( $token ) {
		
		
		
		$base = function_exists( 'wc_get_cart_url' ) ? wc_get_cart_url() : home_url( '/' );
		return add_query_arg( self::QUERY_VAR, rawurlencode( $token ), $base );
	}

	
	
	

	
	public function maybe_enqueue() {
		if ( ! $this->enabled() ) {
			return;
		}
		$load = ( function_exists( 'is_cart' ) && is_cart() ) || ( function_exists( 'is_checkout' ) && is_checkout() );
		
		
		if ( $this->show_in_sidecart() ) {
			$load = true;
		}
		
		$load = apply_filters( 'aieo_carts_load_assets', $load );
		if ( $load ) {
			$this->do_enqueue();
		}
	}

	
	private function do_enqueue() {
		if ( $this->enqueued ) {
			return;
		}
		$this->enqueued = true;

		$css_path = AIEO_DIR . 'assets/css/aieo-carts.css';
		$js_path  = AIEO_DIR . 'assets/js/aieo-carts.js';
		$css_ver  = file_exists( $css_path ) ? (string) filemtime( $css_path ) : AIEO_VERSION;
		$js_ver   = file_exists( $js_path ) ? (string) filemtime( $js_path ) : AIEO_VERSION;

		wp_enqueue_style(
			'aieo-carts',
			AIEO_URI . 'assets/css/aieo-carts.css',
			array(),
			$css_ver
		);
		wp_enqueue_script(
			'aieo-carts',
			AIEO_URI . 'assets/js/aieo-carts.js',
			array(),
			$js_ver,
			true
		);
		wp_localize_script(
			'aieo-carts',
			'aieoCarts',
			array(
				'ajaxUrl' => admin_url( 'admin-ajax.php' ),
				'nonce'   => wp_create_nonce( self::NONCE ),
				'flags'   => array(
					
					
					'checkout' => $this->show_on_checkout() && function_exists( 'is_checkout' ) && is_checkout(),
				),
				'i18n'    => array(
					'save'    => $this->save_label(),
					'saving'  => __( 'Saving…', 'ai-eshop-optimizer' ),
					'error'   => __( 'Something went wrong. Please try again.', 'ai-eshop-optimizer' ),
					'copy'    => __( 'Copy', 'ai-eshop-optimizer' ),
					'copied'  => __( 'Copied!', 'ai-eshop-optimizer' ),
					'share'   => __( 'Share', 'ai-eshop-optimizer' ),
					'loading' => __( 'Loading the shared cart…', 'ai-eshop-optimizer' ),
				),
			)
		);
	}

	
	
	

	
	public function button_html( $source ) {
		ob_start();
		?>
		<div class="aieo-cart-ops">
			<button type="button" class="aieo-save-cart wp-element-button button" data-source="<?php echo esc_attr( $source ); ?>">
				<?php echo esc_html( $this->save_label() ); ?>
			</button>
			<div class="aieo-cart-share" hidden>
				<p class="aieo-cart-share-msg"></p>
				<div class="aieo-cart-share-row">
					<input type="text" class="aieo-cart-share-url" readonly />
					<button type="button" class="aieo-cart-share-copy button"><?php esc_html_e( 'Copy', 'ai-eshop-optimizer' ); ?></button>
				</div>
			</div>
		</div>
		<?php
		return (string) ob_get_clean();
	}

	
	public function render_button_classic() {
		if ( ! $this->enabled() ) {
			return;
		}
		echo $this->button_html( 'cart_button' ); 
	}

	
	public function render_button_checkout() {
		if ( ! $this->enabled() || ! $this->show_on_checkout() ) {
			return;
		}
		echo $this->button_html( 'checkout' ); 
	}

	
	public function side_cart_button_html() {
		if ( ! $this->enabled() ) {
			return '';
		}
		$label = '';
		if ( class_exists( 'AIEO_DMM_Settings' ) ) {
			$label = (string) AIEO_DMM_Settings::get( 'side_cart_btn_save', '' );
		}
		if ( '' === $label ) {
			$label = __( 'Save cart', 'ai-eshop-optimizer' );
		}
		return '<button type="button" class="aieo-save-cart aieo-sc-btn aieo-sc-btn-save" data-source="side_cart" data-quick="1">'
			. esc_html( $label ) . '</button>';
	}

	
	public function render_button_minicart() {
		if ( ! $this->enabled() ) {
			return;
		}
		echo $this->button_html( 'mini_cart' ); 
	}

	
	public function shortcode_button( $atts ) {
		if ( ! $this->enabled() ) {
			return '';
		}
		$this->do_enqueue();
		return $this->button_html( 'shortcode' );
	}

	
	
	

	
	public function ajax_save_cart() {
		check_ajax_referer( self::NONCE, 'nonce' );

		if ( ! $this->enabled() ) {
			wp_send_json_error( array( 'message' => __( 'Saving carts is disabled.', 'ai-eshop-optimizer' ) ) );
		}
		if ( ! function_exists( 'WC' ) || ! WC()->cart || WC()->cart->is_empty() ) {
			wp_send_json_error( array( 'message' => __( 'Your cart is empty.', 'ai-eshop-optimizer' ) ) );
		}

		if ( class_exists( 'AIEO_Carts' ) ) {
			AIEO_Carts::maybe_install();
		}

		$snap = AIEO_Carts_Store::snapshot_live_cart();
		if ( ! $snap ) {
			wp_send_json_error( array( 'message' => __( 'Your cart is empty.', 'ai-eshop-optimizer' ) ) );
		}

		$uid    = get_current_user_id();
		$email  = '';
		if ( $uid ) {
			$user  = wp_get_current_user();
			$email = $user ? $user->user_email : '';
		}
		$name   = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
		$source = isset( $_POST['source'] ) ? sanitize_key( wp_unslash( $_POST['source'] ) ) : 'cart_button';
		$token  = AIEO_Carts_Store::unique_token( 8 );

		$cart_id = AIEO_Carts_Store::insert_cart(
			array(
				'token'          => $token,
				'kind'           => 'saved',
				'source'         => $source,
				'user_id'        => $uid,
				'customer_email' => $email,
				'session_id'     => $this->session_id(),
				'name'           => $name,
				'items'          => $snap['items'],
				'coupons'        => $snap['coupons'],
				'currency'       => $snap['currency'],
				'item_count'     => $snap['item_count'],
				'subtotal'       => $snap['subtotal'],
				'total'          => $snap['total'],
				'status'         => 'active',
				'expires_at'     => $this->expiry_datetime(),
			),
			$snap['lines']
		);

		if ( ! $cart_id ) {
			wp_send_json_error( array( 'message' => __( 'Could not save the cart. Please try again.', 'ai-eshop-optimizer' ) ) );
		}

		wp_send_json_success(
			array(
				'token'      => $token,
				'url'        => $this->share_url( $token ),
				'item_count' => (int) $snap['item_count'],
				'message'    => __( 'Cart saved! Use this link to reopen or share it.', 'ai-eshop-optimizer' ),
			)
		);
	}

	
	
	

	
	public function maybe_resume_cart() {
		if ( empty( $_GET[ self::QUERY_VAR ] ) ) { 
			return;
		}
		if ( ! function_exists( 'WC' ) || ! function_exists( 'wc_get_cart_url' ) ) {
			return;
		}

		$token = sanitize_text_field( wp_unslash( $_GET[ self::QUERY_VAR ] ) ); 
		if ( ! preg_match( '/^[a-z0-9]{4,20}$/', $token ) ) {
			return;
		}

		if ( function_exists( 'is_cart' ) && is_cart() ) {
			return; 
		}
		wp_safe_redirect( add_query_arg( self::QUERY_VAR, rawurlencode( $token ), wc_get_cart_url() ) );
		exit;
	}

	
	public function ajax_resume_cart() {
		check_ajax_referer( self::NONCE, 'nonce' );

		if ( ! function_exists( 'WC' ) ) {
			wp_send_json_error( array( 'message' => __( 'Cart unavailable.', 'ai-eshop-optimizer' ) ) );
		}
		$token = isset( $_POST['token'] ) ? sanitize_text_field( wp_unslash( $_POST['token'] ) ) : '';
		if ( ! preg_match( '/^[a-z0-9]{4,20}$/', $token ) ) {
			wp_send_json_error( array( 'message' => __( 'Invalid link.', 'ai-eshop-optimizer' ) ) );
		}

		if ( class_exists( 'AIEO_Carts' ) ) {
			AIEO_Carts::maybe_install();
		}
		if ( ! WC()->cart && function_exists( 'wc_load_cart' ) ) {
			wc_load_cart();
		}
		if ( ! WC()->cart ) {
			wp_send_json_error( array( 'message' => __( 'Cart unavailable.', 'ai-eshop-optimizer' ) ) );
		}

		$row = AIEO_Carts_Store::get_by_token( $token );
		if ( ! $row ) {
			wp_send_json_error( array( 'message' => __( 'That saved-cart link is invalid or has expired.', 'ai-eshop-optimizer' ) ) );
		}

		AIEO_Carts_Store::bump_counter( $row->id, 'view_count' );
		$added = AIEO_Carts_Store::restore_into_cart( $row );
		AIEO_Carts_Store::bump_counter( $row->id, 'resume_count' );

		
		
		WC()->cart->set_session();
		if ( WC()->session ) {
			if ( method_exists( WC()->session, 'set_customer_session_cookie' ) ) {
				WC()->session->set_customer_session_cookie( true );
			}
			if ( method_exists( WC()->session, 'save_data' ) ) {
				WC()->session->save_data();
			}
		}

		$cookie = $this->build_session_cookie();
		if ( $added < 1 || ! $cookie ) {
			wp_send_json_error(
				array(
					'cart_url' => wc_get_cart_url(),
					'message'  => __( 'None of the saved items are available any more.', 'ai-eshop-optimizer' ),
				)
			);
		}

		wp_send_json_success(
			array(
				'added'    => $added,
				'cookie'   => $cookie,
				'cart_url' => wc_get_cart_url(),
			)
		);
	}

	
	private function build_session_cookie() {
		if ( ! WC()->session || ! method_exists( WC()->session, 'get_customer_id' ) ) {
			return null;
		}
		$cid = (string) WC()->session->get_customer_id();
		if ( '' === $cid ) {
			return null;
		}

		$exp  = 0;
		$expg = 0;
		try {
			$ref = new ReflectionObject( WC()->session );
			if ( $ref->hasProperty( '_session_expiration' ) ) {
				$p = $ref->getProperty( '_session_expiration' );
				$p->setAccessible( true );
				$exp = (int) $p->getValue( WC()->session );
			}
			if ( $ref->hasProperty( '_session_expiring' ) ) {
				$p = $ref->getProperty( '_session_expiring' );
				$p->setAccessible( true );
				$expg = (int) $p->getValue( WC()->session );
			}
		} catch ( \Exception $e ) {
			$exp  = 0;
			$expg = 0;
		}
		if ( $exp <= time() ) {
			$exp = time() + (int) apply_filters( 'wc_session_expiration', 60 * 60 * 48 );
		}
		if ( $expg <= time() ) {
			$expg = time() + (int) apply_filters( 'wc_session_expiring', 60 * 60 * 47 );
		}

		
		
		
		
		$message = $cid . '|' . $exp;
		if ( function_exists( 'wp_fast_hash' ) ) {
			$hash = wp_fast_hash( $message );
		} else {
			$hash = hash_hmac( 'md5', $message, wp_hash( $message ) );
		}
		$value = $cid . '|' . $exp . '|' . $expg . '|' . $hash;
		$name  = (string) apply_filters( 'woocommerce_cookie', 'wp_woocommerce_session_' . COOKIEHASH );

		return array(
			'name'   => $name,
			'value'  => $value,
			'maxAge' => max( 0, $exp - time() ),
		);
	}
}
