<?php

if ( !defined( 'ABSPATH' ) ) {

    exit;
}

if ( !class_exists( 'Pricely_Cart_Discounts_Data' ) ) {

    class Pricely_Cart_Discounts_Data {

        private $coupon_id;
        private $discount_ids;

        public function __construct() {

            $this->coupon_id = array();
            $this->discount_ids = array();
        }

        public function process_data( $discounts_data ) {

            if ( !is_array( $discounts_data ) || !count( $discounts_data ) ) {

                return false;
            }

            $result = array(
                'coupons' => $this->process_coupons( $discounts_data ),
                'discounts' => $this->process_discounts( $discounts_data ),
            );

            return $result;
        }

        private function process_coupons( $discounts_data ) {

            $coupons = array();

            foreach ( $discounts_data as $discount_data ) {

                $coupons = $this->process_coupon( $coupons, $discount_data );
            }

            return array_values( $coupons );
        }

        private function process_coupon( $coupons, $discount_data ) {

            $coupon_id = $discount_data[ 'coupon' ][ 'id' ];

            $coupons[ $coupon_id ] = $discount_data[ 'coupon' ];

            $discount_id = $discount_data[ 'id' ];

            return $this->add_coupon_discount_ids( $coupons, $coupon_id, $discount_id );
        }

        private function add_coupon_discount_ids( $coupons, $coupon_id, $discount_id ) {

            if ( !isset( $this->discount_ids[ $coupon_id ] ) ) {

                $this->discount_ids[ $coupon_id ] = array();
            }

            if ( !in_array( $discount_id, $this->discount_ids[ $coupon_id ] ) ) {

                $this->discount_ids[ $coupon_id ][] = $discount_id;
            }

            $coupons[ $coupon_id ][ 'discount_ids' ] = $this->discount_ids[ $coupon_id ];

            return $coupons;
        }

        private function process_discounts( $discounts_data ) {

            $discounts = array();

            foreach ( $discounts_data as $discount_id => $discount_data ) {

                $discounts = $this->process_discount( $discounts, $discount_data, $discount_id );
            }

            return $discounts;
        }

        private function process_discount( $discounts, $discount_data, $discount_id ) {

            $discount = array(
                'discount_id' => $discount_id,
                'inclusive_tax' => $discount_data[ 'inclusive_tax' ],
                'totals' => $discount_data[ 'totals' ],
                'total' => $discount_data[ 'total' ],
                'taxes' => $discount_data[ 'taxes' ],
                'total_tax' => $discount_data[ 'total_tax' ],
                'coupon_id' => $discount_data[ 'coupon' ][ 'id' ]
            );

            $discounts[] = $discount;

            return $discounts;
        }

    }

}
