<?php
if ( ! class_exists( 'IPVisc_Db' ))
{
  /**
   * Class for manage plugin database
   */
  class IPVisc_Db
  {
    /**
     * Take db version
     *
     * @var string
     */
    public $version = '1.0';

    /**
     * Class construct
     *
     * @return void
     */
    public function __construct()
    {
      global $ipvisc_db_version;
      $ipvisc_db_version = $this->version;
    }

    /**
     * Database query
     *
     * @return string
     */
    public function query_stats()
    {
      global $wpdb;

      $table_name = $wpdb->prefix . 'ipvisc_stats';
      $sql = "CREATE TABLE $table_name (
                stat_id          int(11)             NOT NULL AUTO_INCREMENT,
                video_id         int(11)             NOT NULL,
                stat_date        datetime  DEFAULT '0000-00-00 00:00:00' NOT NULL,
                stat_view        int(11)             NOT NULL,
                stat_subscribe   int(11)             NOT NULL,
                stat_play        int(11)             NOT NULL,
                stat_click       int(11)             NOT NULL,
              PRIMARY KEY stat_id (stat_id),
              KEY video_id (video_id)
            );";

      return $sql;
    }

    /**
     * Database query
     *
     * @return string
     */
    public function query()
    {
      $sql  = '';
      $sql .= $this->query_stats();
      return $sql;
    }

    /**
     * install
     *
     * @return void
     */
    public function install()
    {
      global $wpdb, $ipvisc_db_version;
      $installed_ver = get_option( "ipvisc_db_version" );

      if( ! $installed_ver || ( $installed_ver != $ipvisc_db_version ) )
      {
        $sql = $this->query();

        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        dbDelta( $sql );

        update_option( "ipvisc_db_version", $ipvisc_db_version );
      }
    }

    /**
     * update
     *
     * @return void
     */
    public function update()
    {
      global $ipvisc_db_version;
      if ( get_site_option( 'ipvisc_db_version' ) != $ipvisc_db_version ) {
        $this->install();
      }
    }
  }
}
?>
