<?php

//------------------------------------------------------------

// PLUGING ACTIVATION

//------------------------------------------------------------



function wpsa_affiliate_activate( ) {

    global $wpdb;



    $table_name_wpsa_affiliate_product_commission = $wpdb->prefix . 'wpsa_affiliate_product_commission';

    $table_name_wpsa_affiliate_subscription_commission = $wpdb->prefix . 'wpsa_affiliate_subscription_commission';

    $wpsa_affiliate_product_sales = $wpdb->prefix . 'wpsa_affiliate_product_sales';

    $wpsa_affiliate_subscription_sales = $wpdb->prefix . 'wpsa_affiliate_subscription_sales';

    $wpsa_affiliate_referrals = $wpdb->prefix .  'wpsa_affiliate_referrals';

    

    //detects if this is a new installation or simply an update.

    $new_installation = $wpdb->get_var("show tables like '$table_name_wpsa_affiliate_product_commission'" ) ;



    if ( !$new_installation ) {

        $sql = "CREATE TABLE " . $table_name_wpsa_affiliate_product_commission . " (

                        id mediumint(9) NOT NULL AUTO_INCREMENT PRIMARY KEY ,

                        `product_id` INT NOT NULL ,

                        `page_id` INT NOT NULL ,

                        `commission` varchar(100) NOT NULL

		);";



        $sql .= "CREATE TABLE " . $table_name_wpsa_affiliate_subscription_commission . " (

                        id mediumint(9) NOT NULL AUTO_INCREMENT PRIMARY KEY ,

                        `subsc_id` INT NOT NULL ,

                        `page_id` INT NOT NULL ,

                        `commission` varchar(100) NOT NULL,

                        `recurring` ENUM( 'no', 'yes' ) NOT NULL DEFAULT 'no'

		);";



        $sql .= "CREATE TABLE " . $wpsa_affiliate_product_sales . " (

                    id mediumint(9) NOT NULL AUTO_INCREMENT PRIMARY KEY ,

                  `affiliate_uid` int(11) NOT NULL,

                  `pid` int(11) NOT NULL,

                  `pprice` varchar(100) NOT NULL,

                  `discounted_price` varchar(100) NOT NULL,

                  `payment_date` varchar(200) NOT NULL,

                  `masspay_payment_date` varchar(200) NOT NULL,

                  `refund_date` varchar(200) NOT NULL,

                  `date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',

                  `txn_id` varchar(200) NOT NULL,

                  `masspay_txn_id` varchar(200) NOT NULL,

                  `refund_txn_id` varchar(200) NOT NULL,

                  `coupon_code` varchar(200) NOT NULL,

                  `discount` varchar(100) NOT NULL,

                  `commission` varchar(100) NOT NULL,

                  `status` varchar(100) DEFAULT NULL

		);";



        $sql .= "CREATE TABLE " . $wpsa_affiliate_referrals . " (

                    id int NOT NULL AUTO_INCREMENT PRIMARY KEY ,

                    `user_id` INT NULL ,

                    `ps_id` INT NULL ,

                    `ip_address` VARCHAR(200) NULL ,

                    `referred_for` VARCHAR(200) NULL ,

                    `referred_from` VARCHAR(200) NULL ,

                    `landing_page` VARCHAR(200) NULL ,

                    `date` DATETIME NULL

		);";



        $sql .= "CREATE TABLE " . $wpsa_affiliate_subscription_sales . " (

                        id mediumint(9) NOT NULL AUTO_INCREMENT PRIMARY KEY ,

                        `affiliate_uid` INT NOT NULL ,

                        `subsc_id` INT NOT NULL ,

                        `payment_date` varchar(200) NOT NULL,

                        `masspay_payment_date` varchar(200) NOT NULL,

                        `refund_date` varchar(200) NOT NULL,

                        `date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',

                        `txn_id` varchar(200) NOT NULL,

                        `masspay_txn_id` varchar(200) NOT NULL,

                        `refund_txn_id` varchar(200) NOT NULL,

                        `sell` varchar(200) NOT NULL,

                        `commission` varchar(200) NOT NULL,

                        `status` VARCHAR( 100 ) NULL

		);";

        

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

        dbDelta($sql );

    }



    $date = date('M-d-Y', strtotime("+1 days"));

    $next_time_stamp = strtotime($date);

    //wp_schedule_event($next_time_stamp, 'hourly', 'wpsa_affiliate_check_refund_hook');

    wp_schedule_event(time(), 'hourly', 'wpsa_affiliate_check_refund_hook');

}



