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

class WP_SA_PRODUCT_SAES {    
    function log() {
        global $wpdb;        
        $obj = new WP_SA_PRODUCT_SAES;
        $table_name = $wpdb->prefix . "wpsa_product_transaction";
        $path=get_bloginfo('siteurl');
        $path.='/wp-admin/admin.php?page=wp-sa-transaction-log';
        
        if (isset($_GET['email'])) {
            if ($_GET['wp_sa_action'] === 'edit') {
                $obj->edit();
                return;
            }
            else {
                $obj->view();
                return;
            }
        }
       
        if (isset($_GET['action']) && $_GET['action'] === 'add_customer') {
            $obj->add();
            return;
        }

        $search = $_REQUEST['searchtext'];

        if($_POST['submit']=='Search') {
            if($_POST['searchtext']=='') {
                echo "<div class=updated below-h2><p>Please Enter search field</p></div>";
            }
            $qry="SELECT * FROM $table_name WHERE product_id= '$search' OR product_name LIKE '%$search%' OR customer_email like '%$search'OR customer_ip like '%$search%'OR paypal_transaction_id like '%$search%' OR status like '%$search%' OR referal_url  like '%$search%'";
        }
        else {
            $qry = "SELECT customer_email, SUM(`price`) as cost FROM $table_name GROUP BY `customer_email` ORDER BY customer_email DESC ";
        }

        $pagenum = isset($_GET['cpage']) ? $_GET['cpage'] : 1;
        $per_page = 20;
        $count = count($wpdb->get_results($qry, ARRAY_A));
        $page_links = paginate_links( array(
                'base' => add_query_arg( 'cpage', '%#%' ),
                'format' => '',
                'prev_text' => __('&laquo;'),
                'next_text' => __('&raquo;'),
                'total' => ceil($count / $per_page),
                'current' => $pagenum
        ));
        $rt_post_offset = ($pagenum-1) * $per_page;
        $qry .= " LIMIT {$rt_post_offset}, {$per_page}";
        $results = $wpdb->get_results($qry);
        ?>
    <div class="wrap">
        <h2>Product Sales</h2>
        <a href="?page=wp-sa-transaction-log&action=add_customer" title="Add Customer">Add Customer</a>
        <form action="<?php echo $path; ?>" method="post" name="searchform" >
            <div align="left" >
                <p class="submit">
                    <input type="text" name="searchtext" id="rt_searchbox" value="Enter a keyword to search..." style="width:200px;" onfocus="if(this.value == 'Enter a keyword to search...') this.value='';" onblur="if(this.value == '') this.value='Enter a keyword to search...' ;"/>
                    <input type="submit" name="submit" value="<?php _e('Search'); ?>" />
                </p>
            </div>
        </form>
        <table class="widefat post fixed" style="width: 45%">
            <thead>
                <!--Edited the width of fields. Added 6% to Product ID & Name and reducted 1% from the rest 6 fields : Nemi -->
                <tr class="tablemenu">
                    <th width="1%"></th>
                    <th width="73%">Customer Email ID</th>
                    <th width="26%">Total Cost</th>
                    <th width="26%">Edit</th>
                    <!--<th width="26%">Delete</th>-->
                </tr>
            </thead>
            <?php
            if(empty ($results)) {
                echo '<tr><td colspan="7">There are no sales log. <a href="'.get_option('siteurl').'/wp-admin/admin.php?page=wp-sa-salesautomator">Click here</a> to Manage Products</td></tr></tbody></table></div>';
                return ;
            }
            $k = 1;
            foreach ($results as $result) {
                if($k % 2) { $class = 'alternate'; }
                else { $class = 'unread'; }
            ?>
            <tr class="<?php echo $class; ?>">
                <td><?php echo $k ;?></td>
                <td><a href="<?php echo get_bloginfo('siteurl'); ?>/wp-admin/admin.php?page=wp-sa-transaction-log&email=<?php echo $result->customer_email ;?>&wp_sa_action=view"><?php echo $result->customer_email ;?></a></td>
                <td><?php echo $result->cost ;?></td>
                <td><a href="<?php echo get_bloginfo('siteurl'); ?>/wp-admin/admin.php?page=wp-sa-transaction-log&email=<?php echo $result->customer_email ;?>&wp_sa_action=edit"><img title="Edit!" alt="Edit!" src="<?php echo WP_PLUGIN_URL; ?>/wp-salesautomator/img/icons/Edit.png" width="16px"/></a></td>
            </tr>
            <?php $k++;
            }
            ?>
        </table>
        <?php if($count>$per_page) { echo $page_links; } ?>
    </div>
    <?php
    }

