<?php

if( ! class_exists( 'MDWC_Configuration' ) ):
class MDWC_Configuration {

    private static $_instance;

    /**
     * Single ton
     * 
     * @return MDWC_Configuration
     * 
     * @since 1.1.0
     */
    public static function get_instance() {

        if( self::$_instance == null ) {
            self::$_instance = new self();
        }

        return self::$_instance;

    }

    /**
     * Constructor
     * 
     * @since 1.1.0
     */
    public function __construct() {

        $current_version = get_option( 'mdwc_db_version' );

        if( 
            ! $current_version 
            || 
            ( $current_version && version_compare( $current_version, MDWC_DB_VERSION, '<' ) ) 
        ) {

            add_action( 'plugins_loaded', array( $this, 'update' ) );

        }

    }

    /**
     * Activation Callback
     * 
     * @since 1.1.0
     */
    public static function activate() {

        self::get_instance()->create_tables();

    }

    /**
     * Create Tables | Activation Callback
     * 
     * @since 1.1.0
     */
    public function create_tables() {

        global $wpdb;

        $charset_collate = $wpdb->get_charset_collate();
        $visitor_table = $wpdb->prefix . 'mdwc_visitors';
        $insights_table = $wpdb->prefix . 'mdwc_insights';
        $insights_result = '';

        $sql = "CREATE TABLE IF NOT EXISTS $visitor_table (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            visitor_ip varchar(255) NOT NULL,
            created_at datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
            PRIMARY KEY  (id)
        ) $charset_collate;";

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

        if( ! empty( $visitor_result ) ) {

            $sql = "CREATE TABLE IF NOT EXISTS $insights_table (
                id mediumint(9) NOT NULL AUTO_INCREMENT,
                visitor_id varchar(255) NOT NULL,
                product_id varchar(255) NOT NULL,
                `event` varchar(255) NOT NULL,
                is_midnight varchar(10) NOT NULL,
                price varchar(255) NOT NULL,
                created_at datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
                PRIMARY KEY  (id)
            ) $charset_collate;";

            $insights_result = dbDelta( $sql );

        }

        if( ! empty( $visitor_result ) && ! empty( $insights_result ) ) {

            update_option( 'mdwc_db_version', MDWC_DB_VERSION );

        }

    }

    /**
     * Update | Action Callback
     * 
     * @since 1.1.0
     */
    public function update() {

        $this->create_tables();

    }

}

MDWC_Configuration::get_instance();

endif;