woocommerce-referral-coupon-affiliates.php 9.17 KB
<?php

/**
 * Plugin Name: Fgc WooCommerce Referral Subscription, Affiliates and Coupon
 * Plugin URI: http://fgc.vn
 * Description: Fgc WooCommerce Referral Subscription, Affiliates and Coupon
 * Author: Hoang Bien.
 * Author URI: http://fgc.vn
 * Version: 1.0
 *
 * Copyright 2016 Prospress, Inc.  (email : freedoms@prospress.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @package		WooCommerce Subscriptions
 * @author		Hoang Bien
 * @since		1.0
 */
global $firstreferee;
global $adminAffiliateID;
global $user_id_created;
$user_id_created = 2;

$check_host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : null;
if (strrpos('fgc' . $check_host, '16jason79.dev.fgct.net')) {
    $adminAffiliateID = array(230, 231, 232);
    $firstreferee = array('firstreferee', 'firstreferee230', 'firstreferee231', 'firstreferee232');
} elseif (strrpos('fgc' . $check_host, 'dev.reize.com.au')) {
    $adminAffiliateID = array(248, 250, 251);
    $firstreferee = array('firstreferee', 'firstreferee248', 'firstreferee250', 'firstreferee251');
} else {
    $adminAffiliateID = array(407, 408, 409);
    $firstreferee = array('firstreferee', 'firstreferee407', 'firstreferee408', 'firstreferee409');
}


include_once 'class.processcronjob.php';

add_action('plugins_loaded', 'fgc_run_cronjob_action_init', 1);

/**
 * romoveCouponSub
 * http://reize.sydneyecommerce.com.au/?cr_action=romoveCouponSub&sub=895&customer=94
 */
function fgc_run_cronjob_action_init() {
    $action = isset($_REQUEST['cr_action']) ? $_REQUEST['cr_action'] : '';
    if ($action == 'addCoupon') {
        $type = isset($_REQUEST['type']) ? $_REQUEST['type'] : 'month'; //month or hours
        ClassProcessCronjob::createCouponFromEarnMoneyInAffiliateSystem($type);
        exit();
    } elseif ($action == 'removeCoupon') {
        $type = isset($_REQUEST['type']) ? $_REQUEST['type'] : 'month'; //month or hours
        ClassProcessCronjob::removeCouponInSubscription($type);
        exit();
    } elseif ($action == 'emptyTable') {
        fgc_empty_table();
        exit();
    } elseif ($action == 'checkResult') {
        fgc_checkResult();
        exit();
    } elseif ($action == 'romoveCouponSub') {
        $sub_id = isset($_REQUEST['sub']) ? $_REQUEST['sub'] : 0;
        $customer_id = isset($_REQUEST['customer']) ? $_REQUEST['customer'] : 0;
        fgc_remove_coupon_form_sub($sub_id, $customer_id);
        exit();
    } elseif ($action == 'refundAmountForClient') {
        ClassProcessCronjob::refundAmountForClient();
        exit();
    } elseif ($action == 'checkCoupon') {
        fgc_checkResultUserCoupon();
        exit();
    }
}

function fgc_update_subscriptions($post_id) {

    $post_object = get_post($post_id);
    // file_put_contents(dirname(__FILE__).DIRECTORY_SEPARATOR.'text.txt','--- Post object ---- \n',FILE_APPEND);
    //file_put_contents(dirname(__FILE__).DIRECTORY_SEPARATOR.'text.txt', print_r($post_object,true),FILE_APPEND);
    if ($post_object->post_type == 'scheduled-action') {//scheduled-action, shop_subscription
        $post_content = isset($post_object->post_content) ? $post_object->post_content : '';
        if ($post_content != '') {
            $sub_id = json_decode($post_content);

            $sub_id = isset($sub_id->subscription_id) ? $sub_id->subscription_id : 0;
            if ($sub_id > 0) {
                global $wpdb;
                $userCouponTable = $wpdb->prefix . 'woocommerce_coupon_affiliates';
                $query = "SELECT * FROM `$userCouponTable` WHERE `subscriptions_id` = '$sub_id' AND `used` = '0' LIMIT 0,1";
                $result = $wpdb->get_results($query);

                if (!empty($result)) {// && $action == 'editpost'
//                    $coupon_id = isset($result[0]->coupon_id) ? $result[0]->coupon_id : 0;
//                    if ($coupon_id > 0) {
//                        $discount_amount = get_post_meta($coupon_id, 'coupon_amount', true);
//                        //$current_discount = get_post_meta($post_id, '_cart_discount', true);
//                        if ($discount_amount > 0) {
//                            update_post_meta($sub_id, '_cart_discount', $discount_amount);
//                        }
//                    }
//                    $next_date_payment = get_post_meta($sub_id, '_schedule_next_payment', true);
//                    $query = "UPDATE `$userCouponTable` SET `date_payment` = '$next_date_payment'  WHERE `subscriptions_id` = '$sub_id' AND `used` = '0'";
//                    $wpdb->query($query);
                }
            }
        }
    }
}

