<?php

/**
 * run when plugin activate
 */
class Salesloo_Activator
{
    /**
     * Instance.
     *
     * Holds the plugin activator instance.
     *
     * @since 1.0.0
     * @access public
     */
    public static $instance = null;

    /**
     * run the plugin activator
     */
    public static function run()
    {
        update_option('salesloo_version', SALESLOO_VERSION);

        if (is_null(self::$instance)) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    /**
     * create product table if not exists on plugin activation
     */
    public function create_product_table()
    {
        global $wpdb;

        $sql = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}salesloo_product (
          ID int(11) NOT NULL AUTO_INCREMENT,
          slug varchar(255) NOT NULL,
          title varchar(255) NOT NULL,
          thumbnail_id int(11) NULL,
          description longtext NULL,
          duration varchar(255) DEFAULT 'onetime' NOT NULL,
          affiliate BOOL DEFAULT 1 NOT NULL,
          items longtext NOT NULL,
          status varchar(255) DEFAULT 'draft' NOT NULL,
          created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
		  updated_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
          PRIMARY KEY (ID)
        )";
        $wpdb->query($sql);

        $sql = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}salesloo_productmeta (
          meta_id int(11) NOT NULL AUTO_INCREMENT,
          product_id int(11) NOT NULL,
          meta_key varchar(255) NOT NULL,
          meta_value longtext NULL,
          PRIMARY KEY (meta_id)
        )";
        $wpdb->query($sql);
    }

    /**
     * create coupon table if not exists on plugin activation
     */
    public function create_coupon_table()
    {
        global $wpdb;

        $table = $wpdb->prefix . 'salesloo_coupon';
        $sql = "CREATE TABLE IF NOT EXISTS {$table} (
          ID int(11) NOT NULL AUTO_INCREMENT,
          title varchar(255) NOT NULL,
          description longtext NULL,
          rebate varchar(255) NOT NULL,
          active_start datetime DEFAULT NULL NULL,
          active_end datetime DEFAULT NULL NULL,
          is_private BOOL DEFAULT 0 NOT NULL,
          max_usage int(11) DEFAULT 0 NOT NULL,
          products longtext NULL,
          users longtext NULL,
          status varchar(255) DEFAULT 'draft' NOT NULL,
          created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
          updated_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
          PRIMARY KEY (ID)
        )";
        $wpdb->query($sql);
        $code_table = $wpdb->prefix . 'salesloo_coupon_code';
        $sql = "CREATE TABLE IF NOT EXISTS {$code_table} (
          code_id int(11) NOT NULL AUTO_INCREMENT,
          coupon_id int(11) NOT NULL,
          user_id int(11) NULL,
          code varchar(255) NOT NULL,
          PRIMARY KEY (code_id)
        )";
        $wpdb->query($sql);
        $usage_table = $wpdb->prefix . 'salesloo_coupon_usage';
        $sql = "CREATE TABLE IF NOT EXISTS {$usage_table} (
          usage_id int(11) NOT NULL AUTO_INCREMENT,
          coupon_id int(11) NOT NULL,
          code_id int(11) NOT NULL,
          invoice_id int(11) NOT NULL,
          PRIMARY KEY (usage_id)
        )";
        $wpdb->query($sql);
    }

    /**
     * create affiliate click table if not exists on plugin activation
     */
    public function create_affiliate_click_table()
    {
        global $wpdb;

        $meta_table = $wpdb->prefix . 'salesloo_affiliate_click';
        $sql = "CREATE TABLE IF NOT EXISTS {$meta_table} (
          ID bigint NOT NULL AUTO_INCREMENT,
          affiliate_id int(11) NOT NULL,
          visited_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
          product_id int(11) NOT NULL,
          uri varchar(255) NOT NULL,
          referer varchar(255) NULL,
          device varchar(255) NULL,
          ip varchar(255) NULL,
          browser varchar(255) NULL,
          platform varchar(255) NULL,
          PRIMARY KEY (ID)
        )";
        $wpdb->query($sql);
    }

    /**
     * create cart table if not exists on plugin activation
     */
    public function create_cart_table()
    {
        global $wpdb;

        $table = $wpdb->prefix . 'salesloo_cart';
        $meta_table = $wpdb->prefix . 'salesloo_cartmeta';

        $column = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s AND COLUMN_NAME = %s ",
            DB_NAME,
            $table,
            'products'
        ));

        if ($column) {
            $wpdb->query("DROP TABLE IF EXISTS {$table}");
            $wpdb->query("DROP TABLE IF EXISTS {$meta_table}");
        }

        $sql = "CREATE TABLE IF NOT EXISTS {$table} (
          ID bigint NOT NULL AUTO_INCREMENT,
          user varchar(255) NOT NULL,
          product_id int(11) NOT NULL,
          on_checkout tinyint DEFAULT NULL NULL,
          PRIMARY KEY (ID)
        )";
        $wpdb->query($sql);
    }

    /**
     * create checkout table if not exists on plugin activation
     */
    public function create_checkout_table()
    {
        global $wpdb;

        $table = $wpdb->prefix . 'salesloo_checkout';
        $sql = "CREATE TABLE IF NOT EXISTS {$table} (
          ID int(11) NOT NULL AUTO_INCREMENT,
          user varchar(255) NOT NULL,
          created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
          updated_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
          PRIMARY KEY (ID)
        )";
        $wpdb->query($sql);

        $meta_table = $wpdb->prefix . 'salesloo_checkoutmeta';
        $sql = "CREATE TABLE IF NOT EXISTS {$meta_table} (
          meta_id bigint(11) NOT NULL AUTO_INCREMENT,
          checkout_id int(11) NOT NULL,
          meta_key varchar(255) NOT NULL,
          meta_value longtext NULL,
          PRIMARY KEY (meta_id)
        )";
        $wpdb->query($sql);
    }

    /**
     * create order table if not exists on plugin activation
     */
    public function create_order_table()
    {
        global $wpdb;

        $table = $wpdb->prefix . 'salesloo_order';
        $sql = "CREATE TABLE IF NOT EXISTS {$table} (
          ID int(11) NOT NULL AUTO_INCREMENT,
          code varchar(255) NOT NULL,
          user_id int(11) NOT NULL,
          product_id int(11) NOT NULL,
          status varchar(255) DEFAULT 'inactive' NOT NULL,
          expired_at datetime NULL,
          created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
          updated_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
          PRIMARY KEY (ID)
        )";
        $wpdb->query($sql);

        $meta_table = $wpdb->prefix . 'salesloo_ordermeta';
        $sql = "CREATE TABLE IF NOT EXISTS {$meta_table} (
          meta_id bigint(11) NOT NULL AUTO_INCREMENT,
          order_id int(255) NOT NULL,
          meta_key varchar(255) NOT NULL,
          meta_value longtext NULL,
          PRIMARY KEY (meta_id)
        )";
        $wpdb->query($sql);

        $sql = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}salesloo_order_log (
          log_id bigint(11) NOT NULL AUTO_INCREMENT,
          order_id int(11) NOT NULL,
          created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
          note longtext NULL,
          PRIMARY KEY (log_id)
        )";
        $wpdb->query($sql);
    }

    /**
     * create access table if not exists on plugin activation
     */
    public function create_access_table()
    {
        global $wpdb;

        $table = $wpdb->prefix . 'salesloo_access';
        $sql = "CREATE TABLE IF NOT EXISTS {$table} (
          ID int(11) NOT NULL AUTO_INCREMENT,
          order_id int(11) NOT NULL,
          item_id int(11) NOT NULL,
          PRIMARY KEY (ID)
        )";
        $wpdb->query($sql);

        $meta_table = $wpdb->prefix . 'salesloo_accessmeta';
        $sql = "CREATE TABLE IF NOT EXISTS {$meta_table} (
          meta_id bigint(11) NOT NULL AUTO_INCREMENT,
          access_id int(255) NOT NULL,
          meta_key varchar(255) NOT NULL,
          meta_value longtext NULL,
          PRIMARY KEY (meta_id)
        )";
        $wpdb->query($sql);
    }

    /**
     * create commission table if not exists on plugin activation
     */
    public function create_commission_table()
    {
        global $wpdb;

        $table = $wpdb->prefix . 'salesloo_commission';
        $sql = "CREATE TABLE IF NOT EXISTS {$table} (
          ID bigint NOT NULL AUTO_INCREMENT,
          user_id int(11) NOT NULL,
          invoice_id int(11) NOT NULL,
          order_id int(11) NOT NULL,
          product_id int(11) NOT NULL,
          amount decimal(11, 4) NOT NULL,
          status varchar(255) NOT NULL,
          note longtext NULL,
          created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
          updated_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
          PRIMARY KEY (ID)
        )";
        $wpdb->query($sql);
    }

    /**
     * create commission withdrawal table if not exists on plugin activation
     */
    public function create_commission_withdrawal_table()
    {
        global $wpdb;

        $table = $wpdb->prefix . 'salesloo_commission_withdrawal';
        $sql = "CREATE TABLE IF NOT EXISTS {$table} (
          ID bigint NOT NULL AUTO_INCREMENT,
          user_id int(11) NOT NULL,
          amount decimal(11, 4) NOT NULL,
          method varchar(255) NOT NULL,
          note longtext NULL,
          proof_of_payment int(11) NULL,
          created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
          updated_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
          PRIMARY KEY (ID)
        )";
        $wpdb->query($sql);
    }


    /**
     * Create invoice database table
     * 
     * create invoice table into database if not exists on plugin activation
     *
     * @return void
     */
    public function create_invoice_table()
    {
        global $wpdb;

        $sql = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}salesloo_invoice (
          ID bigint NOT NULL AUTO_INCREMENT,
          number varchar(255) NOT NULL,
          user_id int(11) NOT NULL,
          summary longtext NOT NULL,
          total decimal(20, 4) NOT NULL,
          payment_method varchar(255) NOT NULL,
          type varchar(255) NOT NULL DEFAULT 'place_order',
          status varchar(255) NOT NULL,
          due_date_at datetime NULL,
          created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
          updated_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
          PRIMARY KEY (ID)
        )";
        $wpdb->query($sql);

        $meta_table = $wpdb->prefix . 'salesloo_invoicemeta';
        $sql = "CREATE TABLE IF NOT EXISTS {$meta_table} (
          meta_id bigint(11) NOT NULL AUTO_INCREMENT,
          invoice_id int(255) NOT NULL,
          meta_key varchar(255) NOT NULL,
          meta_value longtext NULL,
          PRIMARY KEY (meta_id)
        )";
        $wpdb->query($sql);

        $sql = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}salesloo_invoice_order (
          invoice_order_id bigint NOT NULL AUTO_INCREMENT,
          invoice_id int(11) NOT NULL,
          order_id int(11) NOT NULL,
          PRIMARY KEY (invoice_order_id)
        )";
        $wpdb->query($sql);

        /**
         * add executed_at column if not exists
         * 
         * since version 0.10.0
         */
        $column = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s AND COLUMN_NAME = %s ",
            DB_NAME,
            $wpdb->prefix . 'salesloo_invoice',
            'type'
        ));

        if (empty($column)) {
            $wpdb->query("ALTER TABLE {$wpdb->prefix}salesloo_invoice ADD type varchar(255) NOT NULL DEFAULT 'place_order' AFTER payment_method");
        }
    }

    public function create_notification_table()
    {
        global $wpdb;

        $table = $wpdb->prefix . 'salesloo_notification';
        $sql = "CREATE TABLE IF NOT EXISTS {$table} (
          ID bigint NOT NULL AUTO_INCREMENT,
          event varchar(255) NOT NULL,
          data longtext NOT NULL,
          executed BOOL DEFAULT 0 NOT NULL,
          executed_at datetime DEFAULT NULL NULL,
          created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
          PRIMARY KEY (ID)
        )";
        $wpdb->query($sql);

        /**
         * add executed_at column if not exists
         * 
         * since version 0.5.3
         */
        $column = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s AND COLUMN_NAME = %s ",
            DB_NAME,
            $table,
            'executed_at'
        ));

        if (empty($column)) {
            $wpdb->query("ALTER TABLE $table ADD executed_at datetime NULL DEFAULT NULL AFTER executed");
        }
    }

    public function create_event_table()
    {
        global $wpdb;

        $table = $wpdb->prefix . 'salesloo_event';
        $sql = "CREATE TABLE IF NOT EXISTS {$table} (
          ID bigint NOT NULL AUTO_INCREMENT,
          name varchar(255) NOT NULL,
          data longtext NOT NULL,
          executed_at datetime DEFAULT NULL NULL,
          created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
          PRIMARY KEY (ID)
        )";
        $wpdb->query($sql);
    }

    /**
     * Plugin activate constructor.
     *
     * @since 0.0.1
     * @access private
     */
    private function __construct()
    {
        $this->create_product_table();
        $this->create_coupon_table();
        $this->create_affiliate_click_table();
        $this->create_cart_table();
        $this->create_order_table();
        $this->create_access_table();
        $this->create_commission_table();
        $this->create_commission_withdrawal_table();
        $this->create_invoice_table();
        $this->create_notification_table();
        $this->create_event_table();
        $this->create_checkout_table();
    }
}
