woocommerce-coupon-affiliates-single-product.php 8.48 KB
<?php

/**
 * Plugin Name: Fgc WooCommerce Coupon Affiliates For Single Product
 * Plugin URI: http://fgc.vn
 * Description: Fgc WooCommerce Coupon Affiliates For Single Product
 * Author: Phuong An.
 * 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		Phuong An
 * @since		1.0
 */
add_action('plugins_loaded', 'fgc_run_cronjob_action', 2);

/**
 * Cronjob to add affiliate code
 * http://reize.sydneyecommerce.com.au/?cr_action=addAffiliateCode
 */
function fgc_run_cronjob_action() {
    $action = isset($_REQUEST['cr_action']) ? $_REQUEST['cr_action'] : '';
    if ($action == 'addAffiliateCode') {
        createAffiliateCode();
        exit();
    }
}

/*
 * Create Affiliate Code if user haven't it.
 */

function createAffiliateCode() {
    $users = get_users_of_blog();
    $list_affiliate = array();
    echo '<pre>';
    foreach ($users as $user) {
//        generateCode('AF', 6);
        $user_id = $user->ID;
        $_affiliate_code = get_user_meta($user_id, '_affiliate_code', true);
//        $list_affiliate[] = $_affiliate_code;
//        delete_user_meta($user_id, '_affiliate_code');
//        continue;
        if ($_affiliate_code == '') {
            add_user_meta($user_id, '_affiliate_code', generateAffiliateCode($user_id), true);
            echo '<br/>Updated for user_id: ' . $user_id;
        } else {
            echo '<br/>User_id: ' . $user_id . ' has "' . $_affiliate_code . '" code.';
        }
//        if (count($_affiliate_code) == 0) {
//            add_user_meta($user_id, '_affiliate_code', generateAffiliateCode($user_id), true);
//        } else {
//            if ($_affiliate_code[0] == '') {
//                update_user_meta($user_id, '_affiliate_code', generateAffiliateCode($user_id), '');
//            }
//        }
    }
}

/*
 * Create coupon code when user applies affiliate code, then change current coupon code to new coupon code
 *
 */

function update_affiliate_coupon_code() {
// Add Discount
    if (!empty($_POST['coupon_code'])) {
        $user_id = get_current_user_id();
        $_affiliate_code = get_user_meta($user_id, '_affiliate_code', true);    // Get affiliate code of the user
        if ($_affiliate_code != '' && $_POST['coupon_code'] == $_affiliate_code) {
            $_cart_total = (float) WC()->cart->total;   // Get total of current order
            $_credit_amount = (float) ClassProcessCronjob::getTotalRemainOfCustomer($user_id);  // Get current credit amount
            if ($_cart_total >= $_credit_amount) {
                $_POST['coupon_code'] = generate_affiliate_coupons($_credit_amount, $user_id);      // If cart total >= credit amount, create a coupon which have value = current credit amount
//                ClassProcessCronjob::updateTotalUsedOfUser($user_id, $_credit_amount, 'AUD', $_credit_amount);  // Reduce Credit Amount
            } else {
                $_POST['coupon_code'] = generate_affiliate_coupons($_cart_total, $user_id);     // If cart total < credit amount, create a coupon which have value = cart total
//                ClassProcessCronjob::updateTotalUsedOfUser($user_id, $_cart_total, 'AUD', $_credit_amount);     // Reduce Credit Amount
            }
            $_credit_amount = (float) ClassProcessCronjob::getTotalRemainOfCustomer($user_id);
            if ($_credit_amount > 0) {
                update_user_meta($user_id, '_affiliate_code', generateAffiliateCode($user_id), $_affiliate_code);
            } else {
                delete_user_meta($user_id, '_affiliate_code');    // Delete affiliate code which has been used.
            }
        }
    }
}

add_action('wp_loaded', 'update_affiliate_coupon_code', 35);


/*
 * Generate Random String
 */

