<?php

if ( !defined( 'ABSPATH' ) ) {

    exit;
}

if ( !class_exists( 'Pricely_Pipeline_Order' ) ) {

    require_once 'pipeline-order-coupons.php';
    require_once 'pipeline-order-usage-counts.php';

    class Pricely_Pipeline_Order {

        private static $instance;
        private $order_coupons;
        private $usage_counts;
        private $cart_data;
        private $order_store_key;

        public static function get_instance(): self {

            if ( !self::$instance ) {

                self::$instance = new self();
            }

            return self::$instance;
        }

        public function __construct() {

            $this->cart_data = false;
            $this->order_store_key = 'pricely';

            $this->order_coupons = new Pricely_Pipeline_Order_Coupons();
            $this->usage_counts = new Pricely_Pipeline_Order_Usage_Counts();

            add_action( 'woocommerce_checkout_create_order', array( $this, 'create_order' ), 9999, 2 );
            add_action( 'woocommerce_checkout_order_created', array( $this, 'order_created' ), 9999, 1 );
        }

        public function process_cart_data() {

            $coupons_data = $this->get_coupons_data();
            $usage_ids = $this->get_usage_ids( $coupons_data );


            $data = array();

            if ( $usage_ids ) {

                $data[ 'usage_ids' ] = $usage_ids;
            }

            if ( $coupons_data ) {

                $data[ 'coupons' ] = $coupons_data;
            }


            if ( count( $data ) ) {

                $this->cart_data = $data;
            } else {

                $this->cart_data = false;
            }
        }

        public function create_order( $order, $data ) {

            if ( !$this->cart_data ) {

                return;
            }

            if ( !$order ) {

                return;
            }

            $order->update_meta_data( $this->order_store_key, $this->cart_data );
        }

        public function order_created( $order ) {

            if ( !$this->cart_data ) {

                return;
            }

            if ( !$order ) {

                return;
            }

            $this->save_usage_ids( $order->get_customer_id() );
        }

        private function save_usage_ids( $user_id ) {

            if ( !isset( $this->cart_data[ 'usage_ids' ] ) ) {

                return;
            }

            $usage_ids = $this->cart_data[ 'usage_ids' ];

            if ( !$usage_ids ) {

                return;
            }

            $this->usage_counts->save_data( $usage_ids, $user_id );
        }

        private function get_usage_ids( $coupons_data ) {

            return $this->usage_counts->get_cart_data( $coupons_data );
        }

        private function get_coupons_data() {

            return $this->order_coupons->get_cart_data();
        }

    }

    Pricely_Pipeline_Order::get_instance();
}
