<?php
namespace SabaiApps\Directories\Component\Field\Type;

trait SaveNotesTrait {

	protected function _saveNotes( array &$value, ?array $currentValues = null, $key = 'notes' ) {
		// Update and serialize notes
		if ( ! isset( $value[ $key ] ) ) {
			if ( ! empty( $currentValues[0][ $key ] ) ) {
				$value[ $key ] = $currentValues[0][ $key ];
			}
		} else {
			$notes = array();
			foreach ( array_keys( $value[ $key ] ) as $_key ) {
				if ( ! is_numeric( $_key ) ) {
					continue;
				}

				if ( $note = $this->_toValidNote( $value[ $key ][ $_key ], isset( $currentValues[0][ $key ][ $_key ] ) ? $currentValues[0][ $key ][ $_key ] : null ) ) {
					$notes[] = $note;
				}
			}
			$value[ $key ] = $notes;
		}
	}

	protected function _toValidNote( $note, ?array $current = null ) {
		if ( is_string( $note ) ) {
			if ( ! strlen( $note ) ) {
				return;
			}

			$note = array( 'msg' => $note );
		} elseif ( is_array( $note ) ) {
			if ( ! isset( $note['msg'] ) || ! strlen( $note['msg'] ) ) {
				return;
			}

			foreach ( array_keys( $note ) as $key ) {
				if ( ! in_array( $key, array( 'id', 'msg', 'lv', 'ts', 'by' ) ) ) {
					unset( $note[ $key ] );
				}
			}
		} else {
			return;
		}
		if ( isset( $current ) ) {
			$note += $current;
		}
		if ( ! isset( $note['ts'] ) ) {
			$note['ts'] = time();
		}
		return $note;
	}
}
