<?php

/**
 * Management of the Lockee block
 */
class Lockee_Block extends Lockee_Singleton
{
  /**
   * Init the Lockee block functionnality
   */
  protected function init() {}

  /**
   * Register the block
   */
  public function lockee_block_init()
  {
    $myblock = dirname(dirname(__FILE__)) . '/build/lockee-block';
    register_block_type(
      $myblock,
      array(
        'render_callback' => [$this, 'render_callback'],
      )
    );
    wp_set_script_translations(
      'lockee-lock-block-editor-script',
      'lockee',
      plugin_dir_path(__DIR__) . 'languages/'
    );
  }

  /**
   * Block render callback
   * 
   */
  public function render_callback($attributes = [])
  {
    if (!is_array($attributes)) {
      return '<p>' . esc_html__("Lock not found. Please check the block settings.", "lockee") . '</p>';
    }

    $id = isset($attributes['lockId']) ? intval($attributes['lockId']) : 0;
    if ($id <= 0) {
      return '<p>' . esc_html__("Lock not found. Please check the block settings.", "lockee") . '</p>';
    }

    $lockee_type = get_post_meta($id, 'lockee_type', true);
    $lockee_code = get_post_meta($id, 'lockee_code', true);
    $lockee_options = get_post_meta($id, 'lockee_options', true);

    if (empty($lockee_type) || empty($lockee_code)) {
      return '<p>' . esc_html__("Lock not found. Please check the block settings.", "lockee") . '</p>';
    }

    $lock_html = Lockee_Utils::generateLock('open', $id, $lockee_type, '', $lockee_options);

    return $lock_html;
  }
}
