<?php

namespace Reach\App\Fields;

/**
 * Class FieldParser
 *
 * @package Reach\App\Fields
 */
class FieldParser {

    /**
     * Loop through an array of field data and return an object of values for use in group field modules
     *
     * @param array $fields
     * @param array $meta
     * @param string $key
     *
     * @return mixed
     */
    public function processFieldData( $fields = [], $meta, $key ) {
        $data = [];

        // loop through fields and check for meta values to apply to the data array
        foreach ( $fields as $field ) {
            if ( ! isset( $field['name'] ) ) {
                continue;
            }

            // remove the group key from the field name to set a global key for accessing the data within the object
            $field_name = explode( "{$key}_", $field['name'] );
            if ( ! isset( $field_name[1] ) ) {
                continue;
            }

            // set the value of the post meta to our data array with our global key
            $data[ $field_name[1] ] = isset( $meta[ $field['name'] ][0] ) ? maybe_unserialize( $meta[ $field['name'] ][0] ) : false;
        }

        // return the array as an object
        return (object) $data;
    }

    /**
     * Adds prefix to css classes
     *
     * @param string $prefix
     * @param string $classes
     *
     * @return string
     */

    public function prefixCssClasses( $prefix, $classes ) {
      $prefixed_classes = '';
      $classes          = explode(' ', $classes);

      foreach ($classes as $class) {
        if ($class !== '') {
          $prefixed_classes .= $prefix . '-' . $class . ' ';
        }
      }

      return $prefixed_classes;
    }

    /**
     * Custom db query for grabbing all post meta while excluding ACF field key rows
     *
     * @param $post_id
     *
     * @return bool|mixed
     */
    public static function getPostMeta( $post_id ) {
        global $wpdb;
        $cache_key = 'ad_post_meta_' . $post_id;
        $post_meta = wp_cache_get( $cache_key, 'meta' );

        if ( ! $post_meta ) {
            $post_meta_db = $wpdb->get_results(
                    "SELECT meta_key, meta_value FROM $wpdb->postmeta WHERE post_id=$post_id AND meta_value NOT LIKE 'field_%'"
            );
            $post_meta    = [];
            foreach ( (array) $post_meta_db as $o ) {
                $post_meta[ $o->meta_key ] = maybe_unserialize( $o->meta_value );
            }
            if ( ! wp_installing() || ! is_multisite() ) {
                wp_cache_add( $cache_key, $post_meta, 'meta' );
            }
        }
        return $post_meta;
    }

}