//------------------------------------------------------------

// PLUGING DEACTIVATION

//------------------------------------------------------------

function wpsa_affiliate_deactivate() {

    wp_clear_scheduled_hook('wpsa_affiliate_check_refund_hook');

}



//------------------------------------------------------------

//  PLUGING UNINSTALLATION

//------------------------------------------------------------

function wpsa_affiliate_uninstall() {

    global $wpdb;

    

    $table_name_wpsa_affiliate_product_commission = $wpdb->prefix . 'wpsa_affiliate_product_commission';

    $table_name_wpsa_affiliate_subscription_commission = $wpdb->prefix . 'wpsa_affiliate_subscription_commission';

    $wpsa_affiliate_product_sales = $wpdb->prefix . 'wpsa_affiliate_product_sales';

    $wpsa_affiliate_subscription_sales = $wpdb->prefix . 'wpsa_affiliate_subscription_sales';

    $wpsa_affiliate_referrals = $wpdb->prefix .  'wpsa_affiliate_referrals';

    

    if ($wpdb->get_var("SHOW TABLES LIKE '".$table_name_wpsa_affiliate_product_commission."'") == $table_name_wpsa_affiliate_product_commission) {

        $wpdb->query( "DROP TABLE $table_name_wpsa_affiliate_product_commission, $table_name_wpsa_affiliate_subscription_commission, $wpsa_affiliate_product_sales, $wpsa_affiliate_subscription_sales, $wpsa_affiliate_referrals" );

    }

}



//------------------------------------------------------------

//  CREATE ADMIN MENU

//------------------------------------------------------------



if (function_exists('wpsa_install')) {

    add_action('admin_menu', 'wpsa_affiliate_menu', 13);

    function wpsa_affiliate_menu() {

        global $affiliate_handler;

        global $submenu;

        //$affiliate_handler = sa_rt_get_addonsubmenu('wpsa-affiliate-options');

        if (!isset($submenu['wpsa-addon']) && count($submenu['wpsa-addon']<=0))  $affiliate_handler = 'wpsa-addon';

        else $affiliate_handler = 'wpsa-affiliate-options';



        add_submenu_page('wpsa-addon', 'WPSA Affiliate', 'Affiliates', 'manage_options', $affiliate_handler, 'wpsa_affiliate_options_html');

    }

}



//------------------------------------------------------------

//  INCLUDE CSS ON ADMIN SIDE

//------------------------------------------------------------

wp_enqueue_style('wpsa_admin_style', WPSA_AFFILIATE_URL.'/css/wpsa_admin_style.css');;



//------------------------------------------------------------

//  INCLUDE CSS ON FRONT SIDE

//------------------------------------------------------------

add_action( 'wp_print_styles', 'wpsa_affiliate_options_load_css' );

function wpsa_affiliate_options_load_css() {

    if (!is_admin())

        wp_enqueue_style('wpsa_style', WPSA_AFFILIATE_URL.'/css/wpsa_style.css');

        wp_enqueue_style('fancybox-css', WPSA_AFFILIATE_URL.'/fancybox/jquery.fancybox-1.3.1.css');

}



//------------------------------------------------------------

//  INCLUDE JS ON FRONT SIDE

//------------------------------------------------------------

add_action( 'wp_print_scripts', 'wpsa_affiliate_options_load_js' );

function wpsa_affiliate_options_load_js() {

    global $affiliate_handler;

    if ( strpos($_SERVER['REQUEST_URI'], $affiliate_handler ) !== false ) {

        wp_enqueue_script('wpsa-affiliate-js-admin',WPSA_AFFILIATE_URL.'/js/wpsa-affiliate-admin.js');

		wp_enqueue_script('wpsa-affiliate-admin-menu',WPSA_AFFILIATE_URL.'/js/wpsa-affiliate-admin-menu.js');

        wp_enqueue_script('jquery-validate',WPSA_AFFILIATE_URL.'/js/jquery.validate.js');

    }

    if (!is_admin()) {

        //wp_enqueue_script('mousewheel',WPSA_AFFILIATE_URL.'/fancybox/jquery.mousewheel-3.0.2.pack.js', array('jquery'));

        wp_enqueue_script('fancybox',WPSA_AFFILIATE_URL.'/fancybox/jquery.fancybox-1.3.1.js', 'jquery');

        wp_enqueue_script('wpsa-affiliate-js',WPSA_AFFILIATE_URL.'/js/wpsa-affiliate.js');

        wp_localize_script('wpsa-affiliate-js', 'wpsa_affiliate_var', array(

            'admin_ajax_php' => get_option('siteurl').'/wp-admin/admin-ajax.php'

        ));

    }

}   



