<?php
/*
 * Plugin Name: Wordpress Admin Table
 * Description: 관리자 페이지 테이블 예제 플러그인
 * Version:   1.0.0
 * Author:    HiSEON
 * Author URI:  https://hiseon.me/
 */

include_once "table.php";

class admin_table_plugin {
  protected static $_instance = null;
  public $_tablelist;

  public static function instance() {
    if (is_null(self::$_instance)) {
      self::$_instance = new self();
    }

    return self::$_instance;
  }

  protected function __construct() {
    $this->init();
  }

  private function __clone() {}
  private function __sleep() {}
  private function __wakeup() {}

  public function get_table_name() {
    global $wpdb;
    return $wpdb->prefix.'customers';
  }

  public function install() {
    global $wpdb;
    $table_name = $this->get_table_name();

    if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
      $sql = "CREATE TABLE $table_name (
        ID int auto_increment primary key,
        name text,
        address text,
        city text
      );";
      require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
      dbDelta($sql);
    }
  }

  public function init() {
    add_filter('set-screen-option', array($this, 'set_screen'), 10, 3);
    add_action('admin_menu', array($this, 'admin_menu'));
  }

  public function set_screen($status, $option, $value) {
    return $value;
  }

  public function admin_menu() {
    $hook = add_menu_page('페이지 상단제목', '버튼이름2', 'manage_options', 'admintable',
      array($this, 'admin_page'), 'dashicons-admin-post');

    add_action("load-$hook", array($this, 'screen_option'));
  }

  public function screen_option() {
    $option = 'per_page';
    $args   = array(
      'label'   => 'Customers',
      'default' => 10,
      'option'  => 'customers_per_page'
    );

    add_screen_option($option, $args);
    $this->_tablelist = new admin_list_table();
  }

  public function admin_page() {
    echo '<div class="wrap"><h2>My List Table Test</h2>';
    echo '<form method="post">';

    $this->_tablelist->prepare_items();
    $this->_tablelist->display();

    echo '</form>';
    echo '</div>';
  }
}

function ATP() {
  return admin_table_plugin::instance();
}

ATP();

function admin_table_activate() {
  ATP()->install();
}

register_activation_hook(__FILE__, 'admin_table_activate');
