<?php
/**
 * Abandoned Cart Frontend Trait.
 *
 * @package automation-web-platform
 */

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


/**
 * Trait WAWP_Abandoned_Cart_Frontend.
 * Handles all frontend-facing logic and hooks for Abandoned Carts.
 */
trait WAWP_Abandoned_Cart_Frontend {

	/**
	 * Initialize the abandoned cart session.
	 */
	public function init_session() {
		if ( is_admin() && ! wp_doing_ajax() ) {
			return;
		}

		if ( $this->is_bot() ) {
			return;
		}

		if ( empty( $_SESSION['wac_session'] ) ) {
			if ( ! empty( $_COOKIE['wac_session'] ) ) {
				$_SESSION['wac_session'] = sanitize_text_field( wp_unslash( $_COOKIE['wac_session'] ) );
			} else {
				$session_id              = wp_generate_uuid4();
				$_SESSION['wac_session'] = $session_id;
				setcookie( 'wac_session', $session_id, time() + ( 365 * 24 * 60 * 60 ), '/' );
			}
		}

		$session_id = sanitize_text_field( wp_unslash( $_SESSION['wac_session'] ) );

		// Initial record if not exists.
		$this->insert_or_update( $session_id, get_current_user_id() );
	}

	/**
	 * Capture IP and User Agent on the first visit.
	 */
	public function capture_ip_user_agent() {
		if ( empty( $_SESSION['wac_session'] ) || is_admin() ) {
			return;
		}

		$session_id                    = sanitize_text_field( wp_unslash( $_SESSION['wac_session'] ) );
		$ip                            = $this->get_user_ip();
		$ua                            = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '';
		list( $browser, $os, $device ) = $this->parse_user_agent( $ua );
		$country                       = $this->get_ip_country_code();
		$location                      = $ip . ( $country ? ' | ' . $country : '' );

		$this->insert_or_update( $session_id, get_current_user_id(), '', $location, '', 0.0, '', $browser, $os, $device );
	}

	/**
	 * Hooked to woocommerce_cart_updated.
	 */
	public function cart_updated() {
		if ( empty( $_SESSION['wac_session'] ) ) {
			return;
		}

		$session_id = sanitize_text_field( wp_unslash( $_SESSION['wac_session'] ) );
		$cart       = WC()->cart;
		if ( ! $cart ) {
			return;
		}

		$items = array();
		foreach ( $cart->get_cart() as $cart_item ) {
			$product = $cart_item['data'];
			$items[] = array(
				'product_id'   => $cart_item['product_id'],
				'variation_id' => $cart_item['variation_id'],
				'quantity'     => $cart_item['quantity'],
				'name'         => $product->get_name(),
				'price'        => $product->get_price(),
			);
		}

		$total  = $cart->get_total( 'raw' );
		$status = ! empty( $items ) ? 'shopping' : 'online';

		$this->insert_or_update( $session_id, get_current_user_id(), '', '', maybe_serialize( $items ), $total, $status );

		if ( ! empty( $items ) ) {
			global $wpdb;
			$table = $wpdb->prefix . 'wawp_abandoned_carts';
			$row   = WAWP()->db->get_results_cached( $wpdb->prepare( 'SELECT id FROM %i WHERE session_id = %s ORDER BY id DESC LIMIT 1', $table, $session_id ), "wawp_ac_row_{$session_id}", 'wawp_ac', 300 );
			if ( ! empty( $row ) ) {
				$this->notifications->schedule_notifications_for_cart( $row[0]['id'], 'abandoned_cart' );
			}
		}
	}

	/**
	 * Prefill checkout fields from saved session data.
	 *
	 * @param mixed  $value Value.
	 * @param string $input Input name.
	 * @return mixed
	 */
	public function prefill_checkout_fields( $value, $input ) {
		if ( ! empty( $value ) ) {
			return $value;
		}

		if ( empty( $_SESSION['wac_session'] ) ) {
			return $value;
		}

		if ( ! $this->get_wawp_setting( WAWP_Settings_Registry::AC_ENABLE_CHECKOUT_AUTOFILL, 1 ) ) {
			return $value;
		}

		$session_id = sanitize_text_field( wp_unslash( $_SESSION['wac_session'] ) );
		global $wpdb;
		$table = $wpdb->prefix . 'wawp_abandoned_carts';
		$row   = WAWP()->db->get_results_cached( $wpdb->prepare( 'SELECT contact_details FROM %i WHERE session_id = %s ORDER BY id DESC LIMIT 1', $table, $session_id ), "wawp_ac_contact_{$session_id}", 'wawp_ac', 300 );

		if ( ! empty( $row ) && ! empty( $row[0]['contact_details'] ) ) {
			$data = maybe_unserialize( $row[0]['contact_details'] );
			if ( is_array( $data ) && isset( $data[ $input ] ) ) {
				return $data[ $input ];
			}
		}

		return $value;
	}