//------------------------------------------------------------

//  SHOW NOTIC WHEN WPSA PLUGIN IS ABSENT OR INACTIVE

//------------------------------------------------------------



add_action( 'admin_notices', 'wpsa_affiliate_notice' );



function wpsa_affiliate_notice() {

    global $cache_enabled;

    if (!function_exists('wpsa_install'))

        echo '<div class="error"><p><strong>The WP SalesAutomator plugin must be installed to work wpsa-affiliate plugin.</strong></p></div>';

}



//------------------------------------------------------------

//  SHORT CODE TO SHOW REGISTRATION FORM FOR AFFILIATE USERS

//------------------------------------------------------------

add_shortcode('wpsa_affiliate_register', 'wpsa_affiliate_register');



function wpsa_affiliate_register() {

    global $wpsa_errors;

    $reg = get_option('wpsa_reg');

    $wpsa_affiliate = get_option('wpsa_affiliate');



    if ($wpsa_errors) {

        $error_msg = '<div id="login_error">';

        foreach ($wpsa_errors->errors as $error) {

            $error_msg .=  $error[0].'<br/>';

        }

        $error_msg .= '</div>';

        //echo $error_msg;

    }

    $reg_form = '';

    $reg_form .= '

    <div id="aff_register">

    <form id="" class="" method="post" action="" enctype="">

            <fieldset class="fieldset">

                <legend class="fieldheader">Register</legend>'.$error_msg.'

                <ul id="wpsa-regform">

                        <div class="fieldsetcontent">

                            <p><label for="username"><span>Username:</span></label><br>

                            <input type="text" value="" id="username" name="username"></p>

                        

                            <p><label for="email"><span>Paypal Email:</span></label><br>

                            <input type="text" value="" id="email" name="email"></p>

                            ';



    if ( isset( $reg['first_name'] ) ) {

        $reg_form .= '<p>

            <label for="first_name"><span>First Name:</span></label><br>

            <input type="text" value="" id="first_name" name="first_name">

                        </p>';

    }

    if ( isset( $reg['last_name'] ) ) {

        $reg_form .= '<p>

            <label for="last_name"><span>Last Name:</span></label><br>

            <input type="text" value="" id="last_name" name="last_name">

        </p>';

    }

    if ( isset( $reg['phone'] ) ) {

        $reg_form .= '<p>

            <label for="phone"><span>Phone Number:</span></label><br>

            <input type="text" value="" id="phone" name="phone">

        </p>';

    }

    if ( isset( $reg['tax'] ) ) {

        $reg_form .= '<p>

            <label for="tax"><span>Tax ID or SSN: (US only)</span></label><br>

            <input type="text" value="" id="tax" name="tax">

        </p>';

    }

    if ( isset( $reg['address'] ) ) {

        $reg_form .= '<p>

            <label for="address"><span>Address:</span></label><br>

            <input type="text" value="" id="address" name="address">

        </p>';

    }

    if ( isset( $reg['city'] ) ) {

        $reg_form .= '<p>

            <label for="city"><span>City:</span></label><br>

            <input type="text" value="" id="city" name="city">

        </p>';

    }

    if ( isset( $reg['zip'] ) ) {

        $reg_form .= '<p>

            <label for="zip"><span>Postal/Zip code:</span></label><br>

            <input type="text" value="" id="zip" name="zip">

        </p>';

    }

    if ( isset( $reg['state'] ) ) {

        $reg_form .= '<p>

            <label for="state"><span>County/State:</span></label><br>

            <input type="text" value="" id="state" name="state">

        </p>';

    }

    if ( isset( $reg['country'] ) ) {

        $reg_form .= '<p>

            <label for="country"><span>Country:</span></label><br>

            <input type="text" value="" id="country" name="country">

        </p>';

    }



    $reg_form .= '<p>

        <input type="checkbox" id="tnc" name="tnc" value="tnc">

        I understand and accept all <a href="#wpsatnc" id="tnctext">terms and conditions</a>

        <div id ="wpsatnc-holder"><p id="wpsatnc">'.$wpsa_affiliate['tnc'].'</p></div>

    </p>';



    $reg_form .= '</div></ul></fieldset>';

    $reg_form .= wp_nonce_field('wpsa_reg');

    $reg_form .= '<input type="hidden" value="affiliate"  name="user_type">';

    $reg_form .= '<p class=""><input type="submit" value="Signup" class="" id="" name="submit"></p></form></div>';

    return $reg_form;

}