function generateRandomString($length) {
    $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

/*
 * Generate Affiliate Code
 *
 */

function generateAffiliateCode($user_id) {
    $affiliateCode = generateCode('AF', 6);
    if (class_exists('FGC_ActiveCampaign')) {
        $contact["field[%UNIQUE_CUSTOMER_COUPON_CODE%,0]"] = $affiliateCode;
        FGC_ActiveCampaign::sync_contact_by_user_id($user_id, $contact);
    }
    return $affiliateCode;
}

/*
 * Generate code which have not exist yet
 */

function generateCode($prefix, $length) {
    $code = $prefix . generateRandomString($length);
    global $wpdb;
    $i = 0;
    while ($i < 5) {
        $results = $wpdb->get_results("SELECT * FROM wp_posts WHERE post_title = '$code' and post_type = 'shop_coupon'");
        if (count($results) == 0) {
            $results = $wpdb->get_results("SELECT * FROM wp_usermeta WHERE meta_key = '_affiliate_code' AND meta_value = '$code'");
            if (count($results) == 0) {
                return $code;
            } else {
                $code = $prefix . generateRandomString($length);
            }
        } else {
            $code = $prefix . generateRandomString($length);
        }
    }
}

/*
 * Generate coupon for affiliate
 */

function generate_affiliate_coupons($amount, $user_id) {
    $coupon_code = generateCode('SI', 6);  // create 8 letters coupon
    $discount_type = 'fixed_cart'; // Type: fixed_cart, percent, fixed_product, percent_product

    $coupon = array(
        'post_title' => $coupon_code,
        'post_content' => 'Affiliate coupon',
        'post_excerpt' => 'Affiliate coupon',
        'post_status' => 'publish',
        'post_author' => 1,
        'post_type' => 'shop_coupon'
    );

    $new_coupon_id = wp_insert_post($coupon);

// Add meta
    update_post_meta($new_coupon_id, 'discount_type', $discount_type);
    update_post_meta($new_coupon_id, 'coupon_amount', $amount);
    update_post_meta($new_coupon_id, 'individual_use', 'yes');
    update_post_meta($new_coupon_id, 'product_ids', '');
    update_post_meta($new_coupon_id, 'exclude_product_ids', '');
    update_post_meta($new_coupon_id, 'usage_limit', '1');
    update_post_meta($new_coupon_id, 'usage_limit_per_user', '1');
    update_post_meta($new_coupon_id, 'expiry_date', '');
    update_post_meta($new_coupon_id, 'apply_before_tax', 'no');
    update_post_meta($new_coupon_id, 'free_shipping', 'no');
    update_post_meta($new_coupon_id, 'exclude_sale_items', 'no');
    update_post_meta($new_coupon_id, 'product_categories', '');
    update_post_meta($new_coupon_id, 'exclude_product_categories', '');
    update_post_meta($new_coupon_id, 'minimum_amount', '');
    update_post_meta($new_coupon_id, 'customer_email', '');
    update_post_meta($new_coupon_id, 'affiliate_id', $user_id);

    return $coupon_code;
}

add_action('woocommerce_payment_complete', 'reduce_credit_amount_after_order_completed');

/*
 * Reduce credit amount after order completed.
 */

function reduce_credit_amount_after_order_completed($order_id) {
    $order = new WC_Order($order_id);
    global $woocommerce;
    $cartObject = $woocommerce->cart;
    if (!empty($cartObject) && is_object($cartObject)) {
        $applied_coupon = $cartObject->get_coupons();
        if (count($applied_coupon) > 0) {
            foreach ($applied_coupon as $key => $value) {
                $applied_coupon_id = $value->id;
                $affiliate_id = get_post_meta($applied_coupon_id, 'affiliate_id', false);
                $coupon_amount = get_post_meta($applied_coupon_id, 'coupon_amount', false);
                if (count($affiliate_id) > 0 && count($coupon_amount) > 0) {
                    $user_id = get_current_user_id();
                    $_credit_amount = (float) ClassProcessCronjob::getTotalRemainOfCustomer($user_id);
                    ClassProcessCronjob::updateTotalUsedOfUser($user_id, $coupon_amount[0], 'AUD', $_credit_amount);  // Reduce Credit Amount
                }
            }
        }
    }
}