    function edit() {
        global $wpdb;
        $edit_table = $wpdb->prefix . "wpsa_product_transaction";
        $email = $_GET['email'];

        ?><h2>WPSA Product Sales Log - Edit</h2><?php

        if (isset($_POST['edit_c_submit'])) {
            $edit_email = $_POST['email'];
            $ids = $_POST['id'];
            if ($email != $edit_email) {
                $update_query = "UPDATE {$edit_table} SET customer_email='{$edit_email}' WHERE customer_email='{$email}'";
                $wpdb->query($update_query);
                $email = $edit_email;
            }
            foreach ($ids as $id) {
                $update_query = '';
                $update_query = "UPDATE {$edit_table} SET paypal_transaction_id='{$_POST[$id.'_tran_id']}', status='{$_POST[$id.'_status']}' WHERE id={$id}";
                $wpdb->query($update_query);
            }
            ?><h5>Details Updated</h5><?php
        }

        $edit_sql = "SELECT * FROM {$edit_table} WHERE customer_email='{$email}' ORDER BY id DESC";
        $edit_results = $wpdb->get_results($edit_sql);

        if (is_array($edit_results)) {
            ?>
                <form method="post" enctype="multipart/form-data" action="<?php echo "?page=wp-sa-transaction-log&email={$email}&wp_sa_action=edit"; ?>" enctype="multipart/form-data">
                    <table class="form-table" border="0">
                        <tr>
                            <td class="label" width="14%"><label for="email">Email</label></td>
                            <td class="field" width="50%"><input id ="email" name="email" type="text" value="<?php echo $email;?>" /></td>
                        </tr>
                        <tr>
                            <td colspan="2"><hr /></td>
                        </tr>
                        <?php
                    foreach ($edit_results as $edit_result) {
                    ?>
                        <tr>
                            <td colspan="2"><input type="checkbox" name="id[]" value="<?php echo $edit_result->id;?>"/></td>
                        </tr>
                        <tr>
                            <td class="label" width="14%"><label>Bought on:</label></td>
                            <td class="field" width="50%"><?php echo $edit_result->time;?></td>
                        </tr>
                        <tr>
                            <td class="label" width="14%"><label>Product Name:</label></td>
                            <td class="field" width="50%"><?php echo $edit_result->product_name;?></td>
                        </tr>
                        <tr>
                            <td class="label" width="14%"><label for="<?php echo $edit_result->id;?>_tran_id">PayPal Transaction Id</label></td>
                            <td class="field" width="50%"><input id ="<?php echo $edit_result->id;?>_tran_id" name="<?php echo $edit_result->id;?>_tran_id" type="text" value="<?php echo $edit_result->paypal_transaction_id;?>" /></td>
                        </tr>
                        <tr>
                            <td class="label" width="14%"><label for="status">Status</label></td>
                            <td class="field" width="50%">
                                <select name="<?php echo $edit_result->id;?>_status">
                                    <option value="active" <?php if ($edit_result->status === 'active') { echo "SELECTED"; } ?>>Active</option>
                                    <option value="inactive" <?php if ($edit_result->status === 'inactive') { echo "SELECTED"; }?>>Inactive</option>
                                </select>
                            </td>
                        </tr>
                        <tr>
                            <td></td>
                            <td>
                                <input type="submit" value="Save" name="edit_c_submit"/>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2"><hr /></td>
                        </tr>
                        <?php } ?>
                    </table>
                </form>
            <?php
        }
    }
    
