<?php
/**
 * Shared helpers for all data source classes.
 */

namespace RawTypeOE\Free;

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

trait Data_Source_Trait {

	private function filter_columns( $data, $columns ) {
		if ( empty( $columns ) ) {
			return $data;
		}
		$filtered = array();
		foreach ( $columns as $col ) {
			$filtered[ $col ] = isset( $data[ $col ] ) ? $data[ $col ] : '';
		}
		return $filtered;
	}

	private function format_date( $date ) {
		if ( ! is_object( $date ) ) {
			return '';
		}
		$settings    = get_option( 'rawtype_oe_settings', array() );
		$date_format = isset( $settings['date_format'] ) ? $settings['date_format'] : 'Y-m-d';
		return $date->date( $date_format . ' H:i:s' );
	}

	private function get_meta_value( $item, $meta_key ) {
		return $item->get_meta( $meta_key, true );
	}

	private function append_custom_meta_data( $data, $item, $columns ) {
		if ( empty( $columns ) ) {
			return $data;
		}
		foreach ( $columns as $column_key ) {
			$meta_key = Custom_Field_Scanner::parse_meta_key_from_column( $column_key );
			if ( '' === $meta_key ) {
				continue;
			}
			$value = $this->get_meta_value( $item, $meta_key );
			if ( is_array( $value ) || is_object( $value ) ) {
				$value = wp_json_encode( $value );
			}
			$data[ $column_key ] = null !== $value ? $value : '';
		}
		return $data;
	}
}
