<?php

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

/**
 * REST API Handler
 */
class DLift_Rest_API
{
  /**
   * Constructor
   */
  public function __construct()
  {
    add_action('rest_api_init', array($this, 'dlift_register_rest_meta'));
  }

  /**
   * Register REST meta fields
   */
  public function dlift_register_rest_meta()
  {
    register_rest_field('dlift_discount_rule', 'meta', array(
      'get_callback' => array($this, 'dlift_get_post_meta'),
      'update_callback' => null,
      'schema' => array(
        'description' => 'Rule meta data',
        'type' => 'object'
      )
    ));
  }

  /**
   * Get post meta for REST API
   */
  public function dlift_get_post_meta($post)
  {
    $meta = array();
    $meta_fields = array(
      'dlift_condition_type',
      'dlift_condition_value',
      'dlift_discount_type',
      'dlift_discount_value',
      'dlift_progress_message',
      'dlift_success_message',
      'dlift_progress_styles',
      'dlift_success_styles',
    );

    foreach ($meta_fields as $field) {
      $meta[$field] = get_post_meta($post['id'], $field, true);
    }

    return $meta;
  }
}