//add_action('save_post', 'fgc_update_subscriptions', 99);
//add_action('wcs_webhook_subscription_updated', 'fgc_test_update', 1, 1);

function fgc_test_update($sub_id) {
    return;
}

function fgc_empty_table() {
    $query1 = "TRUNCATE wp_woocommerce_coupon_affiliates";
    $query2 = "TRUNCATE wp_aff_referrals_used";
    global $wpdb;
    $wpdb->query($query1);
    $wpdb->query($query2);
}

function fgc_checkResult() {
    global $wpdb;
    $userCouponTable = $wpdb->prefix . 'woocommerce_coupon_affiliates';
    $query = "SELECT * FROM `$userCouponTable` order by id LIMIT 0, 100";
    $result = $wpdb->get_results($query);
    echo "<pre>";
    echo "result 1<br/>";
    print_r($result);
    $userCouponTable = $wpdb->prefix . 'aff_referrals_used';
    $query = "SELECT * FROM `$userCouponTable` order by id LIMIT 0, 100";
    $result = $wpdb->get_results($query);
    print_r($result);
    $totalRemain = ClassProcessCronjob::getTotalRemainOfCustomer(11);
    echo $totalRemain;
}

function fgc_checkResultUserCoupon() {
    global $wpdb;
    $table_name_new3 = $wpdb->prefix . 'aff_referrals_user_coupons';
    $query = "SELECT * FROM `$table_name_new3`";
    $result = $wpdb->get_results($query);
    echo "<pre>";
    print_r($result);
    /* $query = "SHOW TABLES FROM reize";
      $result = $wpdb->get_results($query);
      echo "<pre>";
      print_r($result);
      $query = "select *
      from information_schema.columns
      where table_schema = 'reize'
      and table_name = '$table_name_new3'";
      $result = $wpdb->get_results($query);
      echo "<pre>";
      print_r($result); */
//    $query = "UPDATE `{$wpdb->prefix}aff_referrals_used` SET `amount`= '0' WHERE `user_id`='134';";
//    $wpdb->query($query);
}

function fgc_remove_coupon_form_sub($sub_id, $customer_id) {
    if ($sub_id > 0 && $customer_id > 0) {
        ClassProcessCronjob::removeCouponOfUserFromSubscription($sub_id, $customer_id);
    }
}

global $wpdb;
$extra_db_version = '1.0';

$fgc_installed_ver = get_option("af_extra_db_version");

if ($fgc_installed_ver != $extra_db_version) {

    $table_name_new1 = $wpdb->prefix . 'woocommerce_coupon_affiliates';

    $sql1 = "CREATE TABLE IF NOT EXISTS `$table_name_new1` (
  `id` BIGINT(20) NOT NULL AUTO_INCREMENT,
  `coupon_id` BIGINT(20) NULL,
  `user_id` BIGINT(20) NULL,
  `subscriptions_id` BIGINT(20) NULL,
  `date_create` DATETIME NULL,
  `date_payment` DATETIME NULL,
  `used` TINYINT(1) NULL,
  PRIMARY KEY (`id`));";
    $table_name_new2 = $wpdb->prefix . AFFILIATES_TP . 'referrals_used';
    $sql2 = "CREATE TABLE IF NOT EXISTS `$table_name_new2` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `user_id` bigint(20) DEFAULT NULL,
  `amount` decimal(18,2) DEFAULT NULL,
  `currency_id` char(3) DEFAULT NULL,
  `last_amount` decimal(18,2) DEFAULT NULL,
PRIMARY KEY (`id`));";

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

    update_option("af_extra_db_version", $extra_db_version);
}
//do_action( "save_post_{$post->post_type}", $post_ID, $post, $update );

$extra_db_version2 = '1.0';

$fgc_installed_ver2 = get_option("af_extra_db_version2");

if ($fgc_installed_ver2 != $extra_db_version2) {
    $table_name_new3 = $wpdb->prefix . 'aff_referrals_user_coupons';
    $sql3 = "CREATE TABLE IF NOT EXISTS `$table_name_new3` (
  `coupon_id` BIGINT(20) NOT NULL,
  `coupon_code` VARCHAR(50) NULL,
  `amount` DECIMAL(20,6) NULL,
  `amount_feree` DECIMAL(20,6) NULL,
  `user_id` BIGINT(20) NULL,
  `date_created` DATETIME NULL,
  `is_success` TINYINT(1) NULL,
  PRIMARY KEY (`coupon_id`))
COMMENT = 'Bang nay se luu lai cac coupon da su dung cho first order';";

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

    update_option("af_extra_db_version2", $extra_db_version2);
}

add_action('save_post_shop_order', 'fgc_updateLogCoupon', 1);

function fgc_updateLogCoupon() {
    if (!session_id())
        @session_start();
    $coupon_id = isset($_SESSION['data_coupon']['coupon_code_id']) ? $_SESSION['data_coupon']['coupon_code_id'] : 0;
    ClassProcessCronjob::setSuccessItemReferralsUserCoupons($coupon_id);
    unset($_SESSION['data_coupon']);
}