//------------------------------------------------------------

//  TO HANDLE AFFILIATE USER'S REGISTRAION

//------------------------------------------------------------

add_action('init', 'wpsa_affiliate_handle_reg');



function wpsa_affiliate_handle_reg() {

    if ( wp_verify_nonce($_POST['_wpnonce'], 'wpsa_reg') == 1)  {



        if ($_POST) {



            global $wpsa_errors;

            $wpsa_errors = new WP_Error();



            require_once( ABSPATH . WPINC . '/registration.php');

            

            $user_login = sanitize_user( $_POST['username'] );

            $user_email = apply_filters( 'user_registration_email', $_POST['email'] );



            // Check the username

            if ( $user_login == '' )

                    $wpsa_errors->add('empty_username', __('<strong>ERROR</strong>: Please enter a username.'));

            elseif ( !validate_username( $user_login ) ) {

                    $wpsa_errors->add('invalid_username', __('<strong>ERROR</strong>: This username is invalid.  Please enter a valid username.'));

                    $user_login = '';

            } elseif ( username_exists( $user_login ) )

                    $wpsa_errors->add('username_exists', __('<strong>ERROR</strong>: This username is already registered, please choose another one.'));

            

            // Check the e-mail address

            if ($user_email == '') {

                    $wpsa_errors->add('empty_email', __('<strong>ERROR</strong>: Please type your e-mail address.'));

            } elseif ( !is_email( $user_email ) ) {

                    $wpsa_errors->add('invalid_email', __('<strong>ERROR</strong>: The email address isn&#8217;t correct.'));

                    $user_email = '';

            } elseif ( email_exists( $user_email ) )

                    $wpsa_errors->add('email_exists', __('<strong>ERROR</strong>: This email is already registered, please choose another one.'));



            //check tnc

            if ( $_POST['tnc'] =='' ) {

                $wpsa_errors->add('empty_tnc', __('<strong>ERROR</strong>: Please accept terms and conditions.'));

            }



            if ( $wpsa_errors->get_error_code() )

		return;



            $user_pass = wp_generate_password();

            $user_id = wp_create_user( $user_login, $user_pass, $user_email );

            if ( !$user_id ) {

                    $wpsa_errors->add('registerfail', sprintf(__('<strong>ERROR</strong>: Couldn&#8217;t register you... please contact the <a href="mailto:%s">webmaster</a> !'), get_option('admin_email')));

                    return $wpsa_errors;

            }

            wp_new_user_notification($user_id, $user_pass);



            if ( $user_id ) {

                update_usermeta($user_id, 'wpsa_user', $_POST);

                //wp_redirect(site_url() .'/wp-login.php?checkemail=registered');

                $wpsa_errors->add('registersuccess', sprintf(__('Registration complete. Please check your e-mail.')));

                return $wpsa_errors;

                exit();

            }

        }

    }

}



//------------------------------------------------------------

//  ADD HIDDEN INPUT (REFERAL ID) TO PAYPAL PRODUCT FORM

//------------------------------------------------------------

//to add hidden inputs to paypal product form

add_action('wpsa_product_paypal_form', 'wpsa_affiliate_product_paypal_form', 12);



function wpsa_affiliate_product_paypal_form() {

    global $wpdb;

    //special case if affiliate addon present

    //get user_ud from username saved in cookies as wpsa-ref

    $sql_ref_user = "SELECT ID FROM ".$wpdb->base_prefix."users WHERE user_login = '".trim( $_COOKIE['wpsa-ref'] )."'";

    $row_ref_user = $wpdb->get_row( $sql_ref_user );

        ?>

        <input type="hidden" name="os2_1" value="affiliate_ref"/>

        <input type="hidden" name="on2_1" value="<?php echo $row_ref_user->ID;?>">

        <?php

}



