<?php
/*
Copyright 2012 Neil Harvey - wordpressLAB
*/

add_shortcode('thank_you_page', 'rt_salesautomator_thank_you_page');
/*subscription_form needs help file*/
function rt_salesautomator_thank_you_page($atts) {
    $output = '<div id="wpsa-load-result">';
    if (isset($_COOKIE['check_time_wpsa'])) {
        $output .= '<div id="wpsa-checking">Checking ... <br>Please wait while we verify your payment. If you are not updated within 5 minutes please contact us.</div>';
        $output .= '<div id="result-wpsa"></div>';
        wpsa_insert_js_in_footer();
    }
    else {
        $output .= 'No results found!';
    }
    $output .= '</div>';
    return $output;
}

function wpsa_insert_js_in_footer() {
    add_action('wp_footer', 'wpsa_js_for_validating');
    return;
}

function wpsa_js_for_validating() {
    $output .= '<script type="text/javascript">
                    function wpsa_validate() {
                        var wpsa_validation_post = "wpsa_ajax_action=wpsa_validate";
                        jQuery.post("'.get_bloginfo('url').'/", wpsa_validation_post, function(code_returned_data){
                            eval(code_returned_data);
                        });
                        return false;
                    }
                    var keep_checking = setInterval("wpsa_validate()", 3000);
                </script>';
    echo $output;
}

if ( !empty($_REQUEST['wpsa_ajax_action']) &&  $_REQUEST['wpsa_ajax_action'] === 'wpsa_validate') {
        add_action('init', 'wpsa_validate_link');
}

function wpsa_validate_link() {
    global $wpdb;
    $output = '';
    $type = $_COOKIE['check_type_wpsa'];
    $time = $_COOKIE['check_time_wpsa'];
    if ($type === 'sub') {
        $table_name = $wpdb->prefix . "wpsa_subscription_transaction";
        $sql = "SELECT payer_email, subscriber_id, txn_id FROM {$table_name} WHERE check_time='{$time}'";
        $result = $wpdb->get_row($sql);
        if ($result) {
			/* @todo
			 * We might need to write thank you message template for subscription too.
			 * we need to ask client
			 */
            $output = '<div align="center"><a class="register_link" href="'.wp_login_url().'?action=register&email_id='.$result->payer_email.'&subscr_id='.$result->subscriber_id.'&txn_id='.$result->txn_id.'"><img src="'.get_settings('siteurl').'/wp-content/plugins/'.dirname(dirname(plugin_basename(__FILE__))).'/img/register.gif" alt="Register Here!" border="1" title="Register Here!"/></a></div><p><br>';
        }
    }
    else if ($type === 'pro') {
        $table_name = $wpdb->prefix."wpsa_product_transaction";
        $sql = "SELECT product_id, paypal_transaction_id FROM {$table_name} WHERE check_time='{$time}'";
        $results = $wpdb->get_results($sql);
        if ($results) {
            $output = 'Purchases:<br />';
            
            foreach ($results as $result) {
                $sql_coupon = "SELECT gross_sell, discount FROM ".$wpdb->prefix."wpsa_coupon_log WHERE txn_id = '".$result->paypal_transaction_id."'";
                $row_coupon = $wpdb->get_row($sql_coupon);
                
                $output .= create_temp_file_to_download($result->product_id, TRUE, $row_coupon->gross_sell, $row_coupon->discount).'';
            }
        }
    }
    if (!empty($output)) {
        $ResCode = $output;
        $ResCode = str_replace(Array("\n","\r") , Array("\\n","\\r"),addslashes($ResCode));
        echo "jQuery('div#wpsa-checking').css('display', 'none');";
        echo "jQuery('div#result-wpsa').html('".$ResCode."');";
        echo "clearInterval(keep_checking);";
    }
    exit();
}

function create_temp_file_to_download($product_id, $is_ty_page=FALSE, $wpsa_gross_sell='', $wpsa_discount='') {
    global $wpdb;

    $sql = "SELECT * FROM ".$wpdb->prefix."wpsa_product_details WHERE id = {$product_id} LIMIT 1";
    $row = $wpdb->get_row($sql);
   // error_log($sql);

    $files = $row->file_name;
    $files = explode(',',$files);
    $temp_names = array();
    foreach ($files as $file) {
        $file_ext = strtolower(substr(strrchr($file,"."),1));
        $temp_name = md5(microtime()).'.'.$file_ext;

        $temp_names[] = $temp_name;
        rt_update_download_table($temp_name, $file);
    }
    
    //Changed By NEMI
    if ($is_ty_page) {
        $table_namety = $wpdb->prefix."wpsa_product_transaction";
        $time = $_COOKIE['check_time_wpsa'];
        $product_transaction_row = $wpdb->get_row("SELECT * FROM {$table_namety} WHERE check_time='{$time}'");
        $rt_message_template = $row->message_template;
        $rt_message_template = unserialize($rt_message_template);
        $message = $rt_message_template['ty_msg'];
        $message = str_replace('%user_email%', $product_transaction_row->customer_email, $message);
        $message = str_replace('%first_name%', $product_transaction_row->customer_fname, $message);
        $message = str_replace('%last_name%', $product_transaction_row->customer_lname, $message);
        $message = str_replace('%blogname%', get_option('blogname'), $message);
        $message = str_replace('%product_name%', $row->name, $message);
        $message = str_replace('%description%', $row->description, $message);
        $message = str_replace('%price%', $row->price, $message);
        $reglink='<a class="register_link" href="' .wp_login_url(). '?action=register&email_id='.$product_transaction_row->customer_email.'&txn_id='.$product_transaction_row->paypal_transaction_id.'">Register</a> here!';
        $file_temp_links = '';
        $file_i = 0;
        foreach ($temp_names as $temp_name) {
//            $file_temp_links .= '<a href="'.WP_SA_PLUGIN_URL . '/php/wp-sa-download.php?key='. $temp_name.'">'.$files[$file_i].'</a><br />';
            $file_temp_links .= '<a href="'. get_bloginfo('url') . '/?wpsa_download=1&wpsa_key='. $temp_name.'">'.$files[$file_i].'</a><br />';
            $file_i++;
        }
        $message = str_replace('%download_link%', $file_temp_links , $message);

        $siteurl = get_option('siteurl');
        $message = str_replace('%siteurl%', $siteurl, $message);
        $message = str_replace('%register_link%',$reglink,$message);
        $file_link = $message.'';
    }
    else {
        $file_link = '';
        $file_ie = 0;
        foreach ($temp_names as $temp_name) {
            $file_link .= $files[$file_ie].': '.get_bloginfo('url') . '/?wpsa_download=1&wpsa_key='. $temp_name. "\r\n";
            $file_ie++;
        }
    }
    if($wpsa_discount!='')
        $file_link .= '';
    return ($file_link). "\r\n";
}

function rt_update_download_table($temp_name, $file_name) {
    global $wpdb;

    $now = date("Y-m-d G:i:s");
    $count = 0;
    $ip_addr = '';

    $sql = "INSERT INTO ".$wpdb->prefix."wpsa_download_link ( id, `key`, name, count, expire, ip_addr ) ";
    $sql .= " VALUES ( '', '".$temp_name."', '". $file_name ."', ". $count.", '". $now ."', '". $ip_addr ."') ";
    $wpdb->query($sql);
}
?>