<?php 

function wpsa_affiliate_options_html() {

    global $affiliate_handler;

    ?>

    <div class="wrap">

        <?php $icon_url = plugins_url('images/plugin-menu-icon32.png', __FILE__); ?>

        <div id="icon-wpsa_affiliate" class="icon32"><img src="<?php echo $icon_url; ?>"/></div>

        <h2><?php _e('WPSA Affiliate');?></h2>

        

<script type="text/javascript">

//SYNTAX: ddtabmenu.definemenu("tab_menu_id", integer OR "auto")

ddtabmenu.definemenu("ddtabs1", 0) //initialize Tab Menu #4 with 3rd tab selected

</script>

<p>

<div id="ddtabs1" class="ddcolortabs">

<ul>

<li><a href="#" rel="ct1"><span>Products</span></a></li>

<li><a href="#" rel="ct2"><span>Commissions</span></a></li>

<li><a href="#" rel="ct3"><span>Affiliate Earnings</span></a></li>

<li><a href="#" rel="ct4"><span>Settings</span></a></li>

</ul>

</div>

<div class="ddcolortabsline">&nbsp;</div>



<DIV class="tabcontainer">



<div id="ct1" class="tabcontent">

<a href="?page=<?php echo $affiliate_handler;?>&action=list_products"><?php _e('Active Products');?></a> &nbsp; | &nbsp; <a href="?page=<?php echo $affiliate_handler;?>&action=add_products"><?php _e('Add Product');?></a> &nbsp; | &nbsp; <a href="?page=<?php echo $affiliate_handler;?>&action=list_subsc"><?php _e('Active Subscriptions');?></a> &nbsp; | &nbsp; <a href="?page=<?php echo $affiliate_handler;?>&action=add_subsc"><?php _e('Add Subscription');?></a>

</div>



<div id="ct2" class="tabcontent">

<a href="?page=<?php echo $affiliate_handler;?>&action=payment&type=pending"><?php _e('Pending');?></a> &nbsp; | &nbsp; <a href="?page=<?php echo $affiliate_handler;?>&action=payment&type=set_to_paid"><?php _e('Set to Paid');?></a> &nbsp; | &nbsp; <a href="?page=<?php echo $affiliate_handler;?>&action=mass_payment"><?php _e('Pay Commissions');?></a> &nbsp; | &nbsp; <a href="?page=<?php echo $affiliate_handler;?>&action=payment&type=sent_payment"><?php _e('Masspay Sent');?></a> &nbsp; | &nbsp; <a href="?page=<?php echo $affiliate_handler;?>&action=payment&type=paid"><?php _e('Paid');?></a> &nbsp; | &nbsp; <a href="?page=<?php echo $affiliate_handler;?>&action=payment&type=refunded"><?php _e('Cancelled');?></a>

</div>



<div id="ct3" class="tabcontent">

<a href="?page=<?php echo $affiliate_handler;?>&action=users_earning_product"><?php _e('Products');?></a> &nbsp; | &nbsp; <a href="?page=<?php echo $affiliate_handler;?>&action=users_earning_subscription"><?php _e('Subscriptions');?></a>

</div>



<div id="ct4" class="tabcontent">

<a href="?page=<?php echo $affiliate_handler;?>&action=setting" ><?php _e('Settings');?></a> &nbsp; | &nbsp; <a href="?page=<?php echo $affiliate_handler;?>&action=reg-setting" ><?php _e('Custom Registration');?></a>

</div>



</DIV>

    <div class="clear"></div>



    <div style="margin-bottom: 40px"></div>

        <?php

        switch($_GET['action']) {

            case 'list_products':

                wpsa_affiliate_product_list();

                break;

            case 'add_products':

            case 'edit_products':

                wpsa_affiliate_product_add();

                break;

            

            case 'delete_products':

                wpsa_affiliate_product_delete();

                break;



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

            case 'list_subsc':

                wpsa_affiliate_subsc_list();

                break;

            case 'add_subsc':

            case 'edit_subsc':

                wpsa_affiliate_subsc_add();

                break;



            case 'delete_subsc':

                wpsa_affiliate_subsc_delete();

                break;

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

            case 'users_earning_product':

                wpsa_users_earning_product();

                break;



            case 'list_aff_log_product':

                wpsa_list_aff_log_product();

                break;



            case 'users_earning_subscription':

                wpsa_users_earning_subscription();

                break;



            case 'list_aff_log_subscription':

                wpsa_list_aff_log_subscription();

                break;

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

            case 'payment':

                wpsa_payment();

                break;



            case 'mass_payment':

                wpsa_mass_payment();

                break;

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

            case 'setting':

                wpsa_affiliate_setting();

                break;



            case 'reg-setting':

                wpsa_affiliate_reg_setting();

                break;



            default:

                wpsa_affiliate_product_list();

                break;

        }

        echo '</div>';

    }



    function wpsa_affiliate_product_list() {

        global $wpdb, $affiliate_handler;

        $sql = "SELECT a.*, b.name FROM ".$wpdb->prefix."wpsa_affiliate_product_commission as a, ".$wpdb->prefix."wpsa_product_details as b where a.product_id = b.id";

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

        

        if(isset($_GET['msg'])) {

            ?><div class="updated"><p><strong><?php _e($_GET['msg']);?></strong></p></div><?php

        }

        ?>

        <h3>Active Products</h3>

    <table class="widefat post fixed" id="messagelist">

        <thead>

            <tr class="tablemenu">

                <th width="5%">#</th>

                <th width="25%">Product</th>

                <th width="20%">Commission</th>

                <th width="15%">Edit</th>

                <th width="15%">Delete</th>

            </tr>

        </thead>

            <?php

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

                ?>

        <tr class="read">

            <td><?php _e($k+1);?></td>

            <td><?php echo $row->name;?></td>

            <td><?php echo $row->commission.'%';?></td>

            <td><a href="?page=<?php echo $affiliate_handler;?>&amp;action=edit_products&amp;pid=<?php echo $_GET['pid'];?>&amp;cid=<?php echo $row->id;?>">Edit</a></td>

            <td><a href="?page=<?php echo $affiliate_handler;?>&amp;action=delete_products&amp;pid=<?php echo $_GET['pid'];?>&amp;cid=<?php echo $row->id;?>">Delete</a></td>

        </tr>

                <?php

            }

            ?>

    </table>

        <p><div style="border-left: 3px solid black; padding-left: 3px;">

        <p><strong>Shortcode tags:</strong><br>

        </p>

        <ul style="margin-left: 10px;">

        <li>Enter this tag into a new page to allow affiliates to signup - <strong>[wpsa_affiliate_register]</strong></li>

        <li>Enter this tag into a new page for the affiliate area - <strong>[affiliate_area]</strong><br>

        </li></ul>

        </div></p>

     <?php

    }



    function wpsa_affiliate_product_add() {

        global $wpdb, $affiliate_handler;



        if($_POST) {

        $error_msg ='';



        if( $_GET['action'] == 'add_products' ) {

            $sql_product = "SELECT id FROM ".$wpdb->prefix."wpsa_affiliate_product_commission WHERE product_id = ".$_POST['product'];

            $rows_product = $wpdb->get_row($sql_product);



            if($rows_product){

                $error_msg .= 'Commission structure already exist. </br>';

            }

        }

        

        //check commission amt 

        if($_POST['commission'] > 100)

            $error_msg .= 'Commission percentage should be less than 100. </br>';



        //check affiliate link

        if($_POST['page_id'] == '')

            $error_msg .= 'Please select post/page.</br>';

        

        if($error_msg){

            echo '<div class="error"><p><strong>';

            _e($error_msg);

            echo '</strong></p></div>';

        }

        else{

            if( $_GET['action'] == 'add_products' ) {

                $sql = "INSERT INTO " . $wpdb->prefix . "wpsa_affiliate_product_commission ( `product_id`, `commission`, page_id) VALUES

                            ( '" . $_POST['product'] . "', '" . $_POST['commission'] . "', '" . $_POST['page_id'] . "' )";

                $wpdb->query($sql);

                $msg = 'Commission structure added successfully!';

            }

            else {

                   echo $sql = "UPDATE " . $wpdb->prefix . "wpsa_affiliate_product_commission SET

                        `product_id` = '" . $_POST['product'] . "',

                        `page_id` = '" . $_POST['page_id'] . "',

                        `commission` = '" . $_POST['commission'] . "'

                        WHERE id = ".$_GET['cid'];

                    $wpdb->query($sql);

                    $msg = 'Commission structure edited successfully!';

            }

        ?>

    <script type="text/javascript">

    location.href = '?page=<?php echo $affiliate_handler;?>&action=list_products&msg=<?php echo $msg;?>';

    </script>

    <?php

        }

    }

    if( $_GET['action'] == 'edit_products' ) {

        $sql = "SELECT * FROM ".$wpdb->prefix."wpsa_affiliate_product_commission WHERE id = ".$_GET['cid'];

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

    }

    ?>



<form name="affiliate_form" id="affiliate_form"  method="post" action="<?php echo "?page=".$affiliate_handler."&action=".$_GET['action']."&cid=".$_GET['cid']; ?>" >

<h3>Add/Edit Product</h3>

    <table class="form-table" border="0">

        <tr>

            <td class="label" width="20%"><label id="lproduct" for="product">Select Product</label><br/><small><i>(required)</i></small></td>

            <td class="field" width="30%">

                <select id="product_list" name="product" >

                    <?php

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

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

                    foreach ( $rows as $row ) {

                        ?><option value="<?php echo $row->id; ?>" <?php if($_POST && $_POST['product'] == $row->id) echo 'selected'; else if( $affiliate->product_id == $row->id) echo 'selected'; ?> ><?php echo $row->name . ' ( '. $row->price .')'; ?></option><?php

                    }

                    ?>

                </select>

            </td>

            <td class="status" width="50%"></td>

        </tr>

        

        <tr>

            <td class="label"><label id="lcommission" for="commission">Commission in %</label><br/><small><i>(required)</i></small></td>

            <td class="field"><input id="commission" name="commission" type="text" value="<?php if($_POST) echo $_POST['commission']; else echo $affiliate->commission?>" maxlength="10" /></td>

            <td class="status"></td>

        </tr>



        <tr>

            <td class="label"><label id="lpage_id" for="page_id">Post/Page</label><br/><small><i>(required)</i></small></td>

            <td class="field"><?php

            

            ?>

            <select id="page_id" name="page_id">

                <option value="0" class="mainop" <?php if($_POST && $_POST['page_id'] == 0) echo 'selected'; else if( $affiliate->page_id == 0) echo 'selected'; ?> >Home Page</option>

                <option value=""></option>

                <option value="" class="mainop" >Posts:</option>

            <?php

            $sql_post = "SELECT ID, post_title from ".$wpdb->base_prefix."posts where post_status = 'publish' and post_type = 'post' ";

            $rows_post = $wpdb->get_results($sql_post);

            foreach ($rows_post as $row_post) {

                ?><option value="<?php echo $row_post->ID; ?>" <?php if($_POST && $_POST['page_id'] == $row_post->ID) echo 'selected'; else if( $affiliate->page_id == $row_post->ID) echo 'selected'; ?> ><?php echo $row_post->post_title; ?></option><?php

            }



            echo '<option value=""></option><option value="" class="mainop" >Pages:</option>';



            $sql_page = "SELECT ID, post_title from ".$wpdb->base_prefix."posts where post_status = 'publish' and post_type = 'page'";

            $rows_page = $wpdb->get_results($sql_page);

            foreach ($rows_page as $row_page) {

                ?><option value="<?php echo $row_page->ID; ?>" <?php if($_POST && $_POST['page_id'] == $row_page->ID) echo 'selected'; else if( $affiliate->page_id == $row_page->ID) echo 'selected'; ?> ><?php echo $row_page->post_title; ?></option><?php

            }

            echo '</select>';

            ?></td>

            <td class="status"></td>

        </tr>

    </table>

    <div class="submit"><input type="submit" value="save" name="submit"/></div>

</form>

    <?php

    }



    function wpsa_affiliate_product_delete() {

        global $wpdb, $affiliate_handler;

        $sql = "DELETE FROM ".$wpdb->prefix."wpsa_affiliate_product_commission WHERE id = ".$_GET['cid'];

        $wpdb->query($sql);

        ?>

    <script type="text/javascript">

    location.href = '?page=<?php echo $affiliate_handler;?>&action=list_products&pid=<?php echo $_GET['pid'];?>&msg=Row deleted successfully !';

    </script>

    <?php

    }



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

    //  For subscription

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



    function wpsa_affiliate_subsc_list() {

        global $wpdb, $affiliate_handler;

        $sql = "SELECT a.*, b.name FROM ".$wpdb->prefix."wpsa_affiliate_subscription_commission as a, ".$wpdb->prefix."wpsa_subscriptions as b where a.subsc_id = b.id";

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



        if(isset($_GET['msg'])) {

            ?><div class="updated"><p><strong><?php _e($_GET['msg']);?></strong></p></div><?php

        }

        ?>

        <h3>Active Subscriptions</h3>

    <table class="widefat post fixed" id="messagelist">

        <thead>

            <tr class="tablemenu">

                <th width="5%">#</th>

                <th width="25%">Subscription</th>

                <th width="20%">Commission</th>

                <th width="15%">Edit</th>

                <th width="15%">Delete</th>

            </tr>

        </thead>

            <?php

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

                ?>

        <tr class="read">

            <td><?php _e($k+1);?></td>

            <td><?php echo $row->name;?></td>

            <td><?php echo $row->commission.'%';?></td>

            <td><a href="?page=<?php echo $affiliate_handler;?>&amp;action=edit_subsc&amp;pid=<?php echo $_GET['pid'];?>&amp;cid=<?php echo $row->id;?>">Edit</a></td>

            <td><a href="?page=<?php echo $affiliate_handler;?>&amp;action=delete_subsc&amp;pid=<?php echo $_GET['pid'];?>&amp;cid=<?php echo $row->id;?>">Delete</a></td>

        </tr>

                <?php

            }

            ?>

    </table>

    <p><div style="border-left: 3px solid black; padding-left: 3px;">

        <p><strong>Shortcode tags:</strong><br>

        </p>

        <ul style="margin-left: 10px;">

        <li>Enter this tag into a new page to allow affiliates to signup - <strong>[wpsa_affiliate_register]</strong></li>

        <li>Enter this tag into a new page for the affiliate area - <strong>[affiliate_area]</strong><br>

        </li></ul>

        </div></p>

     <?php

    }



    function wpsa_affiliate_subsc_add() {

        global $wpdb, $affiliate_handler;



        if($_POST) {

        //validation

        $error_msg ='';



        if( $_GET['action'] == 'add_subsc' ) {

            $sql_subsc = "SELECT id FROM ".$wpdb->prefix."wpsa_affiliate_subscription_commission WHERE subsc_id = ".$_POST['subsc'];

            $rows_subsc = $wpdb->get_row($sql_subsc);



            if($rows_subsc){

                $error_msg .= 'Commission structure already exist. </br>';

            }

        }



        //check commission amt and %

        if($_POST['commission'] > 100)

            $error_msg .= 'Commission percentage should be less than 100. </br>';



        //check affiliate link

        if($_POST['page_id'] == '')

            $error_msg .= 'Please select post/page.</br>';



        if($error_msg){

            echo '<div class="error"><p><strong>';

            _e($error_msg);

            echo '</strong></p></div>';

        }

        else{

            if( $_GET['action'] == 'add_subsc' ) {

                $sql = "INSERT INTO " . $wpdb->prefix . "wpsa_affiliate_subscription_commission ( `subsc_id`, `page_id`, `commission`, `recurring`) VALUES

                                                ( '" . $_POST['subsc'] . "', '" . $_POST['page_id'] . "', '" . $_POST['commission'] . "', '" . $_POST['recurring'] . "')";

                $wpdb->query($sql);

                $msg = 'Commission structure added successfully!';

            }

            else {

                    $sql = "UPDATE " . $wpdb->prefix . "wpsa_affiliate_subscription_commission SET

                        `subsc_id` = '" . $_POST['subsc'] . "',

                        `page_id` = '" . $_POST['page_id'] . "',

                        `commission` = '" . $_POST['commission'] . "',

                        `recurring` = '" . $_POST['recurring'] . "'

                        WHERE id = ".$_GET['cid'];

                    $wpdb->query($sql);

                    $msg = 'Commission structure edited successfully!';

            }

        ?>

    <script type="text/javascript">

    location.href = '?page=<?php echo $affiliate_handler;?>&action=list_subsc&msg=<?php echo $msg;?>';

    </script>

    <?php

        }

    }

    if( $_GET['action'] == 'edit_subsc' ) {

        $sql = "SELECT * FROM ".$wpdb->prefix."wpsa_affiliate_subscription_commission WHERE id = ".$_GET['cid'];

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

    }

    ?>



<form name="affiliate_form" id="affiliate_form"  method="post" action="<?php echo "?page=".$affiliate_handler."&action=".$_GET['action']."&cid=".$_GET['cid']; ?>" >

<h3>Add/Edit Subscription</h3>

    <table class="form-table" border="0">

        <tr>

            <td class="label" width="20%"><label id="lsubsc" for="subsc">Select Product</label><br/><small><i>(required)</i></small></td>

            <td class="field" width="30%">



                <select id="subsc_list" name="subsc" >

                    <?php

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

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

                    foreach ( $rows as $row ) {

                        ?><option value="<?php echo $row->id; ?>" <?php if($_POST && $_POST['subsc'] == $row->id) echo 'selected'; else if( $affiliate->subsc_id == $row->id) echo 'selected'; ?> ><?php echo $row->name . ' ( '. $row->amount3 .')'; ?></option><?php

                    }

                    ?>

                </select>

            </td>

            <td class="status" width="50%"></td>

        </tr>



        <tr>

            <td class="label"><label id="lcommission" for="commission">Commission in %</label><br/><small><i>(required)</i></small></td>

            <td class="field"><input id="commission" name="commission" type="text" value="<?php if($_POST) echo $_POST['commission']; else echo $affiliate->commission?>" maxlength="10" /></td>

            <td class="status"></td>

        </tr>

   

        <tr>

            <td class="label">Recurring</td>

            <td class="field">

                <label>

                    <input id="recurring" name="recurring" type="radio" value="no" <?php if($_POST && $_POST['recurring'] == 'no') echo 'checked'; else if( $affiliate->recurring == 'no') echo 'checked'; else echo 'checked' ?> />No

                </label>

                <label>

                    <input id="recurring" name="recurring" type="radio" value="yes" <?php if($_POST && $_POST['recurring'] == 'yes') echo 'checked'; else if( $affiliate->recurring == 'yes') echo 'checked';  ?> />Yes

                </label>

            </td>

            <td class="status"></td>

        </tr>



        <tr>

            <td class="label"><label id="lpage_id" for="page_id">Post/Page</label><br/><small><i>(required)</i></small></td>

            <td class="field"><?php

            

            ?>

            <select id="page_id" name="page_id">

                <option value="0" class="mainop" <?php if($_POST && $_POST['page_id'] == 0) echo 'selected'; else if( $affiliate->page_id == 0) echo 'selected'; ?> >Home Page</option>

                <option value=""></option>

                <option value="" class="mainop" >Posts:</option>

            <?php

            $sql_page = "SELECT ID, post_title from ".$wpdb->base_prefix."posts where post_status = 'publish' and post_type = 'post' ";

            $rows_page = $wpdb->get_results($sql_page);

            foreach ($rows_page as $row_page) {

                ?><option value="<?php echo $row_page->ID; ?>" <?php if($_POST && $_POST['page_id'] == $row_page->ID) echo 'selected'; else if( $affiliate->page_id == $row_page->ID) echo 'selected'; ?> ><?php echo $row_page->post_title; ?></option><?php

            }

            echo '<option value=""></option><option value="" class="mainop" >Pages:</option>';



            $sql_page = "SELECT ID, post_title from ".$wpdb->base_prefix."posts where post_status = 'publish' and post_type = 'page'";

            $rows_page = $wpdb->get_results($sql_page);

            foreach ($rows_page as $row_page) {

                ?><option value="<?php echo $row_page->ID; ?>" <?php if($_POST && $_POST['page_id'] == $row_page->ID) echo 'selected'; else if( $affiliate->page_id == $row_page->ID) echo 'selected'; ?> ><?php echo $row_page->post_title; ?></option><?php

            }

            echo '</select>';

            ?></td>

            <td class="status"></td>

        </tr>



    </table>

    <div class="submit"><input type="submit" value="save" name="submit"/></div>

</form>

    <?php

    }



    function wpsa_affiliate_subsc_delete() {

        global $wpdb, $affiliate_handler;

        $sql = "DELETE FROM ".$wpdb->prefix."wpsa_affiliate_subscription_commission WHERE id = ".$_GET['cid'];

        $wpdb->query($sql);

        ?>

    <script type="text/javascript">

    location.href = '?page=<?php echo $affiliate_handler;?>&action=list_subsc&pid=<?php echo $_GET['pid'];?>&msg=Row deleted successfully !';

    </script>

    <?php

    }



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

    //  For Affiliate Setting

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



    function wpsa_affiliate_setting(){

        if($_POST) {

            $affiliate = array( 'paypal_api_user_name' =>$_POST['paypal_api_user_name'],

                'paypal_api_password' =>$_POST['paypal_api_password'],

                'paypal_api_signature' =>$_POST['paypal_api_signature'],

                'tnc' => stripcslashes($_POST['tnc']),

                'refund_period' => $_POST['refund_period'] ,

                'cookies_expiry' => $_POST['cookies_expiry'],

                'login_redirect' => $_POST['login_redirect'],

                'affiliate_variable' => $_POST['affiliate_variable'],

                'affiliate_area_prod' => $_POST['affiliate_area_prod'],

                'affiliate_area_subsc' => $_POST['affiliate_area_subsc']

                );



            update_option('wpsa_affiliate', $affiliate);

            ?><div class="updated"><p><strong><?php _e('Setting saved successfully!');?></strong></p></div><?php

        }

        $affiliate = get_option('wpsa_affiliate');

    ?>



    <form name="affiliate_form_setting" id="affiliate_form_setting"  method="post" action="" >

    <h3>Settings</h3>

    <table class="form-table" border="0">

        <tr>

            <th class="label" width="20%"><label id="lpaypal_api_user_name" for="paypal_api_user_name">Paypal API User Name</label></th>

            <td class="field" width="80%"><input id="paypal_api_user_name" name="paypal_api_user_name" type="text" value="<?php echo $affiliate['paypal_api_user_name'];?>"  /></td>

        </tr>

        <tr>

            <th class="label"><label id="lpaypal_api_password" for="paypal_api_password">Paypal API Password</label></th>

            <td class="field"><input id="paypal_api_password" name="paypal_api_password" type="text" value="<?php echo $affiliate['paypal_api_password'];?>"  /></td>

        </tr>

        <tr>

            <th class="label"><label id="lpaypal_api_signature" for="paypal_api_signature">Paypal API Signature</label></th>

            <td class="field"><input id="paypal_api_signature" name="paypal_api_signature" type="text" value="<?php echo $affiliate['paypal_api_signature'];?>"  /></td>

        </tr>



        <tr>

            <th class="label"><label id="lrefund_period" for="refund_period">Refund Period (days) </label></th>

            <td class="field"><input id="refund_period" name="refund_period" type="text" value="<?php echo $affiliate['refund_period'];?>"  /></td>

        </tr>

        <tr>

            <th class="label"><label id="lcookies_expiry" for="cookies_expiry">Cookies Expiry Period (days) </label></th>

            <td class="field"><input id="cookies_expiry" name="cookies_expiry" type="text" value="<?php echo $affiliate['cookies_expiry'];?>"  /></td>

        </tr>

        

        <tr>

            <th class="label"><label id="llogin_redirect" for="login_redirect">Login Redirect URL </label></th>

            <td class="field"><input id="login_redirect" name="login_redirect" type="text" value="<?php echo $affiliate['login_redirect'];?>"  /></td>

        </tr>

        <tr>

            <th class="label"><label id="laffiliate_variable" for="affiliate_variable">Affiliate Variable </label></th>

            <td class="field"><input id="affiliate_variable" name="affiliate_variable" type="text" value="<?php echo $affiliate['affiliate_variable'];?>"  /></td>

        </tr>

        <tr>

            <th class="label">Show in Affiliate Area</th>

            <td class="field">

                <input id="affiliate_area_prod" name="affiliate_area_prod" type="checkbox" value="1" <?php if ( $affiliate['affiliate_area_prod'] == 1) echo 'checked';?> />

                <label id="laffiliate_area_prod" for="affiliate_area_prod">Products</label>

            </td>

        </tr>

        <tr>

            <th class="label"></th>

            <td class="field">

                <input id="affiliate_area_subsc" name="affiliate_area_subsc" type="checkbox" value="1" <?php if ( $affiliate['affiliate_area_subsc'] == 1) echo 'checked';?> />

                <label id="laffiliate_area_subsc" for="affiliate_area_subsc">Subscription</label>

            </td>

        </tr>



        <tr>

            <th class="label"><label id="ltnc" for="tnc">Terms and condition Text</label></th>

            <td class="field"><textarea id="tnc" name="tnc" cols="60" rows="10" ><?php echo $affiliate['tnc'];?></textarea></td>

        </tr>

    </table>

    <div class="submit"><input type="submit" value="save" name="submit"/></div>

    </form>

    <p><div style="border-left: 3px solid black; padding-left: 3px;">

        <p><strong>Shortcode tags:</strong><br>

        </p>

        <ul style="margin-left: 10px;">

        <li>Enter this tag into a new page to allow affiliates to signup - <strong>[wpsa_affiliate_register]</strong></li>

        <li>Enter this tag into a new page for the affiliate area - <strong>[affiliate_area]</strong><br>

        </li></ul>

        </div></p>

    <?php

    }



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

    //  For Affiliate Registration form Setting

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



    function wpsa_affiliate_reg_setting(){

    if($_POST) {

            update_option('wpsa_reg', $_POST);

            ?><div class="updated"><p><strong><?php _e('Settings saved successfully!');?></strong></p></div><?php

        }

        $reg = get_option('wpsa_reg');

    ?>



    <form name="affiliate_form_reg_setting" id="affiliate_form_reg_setting"  method="post" action="" >

    <h3>Custom Registration Form</h3>

    <table class="form-table" border="0">

        <tr>

            <td class="label">Select fields that will appear on Affiliate Registration form</td>

        </tr>

        <tr>

            <td class="field">

                <label>

                    <input name="first_name" type="checkbox" value="1" <?php if($reg['first_name'] == '1') echo 'checked';?>  />

                First Name</label>

            </td>

        </tr>

        <tr>

            <td class="field">

                <label>

                    <input name="last_name" type="checkbox" value="1" <?php if($reg['last_name'] == '1') echo 'checked';?>  />

                Last Name</label>

            </td>

        </tr>

        <tr>

            <td class="field">

                <label>

                    <input name="phone" type="checkbox" value="1" <?php if($reg['phone'] == '1') echo 'checked';?>  />

                Phone</label>

            </td>

        </tr>

        <tr>

            <td class="field">

                <label>

                    <input name="tax" type="checkbox" value="1" <?php if($reg['tax'] == '1') echo 'checked';?>  />

                Tax ID or SSN (US only)</label>

            </td>

        </tr>

        <tr>

            <td class="field">

                <label>

                    <input name="address" type="checkbox" value="1" <?php if($reg['address'] == '1') echo 'checked';?>  />

                Address</label>

            </td>

        </tr>

        <tr>

            <td class="field">

                <label>

                    <input name="city" type="checkbox" value="1" <?php if($reg['city'] == '1') echo 'checked';?>  />

                City</label>

            </td>

        </tr>

        <tr>

            <td class="field">

                <label>

                    <input name="zip" type="checkbox" value="1" <?php if($reg['zip'] == '1') echo 'checked';?>  />

                Postal/Zip Code</label>

            </td>

        </tr>

        <tr>

            <td class="field">

                <label>

                    <input name="state" type="checkbox" value="1" <?php if($reg['state'] == '1') echo 'checked';?>  />

                County/State</label>

            </td>

        </tr>

        <tr>

            <td class="field">

                <label>

                    <input name="country" type="checkbox" value="1" <?php if($reg['country'] == '1') echo 'checked';?>  />

                Country</label>

            </td>

        </tr>

    </table>

    <div class="submit"><input type="submit" value="save" name="submit"/></div>

    </form>

    <?php

    }



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

    //  To list affiliate user earning for product referral

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



    function wpsa_users_earning_product() {

        global $wpdb, $affiliate_handler;

       ?>

    <h3>Products - Affiliate Earnings</h3>

    <table class="widefat post fixed" id="messagelist">

        <thead>

            <tr class="tablemenu">

                <th width="5%">#</th>

                <th width="15%">Username</th>

                <th width="30%">Email</th>

                <th width="10%">Referrals</th>

                <th width="10%">Sales</th>

                <th width="10%">Amount</th>

                <th width="10%">Refunded</th>

                <th width="10%">View Log</th>

            </tr>

        </thead>

            <?php

            //echo $sql = "SELECT a.user_id, b.* FROM ".$wpdb->prefix."usermeta a LEFT JOIN ".$wpdb->prefix."wpsa_affiliate_product_sales b on a.user_id = b.affiliat_uid  where a.meta_key = 'wpsa_user'";

            $sql = "SELECT user_id FROM ".$wpdb->prefix."usermeta where meta_key = 'wpsa_user'";

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

            

            if($rows) {

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

                    $userdata = get_userdata($row->user_id);

                    

                    $sql_affiliate = "SELECT count(id) as c, sum(commission) as commission FROM ".$wpdb->prefix."wpsa_affiliate_product_sales where affiliate_uid = ".$row->user_id;

                    $row_affiliate = $wpdb->get_row($sql_affiliate);

                    if($row_affiliate) {

                            $sql_ref = "SELECT count(id) as ref FROM ".$wpdb->prefix."wpsa_affiliate_referrals where user_id = ".$row->user_id;

                            $rows_ref = $wpdb->get_row($sql_ref);



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

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

                    ?>

                        <tr class="read">

                            <td><?php _e($k+1);?></td>

                            <td><?php echo  $userdata->user_login;?></td>

                            <td><?php echo $userdata->user_email;?></td>

                            <td><?php echo $rows_ref->ref;?></td>

                            <td><?php echo $row_affiliate->c;?></td>

                            <td><?php if ($row_affiliate->commission != '') echo '$'.$row_affiliate->commission;?></td>

                            <td><?php if ($rows_refund->refund != '') echo '$'.$rows_refund->refund;?></td>

                            <td><a href="?page=<?php echo $affiliate_handler;?>&action=list_aff_log_product&aid=<?php echo $row->user_id;?>"><?php _e('View Log');?></a></td>

                        </tr>

                    <?php

                        

                    }

                }

            }

            ?>

    </table>

     <?php

    }



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

    //  To list affiliate user earning for subs referral

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



    function wpsa_users_earning_subscription() {

        global $wpdb, $affiliate_handler;

        $sql = "SELECT user_id FROM ".$wpdb->prefix."usermeta where meta_key = 'wpsa_user'";

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

       ?>

    <h3>Subscriptions - Affiliate Earnings</h3>

    <table class="widefat post fixed" id="messagelist">

        <thead>

            <tr class="tablemenu">

                <th width="5%">#</th>

                <th width="15%">Username</th>

                <th width="30%">Email</th>

                <th width="10%">Referrals</th>

                <th width="10%">Sales</th>

                <th width="10%">Refund</th>

                <th width="10%">View Log</th>

            </tr>

        </thead>

            <?php

            if($rows) {

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

                    $userdata = get_userdata($row->user_id);



                    $sql_affiliate = "SELECT count(id) as c, sum(sell) as sell FROM ".$wpdb->prefix."wpsa_affiliate_subscription_sales where affiliate_uid = ".$row->user_id;

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

                    if($rows_affiliate) {

                        foreach($rows_affiliate as $k1 => $row_affiliate) {

                    ?>

                        <tr class="read">

                            <td><?php _e($k+1);?></td>

                            <td><?php echo  $userdata->user_login;?></td>

                            <td><?php echo $userdata->user_email;?></td>

                            <td><?php echo $row_affiliate->c;?></td>

                            <td><?php echo '$'.$row_affiliate->sell;?></td>

                            <td><?php echo 'yet to implement';?></td>

                            <td><a href="?page=<?php echo $affiliate_handler;?>&action=list_aff_log_subscription&aid=<?php echo $row->user_id;?>"><?php _e('View Log');?></a></td>

                        </tr>

                    <?php

                        }

                    }

                }

            }

            ?>

    </table>

     <?php

    }



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

    //  To list affiliate user's log

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



    function wpsa_list_aff_log_product() {

        global $wpdb, $affiliate_handler;

        ?>    

    <table class="widefat post fixed" id="messagelist">

        <thead>

            <tr class="tablemenu">

                <th width="5%">Product ID</th>

                <th width="15%">Transaction ID</th>

                <th width="15%">Payment Date</th>

                <th width="15%">Product Name</th>

                <th width="10%">Product Price</th>

                <th width="10%">Discounted Price</th>

                <th width="10%">Discount</th>

                <th width="10%">Coupon Code</th>

                <th width="10%">Commission</th>

            </tr>

        </thead>

            <?php

            $sql_affiliate = "SELECT * FROM ".$wpdb->prefix."wpsa_affiliate_product_sales where affiliate_uid = ".$_GET['aid'];

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

            if($rows_affiliate) {

                foreach($rows_affiliate as $k => $row_affiliate) {

                    $sql_product = "SELECT name FROM ".$wpdb->prefix."wpsa_product_details where id = ".$row_affiliate->pid;

                    $rows_product = $wpdb->get_row($sql_product);

                ?>

                <tr class="read">

                    <td><?php _e($k);?></td>

                    <td><?php echo $row_affiliate->txn_id;?></td>

                    <td><?php echo $row_affiliate->payment_date;?></td>

                    <td><?php echo $rows_product->name;?></td>

                    <td><?php echo round($row_affiliate->pprice, 2);?></td>

                    <td><?php echo round($row_affiliate->discounted_price, 2);?></td>

                    <td><?php echo $row_affiliate->discount;?></td>

                    <td><?php echo $row_affiliate->coupon_code;?></td>

                    <td><?php echo $row_affiliate->commission;?></td>

                </tr>

                    <?php

                }

            }

        ?>

    </table>

     <?php

    }



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

    //  To list affiliate user's log

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



    function wpsa_list_aff_log_subscription() {

        global $wpdb, $affiliate_handler;

        ?>   

    <table class="widefat post fixed" id="messagelist">

        <thead>

            <tr class="tablemenu">

                <th width="5%">#</th>

                <th width="15%">Transaction ID</th>

                <th width="15%">Payment Date</th>

                <th width="15%">Subscription Name</th>

                <th width="10%">Trail 1 Payment</th>

                <th width="10%">Trail 2 Payment</th>

                <th width="10%">Regular Payment</th>

                <th width="10%">Commission</th>

            </tr>

        </thead>

            <?php

            $sql_affiliate = "SELECT a.*, b.name, b.amount1, b.amount2, b.amount3 FROM ".$wpdb->prefix."wpsa_affiliate_subscription_sales as a, ".$wpdb->prefix."wpsa_subscriptions as b where a.affiliate_uid = ".$_GET['aid']." and a.subsc_id = b.id";

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

            if($rows_affiliate) {

                foreach($rows_affiliate as $k => $row_affiliate) {

                ?>

                <tr class="read">

                    <td><?php _e($k);?></td>

                    <td><?php echo $row_affiliate->txn_id;?></td>

                    <td><?php echo $row_affiliate->payment_date;?></td>

                    <td><?php echo $row_affiliate->name;?></td>

                    <td><?php echo $row_affiliate->amount1;?></td>

                    <td><?php echo $row_affiliate->amount2;?></td>

                    <td><?php echo $row_affiliate->amount3;?></td>

                    <td><?php echo $row_affiliate->commission;?></td>

                </tr>

                        <?php

                }

            }

            ?>

    </table>

     <?php

    }



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

    //  For change affiliate user's payment status

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



    function wpsa_payment() {

        global $wpdb, $affiliate_handler;

        

        if(isset($_GET['msg'])) {

            ?><div class="updated"><p><strong><?php _e($_GET['msg']);?></strong></p></div><?php

        }

        if($_POST) {

            $ids = '';

            $ids = implode(',', $_POST['aff']);

            if ( $ids != '' ) {

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

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

            }



            $ids = '';

            $ids = implode(',', $_POST['aff_subsc']);

            if ( $ids != '' ) {

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

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

            }



            $msg = 'Changes Applied successfuly!';



            ?><script type="text/javascript">

            location.href = '?page=<?php echo $affiliate_handler;?>&action=payment&type=<?php echo $_GET['type'];?>&msg=<?php echo $msg;?>';

            </script><?php

        }

        ?>

    <form action="" method="post">

        <div class="tablenav">

            <div class="alignleft actions">

                <select name="action">

                    <option selected="selected" value="-1">Bulk Actions</option>

                    <option value="pending">Pending</option>

                    <option value="set_to_paid">Set to be paid</option>

                    <option value="sent_payment">Masspay Sent</option>

                    <option value="paid">Paid</option>

                    <option value="refunded">Cancelled</option>

                </select>

                <input type="submit" class="button-secondary action" id="doaction" name="doaction" value="Apply">

            </div>

            <div class="clear"></div>

        </div>

        <div class="clear"></div>

        

    <table class="widefat post fixed" id="messagelist">

        <thead>

            <tr class="tablemenu">

                <th width="5%">#</th>

                <th width="15%">Username</th>

                <th width="20%">Email</th>

                <th width="10%">Earning</th>

                <th width="10%">Status</th>

                <th width="15%">Payment Date</th>

                <th width="15%">Transaction ID</th>

            </tr>

        </thead>

            <?php

            $sql = "SELECT user_id FROM ".$wpdb->prefix."usermeta where meta_key = 'wpsa_user'";

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

            $affiliate = get_option('wpsa_affiliate');



            if($rows) {

                foreach($rows as $row) {

                    $userdata = get_userdata($row->user_id);



                    //$sql_affiliate = "SELECT * FROM ".$wpdb->prefix."wpsa_affiliate_product_sales where status = '".$_GET['type']."' and affiliate_uid = ".$row->user_id;

                    $sql_affiliate = "SELECT id, commission, payment_date, masspay_payment_date, txn_id, masspay_txn_id FROM ".$wpdb->prefix."wpsa_affiliate_product_sales where status = '".$_GET['type']."' and affiliate_uid = ".$row->user_id;

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

                    if($rows_affiliate) {

                        foreach ( $rows_affiliate as $k=>$row_affiliate ) {

                    ?>

                        <tr class="read">

                            <td><input type="checkbox" name="aff[]" value="<?php echo $row_affiliate->id?>" </td>

                            <td><?php echo  $userdata->user_login;?></td>

                            <td><?php echo $userdata->user_email;?></td>

                            <td><?php echo '$'.$row_affiliate->commission;?></td>

                            <td><?php echo $_GET['type'];?></td>

                            <td><?php if ( $_GET['type'] == 'paid')  echo $row_affiliate->masspay_payment_date; else echo $row_affiliate->payment_date;?></td>

                            <td><?php if ( $_GET['type'] == 'paid') echo $row_affiliate->masspay_txn_id; else echo $row_affiliate->txn_id?></td>

                        </tr>

                    <?php

                        }

                    }



                    $sql_affiliate = "SELECT id, commission, payment_date, masspay_payment_date, txn_id, masspay_txn_id FROM ".$wpdb->prefix."wpsa_affiliate_subscription_sales where status = '".$_GET['type']."' and affiliate_uid = ".$row->user_id;

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

                    if($rows_affiliate) {

                        foreach ( $rows_affiliate as $k=>$row_affiliate ) {

                    ?>

                        <tr class="read">

                            <td><input type="checkbox" name="aff_subsc[]" value="<?php echo $row_affiliate->id?>" </td>

                            <td><?php echo  $userdata->user_login;?></td>

                            <td><?php echo $userdata->user_email;?></td>

                            <td><?php echo '$'.$row_affiliate->commission;?></td>

                            <td><?php echo $_GET['type'];?></td>

                            <td><?php if ( $_GET['type'] == 'paid')  echo $row_affiliate->masspay_payment_date; else echo $row_affiliate->payment_date;?></td>

                            <td><?php if ( $_GET['type'] == 'paid') echo $row_affiliate->masspay_txn_id; else echo $row_affiliate->txn_id?></td>

                        </tr>

                    <?php

                        }

                    }

                }

            }

            ?>

    </table>

    </form>

     <?php

    }



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

    //  To  make mass payment

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



    function wpsa_mass_payment() {

        global $wpdb, $affiliate_handler;

        $affiliate = get_option('wpsa_affiliate');

        $wp_sa_setting = get_option('wp_sa_setting');

        

        if(isset($_GET['msg'])) {

            ?><div class="updated"><p><strong><?php _e($_GET['msg']);?></strong></p></div><?php

        }

        if($_POST) {

            $mass_pay = '';

            $mass_pay .= 'USER='.$affiliate['paypal_api_user_name'].'&';

            $mass_pay .= 'PWD='.$affiliate['paypal_api_password'].'&';

            $mass_pay .= 'SIGNATURE='.$affiliate['paypal_api_signature'].'&';

            $mass_pay .= "VERSION=61.0&";

            $mass_pay .= "METHOD=MassPay&";

            $mass_pay .= "RECEIVERTYPE=EmailAddress&";

            

            //$mass_pay .= "L_NOTE0=".count($_POST['email'])."&";



            foreach($_POST['email'] as $i=>$e){

                $mass_pay .= 'L_EMAIL' .$i. '=' . $e . '&';

                $mass_pay .= 'L_AMT' .$i. '=' . $_POST['amt'][$i] . '&';

                $mass_pay .= 'L_UNIQUEID' .$i. '=' . $_POST['aff'][$i] . '&';

                $uids[] .= $_POST['aff'][$i];

            }

            $mass_pay .= "CURRENCYCODE=".$wp_sa_setting['wp_sa_currency_code'];

            if ($wp_sa_setting['wp_sa_test'] == "checked") {

                $paypal_action = "https://api-3t.sandbox.paypal.com/nvp";

            }

            else {

                $paypal_action = "https://api-3t.paypal.com/nvp";

            }



            $ch = curl_init($paypal_action);

            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

            curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

            curl_setopt($ch, CURLOPT_POST, 1);

            curl_setopt($ch, CURLOPT_POSTFIELDS, $mass_pay);

            $res = curl_exec($ch);

            curl_close($ch);

            parse_str($res, $items);

//            print_r($items);

            if('Success' == $items['ACK']) {



                $uids = implode(',', $uids);

                

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

                        `status` = 'sent_payment'

                        WHERE `status` = 'set_to_paid' and affiliate_uid in (".$uids.");";

                $wpdb->query($sql_update_prod );



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

                        `status` = 'sent_payment' 

                        WHERE `status` = 'set_to_paid' and affiliate_uid in (".$uids.");";

                 $wpdb->query($sql_update_subsc );

                 

                $msg = 'Successful! Mass Payment sent.';

            }

            else {

                $msg = 'There is error in processing the mass payment. Please check that paypal email address are valid.';

            }

                ?>

            <script type="text/javascript">

            location.href = '?page=<?php echo $affiliate_handler;?>&action=mass_payment&msg=<?php echo $msg;?>';

            </script>

            <?php

//            else {}

        }

        ?>

    <h3>Pay Commissions - Send Mass Payment</h3>

    <form action="" method="post">

        <div class="tablenav">

            <div class="alignleft actions">

                <input type="submit" class="button-secondary action" id="doaction" name="doaction" value="Send Mass Payment">

            </div>

            <div class="clear"></div>

        </div>

        <div class="clear"></div>



    <table class="widefat post fixed" id="messagelist">

        <thead>

            <tr class="tablemenu">

                <th width="5%">#</th>

                <th width="15%">Username</th>

                <th width="20%">Email</th>

                <th width="10%">Amount</th>

            </tr>

        </thead>

            <?php

            //$sql_affiliate_prod = "SELECT affiliate_uid, sum(commission) as total_commission FROM ".$wpdb->prefix."wpsa_affiliate_product_sales where status = 'set_to_paid' group by affiliate_uid ";

            $sql_affiliate_prod = "SELECT affiliate_uid, sum(commission) as total_commission  FROM

                (

                    SELECT id, affiliate_uid, commission FROM " .$wpdb->prefix. "wpsa_affiliate_product_sales where status = 'set_to_paid'

                        UNION ALL

                    SELECT id, affiliate_uid, commission FROM " .$wpdb->prefix. "wpsa_affiliate_subscription_sales where status = 'set_to_paid'

                )

                AS tunion

                GROUP BY tunion.affiliate_uid";

            $rows_affiliate_prod = $wpdb->get_results($sql_affiliate_prod);



            if ( $rows_affiliate_prod ) {

                foreach ( $rows_affiliate_prod as $k => $row_affiliate_prod ) {

                    if($row_affiliate_prod->affiliate_uid){

                        $userdata = get_userdata($row_affiliate_prod->affiliate_uid);

                        $user_meatdata = get_usermeta($row_affiliate_prod->affiliate_uid, 'wpsa_user');

                        $total_commission = floor($row_affiliate_prod->total_commission*100)/100;

                    ?>

                        <tr class="read">

                            <td>

                                <input type="checkbox" name="aff[]" value="<?php echo $row_affiliate_prod->affiliate_uid;?>"/>

                                <input type="hidden" name="email[]" value="<?php echo $userdata->user_email;?>"/>

<!--                                <input type="hidden" name="email[]" value="<?php echo $user_meatdata['email'];?>"/>-->

<!--                                <input type="hidden" name="amt[]" value="<?php echo $row_affiliate_prod->total_commission;?>"/>-->

                                <input type="hidden" name="amt[]" value="<?php echo $total_commission;?>"/>

                            </td>

                            <td><?php echo  $userdata->user_login;?></td>

<!--                            <td><?php echo $user_meatdata['email'];?></td>-->

                            <td><?php echo $userdata->user_email;?></td>

<!--                            <td><?php echo $row_affiliate_prod->total_commission;?></td>-->

                            <td><?php echo $total_commission;?></td>

                        </tr>

                    <?php

                    }

                }

            }

            ?>

    </table>

    </form>

     <?php

    }

?>