<?php

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

class AIEO_Carts_Store {

	
	const TOKEN_CHARS = '23456789abcdefghjkmnpqrstuvwxyz';

	
	public static function carts_table() {
		global $wpdb;
		return $wpdb->prefix . 'aieo_carts';
	}

	
	public static function items_table() {
		global $wpdb;
		return $wpdb->prefix . 'aieo_cart_items';
	}

	
	public static function table_exists( $table ) {
		global $wpdb;
		return (bool) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) );
	}

	
	public static function unique_token( $len = 8 ) {
		global $wpdb;
		$table = self::carts_table();
		$max   = strlen( self::TOKEN_CHARS ) - 1;
		$token = '';

		for ( $try = 0; $try < 25; $try++ ) {
			$token = '';
			for ( $i = 0; $i < $len; $i++ ) {
				$token .= self::TOKEN_CHARS[ wp_rand( 0, $max ) ];
			}
			$exists = $wpdb->get_var(
				$wpdb->prepare( "SELECT id FROM `{$table}` WHERE token = %s", $token )
			);
			if ( ! $exists ) {
				return $token;
			}
		}

		
		return $token . wp_rand( 100, 999 );
	}

	
	public static function snapshot_live_cart() {
		if ( ! function_exists( 'WC' ) || ! WC()->cart || WC()->cart->is_empty() ) {
			return null;
		}

		$cart  = WC()->cart;
		$lines = array();

		foreach ( $cart->get_cart() as $ci ) {
			$pid     = isset( $ci['product_id'] ) ? (int) $ci['product_id'] : 0;
			$vid     = ! empty( $ci['variation_id'] ) ? (int) $ci['variation_id'] : 0;
			$product = isset( $ci['data'] ) && is_object( $ci['data'] ) ? $ci['data'] : null;
			if ( ! $product ) {
				$product = wc_get_product( $vid ? $vid : $pid );
			}
			$line_total = isset( $ci['line_total'] ) ? (float) $ci['line_total'] : 0;
			$line_tax   = isset( $ci['line_tax'] ) ? (float) $ci['line_tax'] : 0;

			$lines[] = array(
				'product_id'   => $pid,
				'variation_id' => $vid,
				'sku'          => $product ? (string) $product->get_sku() : '',
				'name'         => $product ? (string) $product->get_name() : '',
				'quantity'     => isset( $ci['quantity'] ) ? (int) $ci['quantity'] : 0,
				'line_total'   => $line_total + $line_tax,
			);
		}

		return array(
			'items'      => $cart->get_cart_for_session(),
			'coupons'    => $cart->get_applied_coupons(),
			'currency'   => get_woocommerce_currency(),
			'item_count' => (int) $cart->get_cart_contents_count(),
			'subtotal'   => (float) $cart->get_subtotal(),
			'total'      => (float) $cart->get_total( 'edit' ),
			'lines'      => $lines,
		);
	}

	
	public static function insert_cart( array $row, array $lines = array() ) {
		global $wpdb;

		if ( isset( $row['items'] ) && is_array( $row['items'] ) ) {
			$row['items'] = maybe_serialize( $row['items'] );
		}
		if ( isset( $row['coupons'] ) && is_array( $row['coupons'] ) ) {
			$row['coupons'] = maybe_serialize( $row['coupons'] );
		}

		$now = current_time( 'mysql', true );
		if ( empty( $row['created_at'] ) ) {
			$row['created_at'] = $now;
		}
		if ( empty( $row['updated_at'] ) ) {
			$row['updated_at'] = $now;
		}

		$ok = $wpdb->insert( self::carts_table(), $row );
		if ( false === $ok ) {
			return 0;
		}

		$cart_id = (int) $wpdb->insert_id;
		if ( $cart_id && $lines ) {
			self::replace_items( $cart_id, $lines );
		}
		return $cart_id;
	}

	
	public static function replace_items( $cart_id, array $lines ) {
		global $wpdb;
		$table = self::items_table();

		$wpdb->delete( $table, array( 'cart_id' => (int) $cart_id ) );

		foreach ( $lines as $ln ) {
			$wpdb->insert(
				$table,
				array(
					'cart_id'      => (int) $cart_id,
					'product_id'   => isset( $ln['product_id'] ) ? (int) $ln['product_id'] : 0,
					'variation_id' => isset( $ln['variation_id'] ) ? (int) $ln['variation_id'] : 0,
					'sku'          => isset( $ln['sku'] ) ? (string) $ln['sku'] : '',
					'name'         => isset( $ln['name'] ) ? (string) $ln['name'] : '',
					'quantity'     => isset( $ln['quantity'] ) ? (int) $ln['quantity'] : 0,
					'line_total'   => isset( $ln['line_total'] ) ? (float) $ln['line_total'] : 0,
					'is_restocked' => ! empty( $ln['is_restocked'] ) ? 1 : 0,
				)
			);
		}
	}

	
	public static function get_by_token( $token ) {
		global $wpdb;
		$table = self::carts_table();
		return $wpdb->get_row(
			$wpdb->prepare( "SELECT * FROM `{$table}` WHERE token = %s", $token )
		);
	}

	
	public static function get( $id ) {
		global $wpdb;
		$table = self::carts_table();
		return $wpdb->get_row(
			$wpdb->prepare( "SELECT * FROM `{$table}` WHERE id = %d", (int) $id )
		);
	}

	
	public static function bump_counter( $id, $column ) {
		global $wpdb;
		if ( ! in_array( $column, array( 'view_count', 'resume_count' ), true ) ) {
			return;
		}
		$table = self::carts_table();
		$wpdb->query(
			$wpdb->prepare(
				"UPDATE `{$table}` SET `{$column}` = `{$column}` + 1, updated_at = %s WHERE id = %d",
				current_time( 'mysql', true ),
				(int) $id
			)
		);
	}

	
	public static function restore_into_cart( $cart_row ) {
		if ( ! function_exists( 'WC' ) || ! WC()->cart || ! $cart_row ) {
			return 0;
		}

		$items = maybe_unserialize( $cart_row->items );
		if ( empty( $items ) || ! is_array( $items ) ) {
			return 0;
		}

		WC()->cart->empty_cart();
		$added = 0;

		foreach ( $items as $ci ) {
			$pid = isset( $ci['product_id'] ) ? (int) $ci['product_id'] : 0;
			$vid = ! empty( $ci['variation_id'] ) ? (int) $ci['variation_id'] : 0;
			$qty = isset( $ci['quantity'] ) ? (int) $ci['quantity'] : 1;
			if ( ! $pid ) {
				continue;
			}

			$variation = ( $vid && isset( $ci['variation'] ) && is_array( $ci['variation'] ) )
				? $ci['variation']
				: array();

			$key = WC()->cart->add_to_cart( $pid, $qty, $vid, $variation );
			if ( $key ) {
				$added++;
			}
		}

		$coupons = maybe_unserialize( $cart_row->coupons );
		if ( ! empty( $coupons ) && is_array( $coupons ) ) {
			foreach ( $coupons as $code ) {
				if ( $code && ! WC()->cart->has_discount( $code ) ) {
					WC()->cart->apply_coupon( $code );
				}
			}
		}

		return $added;
	}
}