	/**
	 * Handle order review update to capture billing fields.
	 *
	 * @param string $post_data Post data.
	 */
	public function checkout_update_order_review( $post_data ) {
		if ( empty( $_SESSION['wac_session'] ) ) {
			return;
		}

		$session_id = sanitize_text_field( wp_unslash( $_SESSION['wac_session'] ) );
		parse_str( $post_data, $data );
		$billing_data = $this->capture_billing_logic( $session_id, $data );

		if ( ! empty( $billing_data ) ) {
			$this->add_history_event( 'checkout_fields', 'User filling checkout fields' );
		}
	}

	/**
	 * Mark cart as purchased on thank you page.
	 *
	 * @param int $order_id Order ID.
	 */
	public function order_thankyou( $order_id ) {
		if ( empty( $_SESSION['wac_session'] ) ) {
			return;
		}

		$session_id = sanitize_text_field( wp_unslash( $_SESSION['wac_session'] ) );
		$order      = function_exists( 'wc_get_order' ) ? wc_get_order( $order_id ) : null;
		$contact    = '';

		if ( $order ) {
			$contact = maybe_serialize(
				array(
					'billing_first_name' => $order->get_billing_first_name(),
					'billing_last_name'  => $order->get_billing_last_name(),
					'billing_email'      => $order->get_billing_email(),
					'billing_phone'      => $order->get_billing_phone(),
					'billing_country'    => $order->get_billing_country(),
					'billing_city'       => $order->get_billing_city(),
					'billing_address_1'  => $order->get_billing_address_1(),
					'billing_address_2'  => $order->get_billing_address_2(),
					'billing_state'      => $order->get_billing_state(),
					'billing_postcode'   => $order->get_billing_postcode(),
				)
			);
		}

		$this->insert_or_update( $session_id, get_current_user_id(), $contact, '', '', 0.0, 'purchased', '', '', '', $order_id );
		$this->add_history_event( 'order_complete', 'Order #' . $order_id . ' completed' );

		// Cancel scheduled notifications.
		global $wpdb;
		$table = $wpdb->prefix . 'wawp_abandoned_carts';
		$row   = WAWP()->db->get_results_cached( $wpdb->prepare( 'SELECT id FROM %i WHERE session_id = %s ORDER BY id DESC LIMIT 1', $table, $session_id ), "wawp_ac_row_{$session_id}", 'wawp_ac', 300 );

		if ( ! empty( $row ) ) {
			$this->notifications->cancel_all_scheduled_notifications_for_cart( $row[0]['id'] );
		}
	}