    function add() {
        global $wpdb;
        
        ?><h2>WPSA Product Sales Log - Add</h2><?php

        if (isset($_POST['add_c_submit'])) {
            $email = $_POST['email'];
            $products = $_POST['products'];
            $email_links = $_POST['email_links'];

            if (!empty($email) && $products) {
                $update_table = $wpdb->prefix . "wpsa_product_transaction";
                $update_query = "INSERT INTO {$update_table} (`product_id` ,`product_name` ,`customer_email` , `status` , `time`, `price`) VALUES ";
                $product_ids = array();

                foreach ($products as $product) {
                    $product_details = explode('_|_', $product);
                    $pro_id = intval($product_details[0]);
                    $product_ids[] = $pro_id;
                    $pro_name = $product_details[1];
                    $pro_price = $product_details[2];
                    $update_query .= "({$pro_id}, '{$pro_name}', '{$email}', 'active', NOW(), '{$pro_price}'), ";
                }

                $update_query = substr($update_query, 0, -2);
                $wpdb->query($update_query);

                if ($email_links) {
                    $product_ids = implode(',',$product_ids);
                    $this->wpsa_send_download_link( $product_ids, $_POST);
                }
                ?><h5>Customer added successfully</h5><?php
            }

            else { echo 'Please enter an email.';}
        }
        ?>
        <form name="product_form" id="product_form" class="omlist" method="post" enctype="multipart/form-data" action="<?php echo "?page=wp-sa-transaction-log&action=add_customer"; ?>" enctype="multipart/form-data">
            <table class="form-table" border="0">

                <tr>
                    <td class="label" width="14%"><label for="first_name">First Name</label></td>
                    <td class="field" width="50%"><input id ="first_name" name="first_name" type="text" value="" /></td>
                </tr>
                <tr>
                    <td class="label" width="14%"><label for="last_name">Last Name</label></td>
                    <td class="field" width="50%"><input id ="last_name" name="last_name" type="text" value="" /></td>
                </tr>
                <tr>
                    <td class="label" width="14%"><label for="email">Email</label></td>
                    <td class="field" width="50%"><input id ="email" name="email" type="text" value="" /></td>
                </tr>
                <tr>
                    <td class="label"><label for="products">Products</label></td>
                    <td class="field">
                    <?php
                $prod_table = $wpdb->prefix."wpsa_product_details";
                $prod_qry = "SELECT id, name, price FROM {$prod_table}";
                $prod_results = $wpdb->get_results($prod_qry);
                if (is_array($prod_results)) {
                    foreach ($prod_results as $prod_result) {
                ?>
                            <input type="checkbox" name="products[]" value="<?php echo $prod_result->id.'_|_'.$prod_result->name.'_|_'.$prod_result->price;?>"/> <?php echo $prod_result->name;?><br/>
                    <?php
                    }
                }
                ?>
                    </td>
                </tr>
                <tr>
                    <td class="label"><label for="email_links"> Send Email With Download Links</label></td>
                    <td class="field"><input id="email_links" name="email_links" type="checkbox" value="yes"/></td>
                </tr>
            </table>
            <div class="submit"><input type="submit" value="Add" name="add_c_submit"/></div>
        </form>
        <?php
    }

