<?php

/**
 * Fired during plugin activation
 *
 * @link       https://flothemes.com/
 * @since      1.0.0
 *
 * @package    Flo_Flex_Builder
 * @subpackage Flo_Flex_Builder/includes
 */

/**
 * Fired during plugin activation.
 *
 * This class defines all code necessary to run during the plugin's activation.
 *
 * @since      1.0.0
 * @package    Flo_Flex_Builder
 * @subpackage Flo_Flex_Builder/includes
 * @author     Flothemes <alexb@flothemes.com>
 */
class Flo_Flex_Builder_Gutenberg {

  /**
   * The unique identifier of this plugin.
   *
   * @since    1.0.0
   * @access   protected
   * @var      string    $plugin_name    The string used to uniquely identify this plugin.
   */
  protected $plugin_name;


  public function __construct() {
    $this->plugin_name = 'flo-flex-builder';

    $this->define_admin_hooks();
    $this->flex_gutenberg_actions();
  }

  public function flex_gutenberg_actions() {
    add_action('init', array($this, 'register_gutenberg_block'));
    add_action('enqueue_block_editor_assets', array($this, 'enqueue_gutenberg_scripts'));
  }

  private function define_admin_hooks() {
    add_action('wp_ajax_flexSaveGutenberg', array(&$this, 'flexSaveGutenberg'));
  }

  public function flexSaveGutenberg() {

    Flo_Flex_Builder_Admin::check_capabilities('publish_pages');

    $postData = isset($_POST['editedPostContent']) && isset($_POST['postId']);
    $isUserLoggedIn = is_user_logged_in();
    if ($isUserLoggedIn) {
      if (!$postData) {
        header('HTTP/1.1 204 No Content');
      } else {
        $postId = $_POST['postId'];
        $editedPostContent = $_POST['editedPostContent'];
        $post = get_post($postId);
        $post->post_content = html_entity_decode(stripslashes($editedPostContent));

        $res = wp_update_post($post);

        if ($res) {
          header('HTTP/1.1 201 Updated');

          echo json_encode([
            'previewLink' => get_post_permalink($res),
          ]);
        } else {
          header('HTTP/1.1 409 Can\'t create');
        }
      }
    } else {
      header('HTTP/1.1 403 Not authorized');
    }

    die();
  }

  public function register_gutenberg_block() {
    register_block_type(
      'flo/flo-flex-builder',
      array(
        'render_callback' => array($this, 'flo_render_flex_block'),
        'supports' => [
          'anchor' => true
        ]
      )
    );
  }
  public function flo_render_flex_block($attributes) {
    return flo_get_render_data_flex($attributes);
  }


  public function enqueue_gutenberg_scripts() {

    wp_enqueue_script(
      $this->plugin_name . '_gutenberg',
      plugins_url('dist/flex-gutenberg.min.js', dirname(__FILE__)),
      ['wp-blocks', 'wp-components', 'wp-editor', $this->plugin_name],
      Flo_Flex_Builder_Version
    );
  }
}