//------------------------------------------------------------

//  CRON JOB TO CHECK AFFILIATE USER'S PAYMENT STATUS AGAINST

//  REFUND PERIOD. IF STATUS = PENDING AND PAYMENT DATE >

//  REFUND PERIOD THEN SET STATUS = SET TO PAID

//------------------------------------------------------------



add_action('wpsa_affiliate_check_refund_hook', 'wpsa_affiliate_check_refund');

function wpsa_affiliate_check_refund() {

    global $wpdb;

    $affiliate = get_option('wpsa_affiliate');



    //for product

    $sql_affiliate = "SELECT id, DATEDIFF(now(), date) as date_diff FROM ".$wpdb->prefix."wpsa_affiliate_product_sales where status = 'pending' ";

    $rows_affiliate = $wpdb->get_results($sql_affiliate);

    if ($rows_affiliate) {

        $ids = '';

        foreach ($rows_affiliate as $row_affiliate) {

            if ( $row_affiliate->date_diff > $affiliate['refund_period']) {

                $ids .= $row_affiliate->id.',';

            }

        }



        $ids = substr($ids, 0, -1);

        $sql_update = "UPDATE " .$wpdb->prefix. "wpsa_affiliate_product_sales SET `status` = 'set_to_paid' WHERE id in ($ids) ";

        $sql_update = $wpdb->query($sql_update);

    }



    //for subscription

    $sql_affiliate = "SELECT id, DATEDIFF(now(), date) as date_diff FROM ".$wpdb->prefix."wpsa_affiliate_subscription_sales where status = 'pending' ";

    $rows_affiliate = $wpdb->get_results($sql_affiliate);

    if ($rows_affiliate) {

        $ids = '';

        foreach ($rows_affiliate as $row_affiliate) {

            if ( $row_affiliate->date_diff > $affiliate['refund_period']) {

                $ids .= $row_affiliate->id.',';

            }

        }



        $ids = substr($ids, 0, -1);

        $sql_update = "UPDATE " .$wpdb->prefix. "wpsa_affiliate_subscription_sales SET `status` = 'set_to_paid' WHERE id in ($ids) ";

        $sql_update = $wpdb->query($sql_update);

    }

}



//------------------------------------------------------------

//  TO HANDLE AFFILIATE REFERRALS

//------------------------------------------------------------

add_action('init', 'wpsa_affiliate_referral');

function wpsa_affiliate_referral() {

    global $wpdb;

    

    $wpsa_affiliate = get_option('wpsa_affiliate');

    $affiliate_variable = $wpsa_affiliate['affiliate_variable'];

    

    if ($_GET[$affiliate_variable]) {



        // check refrrer's usermname is valid

        $sql = "SELECT ID FROM ".$wpdb->base_prefix."users WHERE user_login = '".trim($_GET[$affiliate_variable])."'";

        $row = $wpdb->get_row( $sql );



        // if user name found in users table

        if ( $row ) {

            // set cookies

            $cookies_expiry = $wpsa_affiliate['cookies_expiry'];

            $cookies_expiry = $cookies_expiry*86400;

            //setcookie('wpsa-ref', $_GET[$affiliate_variable], time()+$cookies_expiry);//, "/", str_replace('http://www','',get_bloginfo('url')));

            setcookie('wpsa-ref', $_GET[$affiliate_variable], time()+$cookies_expiry, SITECOOKIEPATH);



            $landing_page = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

            $postid = url_to_postid( $landing_page );

            $ps_id = 0;

            $referred_for = '';



            $sql_ps = "SELECT product_id FROM ".$wpdb->base_prefix."wpsa_affiliate_product_commission WHERE page_id = $postid ";

            $row_ps = $wpdb->get_row( $sql_ps );



            if ( $row_ps ) {

                $ps_id = $row_ps->product_id;

                $referred_for = 'product';

            }

            else {

                $sql_ps = "SELECT subsc_id FROM ".$wpdb->base_prefix."wpsa_affiliate_subscription_commission WHERE page_id = $postid ";

                $row_ps = $wpdb->get_row( $sql_ps );



                if ( $row_ps ) {

                    $ps_id = $row_ps->subsc_id;

                    $referred_for = 'subscription';

                }

            }



            if ( $ps_id ) {

               $sql = "INSERT INTO " . $wpdb->prefix . "wpsa_affiliate_referrals

                    (`user_id`, `ps_id`, `ip_address`, `referred_for`, `referred_from`, `landing_page`, `date`)  VALUES

                    ( $row->ID, '".$ps_id."', '" .$_SERVER['REMOTE_ADDR']. "', '".$referred_for."', '" . $_SERVER['HTTP_REFERER'] . "', '" .$landing_page. "', now() )";

                $wpdb->query( $sql );

            }

        }

    }

}



