<?php
/**
 * WooCommerce session helpers.
 *
 * @package CartNinjaRecovery
 */

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

class CARTNINJA_Cart_Session {

	public function is_available() {
		if ( ! function_exists( 'WC' ) ) {
			return false;
		}

		$woocommerce = WC();

		if ( ! $woocommerce || ! is_object( $woocommerce ) ) {
			return false;
		}

		if ( ! isset( $woocommerce->session ) || ! is_object( $woocommerce->session ) ) {
			return false;
		}

		if ( ! isset( $woocommerce->cart ) || ! is_object( $woocommerce->cart ) ) {
			return false;
		}

		if ( ! method_exists( $woocommerce->session, 'get_customer_id' ) || ! method_exists( $woocommerce->cart, 'get_cart' ) ) {
			return false;
		}

		return true;
	}

	public function get_session_id() {
		if ( ! $this->is_available() ) {
			return '';
		}

		$session_id = WC()->session->get_customer_id();

		if ( empty( $session_id ) ) {
			$session_id = wp_generate_uuid4();
		}

		return sanitize_text_field( (string) $session_id );
	}

	public function get_cart_contents() {
		if ( ! $this->is_available() ) {
			return array();
		}

		$items = array();

		foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
			$product = isset( $cart_item['data'] ) ? $cart_item['data'] : false;

			$items[] = array(
				'cart_item_key' => sanitize_text_field( (string) $cart_item_key ),
				'product_id'    => isset( $cart_item['product_id'] ) ? absint( $cart_item['product_id'] ) : 0,
				'variation_id'  => isset( $cart_item['variation_id'] ) ? absint( $cart_item['variation_id'] ) : 0,
				'quantity'      => isset( $cart_item['quantity'] ) ? absint( $cart_item['quantity'] ) : 1,
				'variation'     => isset( $cart_item['variation'] ) ? array_map( 'sanitize_text_field', $cart_item['variation'] ) : array(),
				'product_name'  => $product ? sanitize_text_field( $product->get_name() ) : '',
				'line_total'    => isset( $cart_item['line_total'] ) ? (float) $cart_item['line_total'] : 0,
			);
		}

		return $items;
	}

	public function get_cart_total() {
		if ( ! $this->is_available() ) {
			return 0.0;
		}

		return (float) WC()->cart->get_total( 'edit' );
	}

	public function get_currency() {
		if ( function_exists( 'get_woocommerce_currency' ) ) {
			return sanitize_text_field( get_woocommerce_currency() );
		}

		return sanitize_text_field( get_option( 'woocommerce_currency', 'USD' ) );
	}
}