	/**
	 * Enqueue frontend scripts.
	 */
	public function enqueue_scripts() {
		$enable_popup = $this->get_wawp_setting( WAWP_Settings_Registry::AC_ENABLE_POPUP, 1 );

		// Session Recovery Script.
		wp_add_inline_script(
			'jquery-core',
			"
			(function() {
				function getCookie(n) {
					var m = document.cookie.match(new RegExp('(^| )'+n+'=([^;]+)'));
					return m ? m[2] : null;
				}
				function setCookie(n, v, s) {
					var e = '';
					if (s) {
						var d = new Date();
						d.setTime(d.getTime() + (s * 1000));
						e = '; expires=' + d.toUTCString();
					}
					document.cookie = n + '=' + v + e + '; path=/';
				}
				var c = getCookie('wac_session'), s = localStorage.getItem('wac_session');
				if (c) {
					if (s !== c) localStorage.setItem('wac_session', c);
				} else if (s) {
					setCookie('wac_session', s, 31536000);
					jQuery.post('" . esc_url( admin_url( 'admin-ajax.php' ) ) . "', { action: 'wawp_reclaim_session', session_id: s });
				}
			})();
		"
		);

		wp_enqueue_script( 'wac-track', WAWP_PLUGIN_URL . 'assets/js/wac-track.js', array( 'jquery' ), WAWP_PLUGIN_VERSION, true );
		wp_localize_script(
			'wac-track',
			'wac_track_params',
			array(
				'rest_url' => esc_url_raw( rest_url( 'wawp/v1/cart' ) ),
			)
		);

		wp_enqueue_script( 'wac-custom', WAWP_PLUGIN_URL . 'assets/js/wac-custom.js', array( 'jquery' ), WAWP_PLUGIN_VERSION, true );
		wp_localize_script(
			'wac-custom',
			'wac_params',
			array(
				'rest_url' => esc_url_raw( rest_url( 'wawp/v1/cart' ) ),
			)
		);

		if ( ! $enable_popup ) {
			return;
		}

		wp_enqueue_script( 'wawp-popup-script', WAWP_PLUGIN_URL . 'assets/js/popup.js', array( 'jquery' ), WAWP_PLUGIN_VERSION, true );
		wp_enqueue_style( 'wawp-popup-style', WAWP_PLUGIN_URL . 'assets/css/popup.css', array(), WAWP_PLUGIN_VERSION );

		$billing_phone = '';
		if ( ! empty( $_SESSION['login_your_whatsapp'] ) ) {
			$billing_phone = sanitize_text_field( wp_unslash( $_SESSION['login_your_whatsapp'] ) );

		} elseif ( ! empty( $_COOKIE['New_phone'] ) ) {
			$billing_phone = sanitize_text_field( wp_unslash( $_COOKIE['New_phone'] ) );
		} elseif ( ! empty( $_COOKIE['visitor_phone'] ) ) {
			$billing_phone = sanitize_text_field( wp_unslash( $_COOKIE['visitor_phone'] ) );

		} elseif ( is_user_logged_in() ) {
			$billing_phone = (string) WAWP()->user_manager->get_user_phone( get_current_user_id() );
		}
		$billing_phone = $this->get_digits_only( $billing_phone );

		$autofill_frontend = $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_AUTOFILL_FRONTEND, 1 );
	}

	/**
	 * Add global variables to the central data hub.
	 *
	 * @param array $vars Global variables array.
	 * @return array
	 */
	public function add_frontend_global_vars( $vars ) {
		$enable_popup = $this->get_wawp_setting( WAWP_Settings_Registry::AC_ENABLE_POPUP, 1 );

		if ( ! $enable_popup ) {
			return $vars;
		}

		$billing_phone = '';
		if ( ! empty( $_SESSION['login_your_whatsapp'] ) ) {
			$billing_phone = sanitize_text_field( wp_unslash( $_SESSION['login_your_whatsapp'] ) );
		} elseif ( ! empty( $_COOKIE['New_phone'] ) ) {
			$billing_phone = sanitize_text_field( wp_unslash( $_COOKIE['New_phone'] ) );
		} elseif ( ! empty( $_COOKIE['visitor_phone'] ) ) {
			$billing_phone = sanitize_text_field( wp_unslash( $_COOKIE['visitor_phone'] ) );
		} elseif ( is_user_logged_in() ) {
			$billing_phone = (string) WAWP()->user_manager->get_user_phone( get_current_user_id() );
		}
		$billing_phone = $this->get_digits_only( $billing_phone );

		$autofill_frontend = $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_AUTOFILL_FRONTEND, 1 );

		$vars['pnpPopupData'] = array(
			'rest_url'         => esc_url_raw( rest_url( 'wawp/v1/cart' ) ),
			'successIconUrl'   => WAWP_PLUGIN_URL . 'assets/img/success.gif',
			'successTitle'     => esc_html__( 'Excellent!', 'automation-web-platform' ),
			'successMessage'   => esc_html__( 'You can now browse our website better.', 'automation-web-platform' ),
			'billing_phone'    => $billing_phone,
			'autofillFrontend' => $autofill_frontend,
			'invalidPhoneMsg'  => esc_html__( 'Please add a valid number that matches the selected country code.', 'automation-web-platform' ),
			'nonce'            => wp_create_nonce( 'wawp_abandoned_cart_nonce' ),
		);

		$vars['wawpPopupSettings'] = array(
			'enablePopup'         => true,
			'popupTitle'          => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_TITLE, esc_html__( 'Add your WhatsApp Number', 'automation-web-platform' ) ),
			'popupDescription'    => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_DESCRIPTION, esc_html__( 'To get a better experience with our website.', 'automation-web-platform' ) ),
			'popupDisplay'        => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_DISPLAY, 'both' ),
			'popupWhere'          => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WHERE, 'all' ),
			'popupExcludePages'   => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_EXCLUDE_PAGES, array() ),
			'triggerCart'         => (int) $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_TRIGGER_CART, 1 ) === 1,
			'triggerExit'         => (int) $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_TRIGGER_EXIT, 1 ) === 1,
			'closeHideDuration'   => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_CLOSE_HIDE_DURATION, 300 ),
			'popupInitialDelay'   => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_INITIAL_DELAY, 0 ),
			'autofillFrontend'    => $autofill_frontend,
			'popupFrequency'      => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_FREQUENCY, 'once' ),
			'popupFrequencyLimit' => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_FREQUENCY_LIMIT, 1 ),
			'popupDevices'        => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_DEVICES, 'all' ),
			'minCartValue'        => (float) $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_MIN_CART_VALUE, 0 ),
			'cartTotal'           => ( function_exists( 'WC' ) && WC()->cart ) ? (float) WC()->cart->get_cart_contents_total() : 0,

			// Styling.
			'btnColor'            => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_BTN_COLOR, '#004449' ),
			'btnTextColor'        => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_BTN_TEXT_COLOR, '#ffffff' ),
			'btnHoverColor'       => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_BTN_HOVER_COLOR, '#003337' ),
			'cardColor'           => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_CARD_COLOR, '#ffffff' ),
			'cardHoverColor'      => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_CARD_HOVER_COLOR, '#fcfcfc' ),
			'titleColor'          => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_TITLE_COLOR, '#333333' ),
			'titleHoverColor'     => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_TITLE_HOVER_COLOR, '#111111' ),
			'descColor'           => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_DESC_COLOR, '#666666' ),
			'descHoverColor'      => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_DESC_HOVER_COLOR, '#444444' ),
			'imageUrl'            => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_IMAGE_URL, '' ),
			'imageType'           => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_IMAGE_TYPE, 'inline' ),
			'imageAlignment'      => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_IMAGE_ALIGNMENT, 'center' ),
			'customCss'           => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_CUSTOM_CSS, '' ),
			'saveBtnText'         => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_SAVE_BTN, 'Save' ),
			'successTitle'        => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_SUCCESS_TITLE, 'Excellent!' ),
			'successDesc'         => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_SUCCESS_DESC, 'You can now browse our website better.' ),
			'continueBtnText'     => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_CONTINUE_BTN, 'Continue browsing' ),
			'verificationMethod'  => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_VERIFICATION_METHOD, 'none' ),
			'firebaseConfig'      => WAWP_Connector()->is_firebase_active() ? WAWP_Connector()->get_firebase_config() : null,
			'firebaseActive'      => WAWP_Connector()->is_firebase_active(),
		);

		return $vars;
	}

	/**
	 * AJAX Reclaim Session.
	 */
	public function reclaim_session() {
		check_ajax_referer( 'wawp_abandoned_cart_nonce', 'nonce' );
		if ( ! filter_has_var( INPUT_POST, 'session_id' ) ) {
			wp_die();
		}

		$session_id = sanitize_text_field( filter_input( INPUT_POST, 'session_id', FILTER_SANITIZE_SPECIAL_CHARS ) );

		global $wpdb;
		$table  = $wpdb->prefix . 'wawp_abandoned_carts';
		$exists = (int) WAWP()->db->get_results_cached( $wpdb->prepare( 'SELECT id FROM %i WHERE session_id = %s LIMIT 1', $table, $session_id ), "wawp_ac_exists_{$session_id}", 'wawp_ac', 3600 )[0]['id'] ?? 0;

		if ( $exists ) {
			$_SESSION['wac_session'] = $session_id;
			$this->init_session();
		}
		$this->send_success();
	}

	/**
	 * Restore abandoned cart via URL.
	 */
	public function restore_abandoned_cart() {
		$restore_cart = filter_input( INPUT_GET, 'wawp_restore_cart', FILTER_SANITIZE_SPECIAL_CHARS );
		$wac_id       = filter_input( INPUT_GET, 'wac_id', FILTER_SANITIZE_NUMBER_INT );

		if ( ! $restore_cart || ! $wac_id ) {
			return;
		}

		if ( ! $this->get_wawp_setting( WAWP_Settings_Registry::AC_ENABLE_CART_RESTORATION, 1 ) ) {
			return;
		}

		$cart_id = absint( $wac_id );

		global $wpdb;
		$table    = $wpdb->prefix . 'wawp_abandoned_carts';
		$cart_row = WAWP()->db->get_results_cached( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', $table, $cart_id ), "wawp_ac_restore_{$cart_id}", 'wawp_ac', 300 );
		$cart_row = ! empty( $cart_row ) ? (object) $cart_row[0] : null;

		if ( ! $cart_row || empty( $cart_row->cart_contents ) ) {
			return;
		}

		$contents = maybe_unserialize( $cart_row->cart_contents );
		if ( ! is_array( $contents ) ) {
			return;
		}

		WC()->cart->empty_cart();
		foreach ( $contents as $item ) {
			WC()->cart->add_to_cart( $item['product_id'], $item['quantity'], $item['variation_id'] );
		}

		// Auto-apply coupon via recovery link.
		$notif_settings  = $this->get_wawp_setting( WAWP_Settings_Registry::ABANDONED_CART_NOTIFICATIONS_SETTINGS );
		$coupon_settings = isset( $notif_settings['coupon_settings'] ) ? $notif_settings['coupon_settings'] : array();
		if ( ! empty( $coupon_settings['enable'] ) && ! empty( $coupon_settings['auto_apply'] ) ) {
			if ( class_exists( 'WAWP_Abandoned_Cart_Notifications' ) ) {
				$coupon_code = WAWP_Abandoned_Cart_Notifications::get_instance()->generate_coupon_code( $cart_id, $coupon_settings );
				if ( $coupon_code ) {
					WC()->cart->apply_coupon( $coupon_code );
				}
			}
		}

		$_SESSION['wac_session'] = $cart_row->session_id;
		setcookie( 'wac_session', $cart_row->session_id, time() + ( 365 * 24 * 60 * 60 ), '/' );
		$this->add_history_event( 'cart_restored', 'Cart restored from link' );

		wp_safe_redirect( wc_get_checkout_url() );
		exit;
	}

	/**
	 * AJAX Update Status.
	 */
	public function update_status() {
		check_ajax_referer( 'wawp_abandoned_cart_nonce', 'nonce' );
		if ( ! isset( $_POST['status'] ) ) {
			wp_die();
		}

		$session_id = $this->get_cart_session_id();
		if ( ! $session_id ) {
			wp_die();
		}

		$status = sanitize_text_field( filter_input( INPUT_POST, 'status', FILTER_SANITIZE_SPECIAL_CHARS ) );
		$this->update_cart_status_logic( $session_id, $status );
		$this->send_success();
	}

	/**
	 * AJAX Track Page View.
	 */
	public function track_page() {
		check_ajax_referer( 'wawp_abandoned_cart_nonce', 'nonce' );
		if ( ! isset( $_POST['url'] ) ) {
			wp_die();
		}

		$session_id = $this->get_cart_session_id();
		if ( ! $session_id ) {
			wp_die();
		}

		$url   = esc_url_raw( (string) filter_input( INPUT_POST, 'url', FILTER_SANITIZE_URL ) );
		$title = sanitize_text_field( (string) filter_input( INPUT_POST, 'title', FILTER_SANITIZE_SPECIAL_CHARS ) );

		$this->add_history_event(
			'page',
			array(
				'url'   => $url,
				'title' => $title,
			)
		);
		$this->send_success();
	}

	/**
	 * AJAX Capture Billing Fields.
	 */
	public function capture_billing_fields() {
		check_ajax_referer( 'wawp_abandoned_cart_nonce', 'nonce' );
		$session_id = $this->get_cart_session_id();
		if ( ! $session_id ) {
			wp_die();
		}

		$data = filter_input_array( INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS );

		$this->capture_billing_logic( $session_id, $data );
		$this->send_success();
	}

	/**
	 * Render the phone capture popup.
	 */
	public function add_popup() {
		if ( is_admin() || wp_doing_ajax() ) {
			return;
		}

		$enable_popup = $this->get_wawp_setting( WAWP_Settings_Registry::AC_ENABLE_POPUP, 1 );
		if ( ! $enable_popup ) {
			return;
		}

		$view_path = WAWP_PLUGIN_DIR . 'includes/abandoned-cart/views/abandoned-cart-popup.php';
		if ( file_exists( $view_path ) ) {
			include $view_path;
		}
	}
}