//------------------------------------------------------------

//  TO HANDLE IPN DATA FOR MASS PAYMENT

//------------------------------------------------------------



add_action('init', 'wpsa_affiliate_masspay_ipn');



function wpsa_affiliate_masspay_ipn() {

    global $wpdb;

    if ($_POST['txn_type'] == 'masspay') {

        if ($_POST['payment_status'] == 'Completed') {

            ob_start("wpsa_affiliate_log");

            print_r($_POST);



            $cnt= 0 ;

            //to count total no. of masspay

            for ( $i = 1; $i<=250; $i++ ) {

                if ($_POST['receiver_email_'.$i]!='' ) {

                    $cnt++;

                }

                else break;

            }



            //$ids = '';

            for ( $i = 1; $i<=$cnt; $i++ ) {

                $sql_update_prod = " UPDATE " .$wpdb->prefix. "wpsa_affiliate_product_sales SET

                        `status` = 'paid' ,

                        `masspay_txn_id` = '".$_POST['masspay_txn_id_'.$i]."',

                        `masspay_payment_date` = '".$_POST['payment_date']."'

                        WHERE (`status` = 'set_to_paid' or `status` = 'sent_payment') and affiliate_uid = ".$_POST['unique_id_'.$i]."; ";

                $wpdb->query($sql_update_prod );



                 $sql_update_subsc = " UPDATE " .$wpdb->prefix. "wpsa_affiliate_subscription_sales SET

                        `status` = 'paid' ,

                        `masspay_txn_id` = '".$_POST['masspay_txn_id_'.$i]."',

                        `masspay_payment_date` = '".$_POST['payment_date']."'

                        WHERE (`status` = 'set_to_paid' or `status` = 'sent_payment') and affiliate_uid = ".$_POST['unique_id_'.$i]."; ";

                 $wpdb->query($sql_update_subsc );

            }

            ob_end_flush();

        }

    }



    else if ($_POST['payment_status'] == 'Refunded') {

        ob_start("wpsa_affiliate_log");

        print_r($_POST);



        if ( $_POST['option_selection2_1'] == 'affiliate_ref') $affiliate_ref = $_POST['option_name2_1'];

        else if ( $_POST['option_selection3_1'] == 'affiliate_ref') $affiliate_ref = $_POST['option_name3_1'];

        else $affiliate_ref = 0;

        

        $sql_update_prod = " UPDATE " .$wpdb->prefix. "wpsa_affiliate_product_sales SET

                `status` = 'refunded' ,

                `refund_txn_id` = '".$_POST['txn_id']."',

                `refund_date` = '".$_POST['payment_date']."'

                WHERE `txn_id` = '" .$_POST['parent_txn_id']. "' and `status` = 'pending' and affiliate_uid = '" .$affiliate_ref."' ";

        $wpdb->query($sql_update_prod );



         $sql_update_subsc = " UPDATE " .$wpdb->prefix. "wpsa_affiliate_subscription_sales SET

                `status` = 'refunded' ,

                `refund_txn_id` = '".$_POST['txn_id']."',

                `refund_date` = '".$_POST['payment_date']."'

                WHERE `txn_id` = '" .$_POST['parent_txn_id']. "' and `status` = 'pending' and affiliate_uid = '".$affiliate_ref."' ";

         $wpdb->query($sql_update_subsc );



        ob_end_flush();

        

    } 

}



//------------------------------------------------------------

//  LOG MASSPAY IPN LOG ON TXT FILE

//------------------------------------------------------------

/*

 * use this function to log the data as and when needed

 */

function wpsa_affiliate_log($str ) {

    file_put_contents(WPSA_AFFILIATE_PATH."masspay-log.txt", "\n\n", FILE_APPEND );

    file_put_contents(WPSA_AFFILIATE_PATH."masspay-log.txt", "---".date("F j, Y, g:i a" )."---\n", FILE_APPEND );

    file_put_contents(WPSA_AFFILIATE_PATH."masspay-log.txt", $str, FILE_APPEND );

}



