<?php

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

if ( !class_exists( 'Reon' ) ) {
    return;
}

if ( !class_exists( 'Pricely_Admin_Data_List_View_Positions' ) ) {

    class Pricely_Admin_Data_List_View_Positions {

        private $prefix;

        public function __construct() {

            $this->prefix = 'view_positions:';
        }

        public function can_get_data( $source ) {

            return $this->starts_with( $this->prefix, $source );
        }

        public function get_data( $result, $in_data_args ) {

            $data_args = $this->process_args( $in_data_args );

            if ( !$data_args ) {

                return $result;
            }

            $pricely_views = Pricely_Views::get_instance();

            $source = $data_args[ 'source' ];

            $view_positions = $pricely_views->get_view_positions();

            if ( !isset( $view_positions[ $source ] ) ) {

                return $result;
            }

            foreach ( $view_positions[ $source ] as $key => $view_position ) {

                if ( !isset( $view_position[ 'show_in_admin' ] ) || !$view_position[ 'show_in_admin' ] ) {

                    continue;
                }

                $title = $key;

                if ( isset( $view_position[ 'title' ] ) ) {

                    $title = $view_position[ 'title' ];
                }

                $result[ $key ] = $title;
            }

            return $result;
        }

        private function process_args( $data_args ) {

            if ( !isset( $data_args[ 'source' ] ) ) {

                return false;
            }

            if ( !$this->starts_with( $this->prefix, $data_args[ 'source' ] ) ) {

                return false;
            }

            $db_source = explode( ':', $data_args[ 'source' ] );

            $source_count = count( $db_source );

            if ( $source_count < 2 ) {

                return false;
            }


            if ( $source_count == 2 ) {

                $data_args[ 'source' ] = $db_source[ 1 ];

                return $data_args;
            }

            $n_src = array();

            for ( $i = 1; $i < $source_count; $i++ ) {

                $n_src[] = $db_source[ $i ];
            }

            $data_args[ 'source' ] = implode( ':', $n_src );

            return $data_args;
        }

        private function starts_with( $needle, $haystack ) {

            return str_starts_with( $haystack, $needle );
        }

    }

}
