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

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

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

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

			return $sql;
		}

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

			$table_name = $wpdb->prefix . 'ipjck_widget_stats';
			$sql = "CREATE TABLE $table_name (
									stat_id         int(11)             NOT NULL AUTO_INCREMENT,
									widg_id         int(11)             NOT NULL,
									widg_type       varchar(20)         NOT NULL,
									stat_date       datetime  DEFAULT '0000-00-00 00:00:00' NOT NULL,
									stat_view       int(11)             NOT NULL,
									stat_click      int(11)             NOT NULL,
									stat_subscribe  int(11)             NOT NULL,
							PRIMARY KEY stat_id (stat_id),
							KEY widget_id (widg_id)
			);";

			return $sql;
		}


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

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

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

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

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

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

}
?>