add_shortcode('affiliate_area', 'wpsa_affiliate_users_affiliate_area');

function wpsa_affiliate_users_affiliate_area($param) {

    global $wpdb, $user_ID;



    if ( !$user_ID ) {

        return '<p><a href="'.wp_login_url().'">Login</a> to see your affiliate area.</p> <p>';

    }

    $wpsa_affiliate = get_option('wpsa_affiliate');



    if ( $wpsa_affiliate['affiliate_area_prod'] ) {

    $output = '<h2>Product</h2>

        <div>

            Get your affiliate link for product:

            <select name="wpsa_aff_product" id="wpsa_aff_product">

                <option value="">Select Product</option>';

                

    $sql = "SELECT id, name FROM ".$wpdb->prefix."wpsa_product_details ";

    $rows = $wpdb->get_results($sql);



    foreach($rows as $row) {

        $output .= '<option value="'.$row->id.'">'.$row->name.'</option>';

    }

     $output .= '</select>

            <p id="wpsa_aff_product_link"></p>

        </div>

        <h4>Stats</h4>

        <table align="center" class="wpaff">

        <thead>

            <tr>

                <th>#</th>

                <th>Product Name</th>

                <th>My Sales</th>

                <th>My Refunds</th>

                <th>Unique Referrals</th>

                <th>Total Earned</th>

            </tr>

        </thead>';

   

    foreach($rows as $k => $row) {

        $sql_sales = "SELECT  sum(pprice) as amt, count(id) as sales FROM " .$wpdb->prefix. "wpsa_affiliate_product_sales where pid = $row->id and affiliate_uid = $user_ID ";

        $row_sales = $wpdb->get_row($sql_sales);

        $sales = 0;

        if($row_sales->amt)  $sales = $row_sales->amt;

        

        $sql_refund = "SELECT sum(commission) as refund FROM " .$wpdb->prefix. "wpsa_affiliate_product_sales where pid = $row->id and affiliate_uid = $user_ID and status = 'refunded' ";

        $row_refund = $wpdb->get_row($sql_refund);

        $refund = 0;

        if($row_refund->refund)  $refund = $row_refund->refund;



        $sql_amt = "SELECT sum(commission) as amt FROM " .$wpdb->prefix. "wpsa_affiliate_product_sales where pid = $row->id and affiliate_uid = $user_ID ";

        $row_amt = $wpdb->get_row($sql_amt);

        $total_amt = 0;

        if ( $row_amt->amt ) $total_amt = $row_amt->amt;

        

        $sql_referral = "SELECT  count(id) as referral FROM " .$wpdb->prefix. "wpsa_affiliate_referrals where ps_id = $row->id and referred_for = 'product' and user_id = $user_ID ";

        $row_referral = $wpdb->get_row($sql_referral);



        $output .= '

        <tr class="d0">

            <td>'.($k+1).'</td>

            <td>'.$row->name.'</td>

            <td>$'.$sales.'</td>

            <td>$'.$refund.'</td>

            <td>'.$row_referral->referral.'</td>

            <td>$'.$total_amt.'</td>

        </tr>';

    }



    $output .= '</table>';

    }

    if ( $wpsa_affiliate['affiliate_area_subsc'] ) {

        $output .= '<h2>Subscriptions</h2>

        <div>

            Get your affiliate link for subscription:

            <select name="wpsa_aff_subscription" id="wpsa_aff_subscription">

                <option value="">Select Subscription</option>';



    $sql = "SELECT id, name FROM ".$wpdb->prefix."wpsa_subscriptions ";

    $rows = $wpdb->get_results($sql);



    foreach($rows as $row) {

        $output .= '<option value="'.$row->id.'">'.$row->name.'</option>';

    }



    $output .= '</select>

            <p id="wpsa_aff_subscription_link"></p>

        </div>

        <h4>Stats</h4>

        <table class="wpaff">

        <thead>

            <tr class="tablemenu">

                <th>#</th>

                <th>Subscription Name</th>

                <th>My Sales</th>

                <th>My Refunds</th>

                <th>Unique Referrals</th>

                <th>Total Earned</th>

            </tr>

        </thead>';

            

    //$sql = "SELECT a.subsc_id, sum(a.sell) as sales, count(a.id) as referral, b.name FROM " .$wpdb->prefix. "wpsa_affiliate_subscription_sales a, " .$wpdb->prefix. "wpsa_subscriptions b where a.subsc_id = b.id and a.affiliate_uid = $user_ID group by a.subsc_id";

    //$rows = $wpdb->get_results($sql);

    

    foreach($rows as $row) {

        $sql_sales = "SELECT  sum(sell) as amt, count(id) as sales FROM " .$wpdb->prefix. "wpsa_affiliate_subscription_sales where subsc_id = $row->id and affiliate_uid = $user_ID ";

        $row_sales = $wpdb->get_row($sql_sales);

        $sales = 0;

        if ($row_sales->amt ) $sales = $row_sales->amt;



        $sql_refund = "SELECT sum(commission) as refund FROM " .$wpdb->prefix. "wpsa_affiliate_subscription_sales where subsc_id = $row->id and affiliate_uid = $user_ID and status = 'refunded' ";

        $row_refund = $wpdb->get_row($sql_refund);

        $refund = 0;

        if ( $row_refund->refund ) $refund = $row_refund->refund;



        $sql_referral = "SELECT  count(id) as referral FROM " .$wpdb->prefix. "wpsa_affiliate_referrals where ps_id = $row->id and referred_for = 'subscription' and user_id = $user_ID ";

        $row_referral = $wpdb->get_row($sql_referral);



        $sql_amt = "SELECT sum(commission) as amt FROM " .$wpdb->prefix. "wpsa_affiliate_product_sales where pid = $row->id and affiliate_uid = $user_ID ";

        $row_amt = $wpdb->get_row($sql_amt);

        $total_amt = 0;

        if ( $row_amt->amt ) $total_amt = $row_amt->amt;



        $output .= '<tr class="d1">

            <td>'.$k.'</td>

            <td>'.$row->name.'</td>

            <td>$'.$sales.'</td>

            <td>$'.$refund.'</td>

            <td>'.$row_referral->referral.'</td>

            <td>$'.$total_amt.'</td>

        </tr>';

    }

    $output .= '</table>';

    }

    return $output;

}



