<?php

if ( !defined( 'ABSPATH' ) ) {

    exit;
}

if ( !class_exists( 'Pricely_View_Data_Tables' ) ) {

    require_once 'tables-volumetric-price-range.php';
    require_once 'tables-volumetric-price.php';

    class Pricely_View_Data_Tables {
    
        private static $instance;
        private $volumetric_price_table_range;
        private $volumetric_price_table;

        public static function get_instance(): self {

            if ( !self::$instance ) {

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

            return self::$instance;
        }

        public function __construct() {

            $this->volumetric_price_table_range = new Pricely_View_Data_Tables_Volumetric_Price_Range();
            $this->volumetric_price_table = new Pricely_View_Data_Tables_Volumetric_Price();
        }
        
        public function get_volumetric_price_data_rows( $view_data ) {

            $price_options = $view_data[ 'price_options' ];

            if ( !$price_options ) {

                return false;
            }

            $product = $view_data[ 'product' ];
            $volumetric_data = $this->volumetric_price_table_range->get_data( $price_options, $product );
            
            if ( !$volumetric_data ) {

                return false;
            }

            $text_formats = $view_data[ 'text_formats' ];

            $data_rows = array();

            foreach ( $volumetric_data[ 'ranges' ] as $range_data ) {

                $data_row = array(
                    'title' => $this->volumetric_price_table->get_table_row_title( $range_data, $text_formats ),
                );

                if ( $view_data[ 'options' ][ 'prices' ] ) {

                    $data_row[ 'prices' ] = $this->volumetric_price_table->get_table_row_prices( $range_data, $product );
                }

                if ( $view_data[ 'options' ][ 'discounts' ] || $view_data[ 'options' ][ 'discount_pers' ] ) {

                    $data_row[ 'discounts' ] = $this->volumetric_price_table->get_table_row_discounts( $range_data, $product );
                }

                $data_rows[] = $data_row;
            }

            if ( !count( $data_rows ) ) {

                return false;
            }

            return $data_rows;
        }
    }

}