    function view() {
        global $wpdb;
        $table_name = $wpdb->prefix . "wpsa_product_transaction";
        $email = $_GET['email'];
        $pagenum = isset($_GET['cpage']) ? $_GET['cpage'] : 1;
        $per_page = 20;
        $qry = "SELECT * FROM $table_name WHERE customer_email='{$email}'";
        $count = count($wpdb->get_results($qry, ARRAY_A));
        $page_links = paginate_links( array(
                'base' => add_query_arg( 'cpage', '%#%' ),
                'format' => '',
                'prev_text' => __('&laquo;'),
                'next_text' => __('&raquo;'),
                'total' => ceil($count / $per_page),
                'current' => $pagenum
        ));
        $rt_post_offset = ($pagenum-1) * $per_page;
        $qry .= " LIMIT {$rt_post_offset}, {$per_page}";
        $results = $wpdb->get_results($qry);
        ?>
        <div class="wrap">
            <h2>WPSA Product Sales Log</h2>
            Transaction Details of <strong><?php echo $email;?></strong>.
            <table class="widefat post fixed" style="margin-top: 23px;">
                <thead>
                    <tr class="tablemenu">
                        <th width="12%">Product ID & Name</th>
                        <th width="17%">Paypal Transaction ID</th>
                        <th width="12%">Price</th>
                        <th width="8%">Time</th>
                        <th width="10%">Customer IP</th>
                        <th width="25%">Referal URL</th>
                        <th width="5%">Status</th>
                        <th width="8%"></th>
                    </tr>
                </thead>
               
                <?php
                $k = 0;
                foreach ($results as $result) {
                    if($k % 2) { $class = 'alternate'; }
                    else { $class = 'unread'; }
                    ?>
                    <tr class="<?php echo $class; ?>">
                        <td><a href="<?php echo get_bloginfo('siteurl'); ?>/wp-admin/admin.php?page=wp-products&wpu=view&pid=<?php echo $result->product_id ;?>"><?php echo $result->product_id.' '.$result->product_name;?></a></td>
                        <td><?php echo $result->paypal_transaction_id;?></td>
                        <td><?php echo $result->price ;?></td>
                        <td><?php echo $result->time ;?></td>
                        <td><?php echo $result->customer_ip ;?></td>
                        <td><?php echo $result->referal_url ;?></td>
                        <td><?php echo $result->status ;?></td>
                        <td>
                            <?php
                        if($result->status == 'active') {
                            ?><input type="submit" value="De-activate" onclick="rt_change_status('rt_deact_transaction',<?php echo $result->id; ?>)"><?php
                        }
                        else {
                            ?><input type="submit" value="Re-activate" onclick="rt_change_status('rt_react_transaction',<?php echo $result->id; ?>)"><?php
                        }
                        ?>
                        </td>
                    </tr>
                    <?php
                    $k++;
                }
                ?>
            </table>
            <?php if($count>$per_page) { echo $page_links; } ?>
        </div>
        <?php
        return;
    }


/********************************************************************
 * To send mail of "product download link"
 ********************************************************************/
function wpsa_send_download_link( $product_ids, $post ) {
    global $wpdb;
    
    $email_to = trim($post['email']);
    $rt_option = get_option('rt_option_products');

    $sql = "SELECT id, 	name, 	description, 	price, 	file_name,  message_template FROM ".$wpdb->prefix."wpsa_product_details WHERE id IN ($product_ids)";
    $results = $wpdb->get_results($sql);

    foreach ($results as $result) {
        $file_temp_links = '';
        
        $file_temp_links = create_temp_file_to_download($result->id, '', '', '').'';

        //end
        $rt_message_template = $result->message_template;
        $rt_option = unserialize($rt_message_template);

        $subject = $rt_option['subject'];

        //$message = '<html><head><title></title></head><body>';
        $message = $rt_option['msg'];

        $message = str_replace('%first_name%', $post['first_name'], $message);
        $message = str_replace('%last_name%', $post['last_name'], $message);

        $message = str_replace('%user_email%', $email_to, $message);
        $message = str_replace('%blogname%', get_option('blogname'), $message);

        $message = str_replace('%product_name%', $result->name, $message);
        $message = str_replace('%description%', $result->description, $message);
        $message = str_replace('%price%', $result->price, $message);

        $message = str_replace('%download_link%', $file_temp_links , $message);
        
        $siteurl = get_option('siteurl');
        $message = str_replace('%siteurl%', $siteurl, $message);

        
        $headers  = 'MIME-Version: 1.0' . "\r\n";
        $headers .= 'Content-type: text/plain; charset=iso-8859-1' . "\r\n";
        $headers .= 'From: '.$rt_option['fromname'].' <'.$rt_option['from'].'>' . "\r\n";

        wp_mail($email_to, $subject, $message, $headers);

    }
}

}
?>