add_action('wp_ajax_nopriv_wpsa_affiliate_get_afflink', 'wpsa_affiliate_get_afflink');

add_action('wp_ajax_wpsa_affiliate_get_afflink', 'wpsa_affiliate_get_afflink');



/**

 * @global <type> $wpdb

 */

function wpsa_affiliate_get_afflink() {

    global $wpdb, $user_ID;

    $wpsa_affiliate = get_option('wpsa_affiliate');



    if ($_POST['pid'])

        $sql = "SELECT  page_id FROM ".$wpdb->prefix."wpsa_affiliate_product_commission where product_id = ".$_POST['pid'];

    else

        $sql = "SELECT  page_id FROM ".$wpdb->prefix."wpsa_affiliate_subscription_commission where subsc_id = ".$_POST['sid'];

    $row = $wpdb->get_row($sql);



    if ( $row ) {

        if ( $row->page_id > 0)

            $product_page = get_permalink($row->page_id);

        else

            $product_page = get_bloginfo ('url');

        if ( strpos( $product_page, '?' ) == NULL)

                $aff = '?';

        else

            $aff = '&';

        

        echo 'Affiliate link is: ' . $product_page . $aff . $wpsa_affiliate['affiliate_variable'].'='.  get_userdata($user_ID)->user_login;

    }

    else 

        echo 'No Affiliate link is assigned to this product.';

    die();

}



/*

 * to redirect login user to url given in admin setting of wpsa-affiliate

 */

add_filter('login_redirect','wpsa_affiliate_login_redirect', 1, 3);



/**

 * redirect users of role subscriber, to affiliate stats page

 * @param <type> $redirect_to

 * @param <type> $request_redirect_to

 * @param <type> $user

 * @return <type>

 */

function wpsa_affiliate_login_redirect($redirect_to, $request_redirect_to, $user) {

    $wpsa_user = get_usermeta($user->ID, 'wpsa_user');



    if($user->caps['subscriber'] && !empty($wpsa_user)) {

        $wpsa_affiliate = get_option('wpsa_affiliate');

        if ( $wpsa_affiliate['login_redirect'] != '')

            return $wpsa_affiliate['login_redirect'] ;

        else return  $redirect_to;

    }

    else {

        return  $redirect_to;

    }

}

?>