<?php
/**
 * Created by PhpStorm.
 * User: matub
 * Date: 2018/11/20
 * Time: 13:36
 */

if(!class_exists('myPluginDatabaseClass')) {
  class myPluginDatabaseClass
  {

    const MYTABLE = 'backupresotre';

    function __construct()
    {
      require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    }

    function install()
    {
      global $jal_db_version;
      $jal_db_version = '1.0';
      global $wpdb;

      $table_name = $wpdb->prefix . self::MYTABLE;

      $charset_collate = $wpdb->get_charset_collate();

      $sql = "CREATE TABLE $table_name (
    id mediumint(9) NOT NULL AUTO_INCREMENT,
    time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
    name tinytext NOT NULL,
    text text NOT NULL,
    url varchar(55) DEFAULT '' NOT NULL,
    UNIQUE KEY id (id)
  ) $charset_collate;";


      dbDelta($sql);

      add_option('jal_db_version', $jal_db_version);

      //$this->jal_install_data();
    }

    function jal_install_data()
    {
      global $wpdb;

      $welcome_name = 'Wordpress さん';
      $welcome_text = 'おめでとうございます、インストールに成功しました！';

      $table_name = $wpdb->prefix . self::MYTABLE;

      $wpdb->insert(
        $table_name,
        array(
          'time' => current_time('mysql'),
          'name' => $welcome_name,
          'text' => $welcome_text,
        )
      );
    }

    function uninstall()
    {
      global $wpdb;

      $table_name = $wpdb->prefix . self::MYTABLE;

      $wpdb->query("DROP TABLE IF EXISTS $table_name");

      delete_option("jal_db_version");
    }

    function get_jal_data($id)
    {
      global $wpdb;
      $sql = "select time,text from " . $wpdb->prefix . "liveshoutbox where id=$id;";
      $rs = $wpdb->get_results($wpdb->prepare($sql));
      if (isset($rs)) {
        return ($rs[0]->time . " : " . $rs[0]->text);
      } else {
        return;
      }
    }
  }
}