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

function rt_subscription_log_page() {
    global $wpdb;
    ?>
<div class="wrap">
    <h2>Subscription Sales</h2>
        <?php
        if ($_GET['wpsa_action'] === "add_subscriber") {
            wpsa_subscription_log_add();
            return;
        }
        if (isset($_GET['item_id'])) {
            if ($_GET['wpsa_action'] === "edit") {
                wpsa_subscription_log_edit();
                return;
            }
            else if ($_GET['wpsa_action'] === "delete") {
                wpsa_subscription_log_delete();
                return;
            }
            else {
                continue;
            }
        }
        $table_name = $wpdb->prefix . "wpsa_subscription_transaction";
        $qry = "SELECT *  FROM $table_name";
        $pagenum = isset($_GET['slpage']) ? $_GET['slpage'] : 1;
        $per_page = 20;
        $count = count($wpdb->get_results($qry, ARRAY_A));
        $page_links = paginate_links( array(
                'base' => add_query_arg( 'slpage', '%#%' ),
                '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);
        ?>
    <a href="?page=wp-sa-subscription-transaction-log&wpsa_action=add_subscriber" title="Add Subscriber">Add Subscriber</a>
    <table class="widefat post fixed" style="margin-top: 10px;">
        <thead>
            <tr class="tablemenu">
                <th width="6%">User ID</th>
                <th width="10%">Subscription ID</th>
                <th width="12%">Paypal transaction ID</th>
                <th width="16%">Customer email ID</th>
                <th width="10%">Subscription date</th>
                <th width="7%">Subscription duration</th>
                <th width="5%">Recurring</th>
                <th width="4%">Status</th>
                <th width="3%">Edit</th>
                <th width="3%">Delete</th>
            </tr>
        </thead>
        <tbody>
                <?php
                if(empty ($results)) {
                    echo '<tr><td colspan="7">There are no subscriptions. <a href="'.get_option('siteurl').'/wp-admin/admin.php?page=wp-sa-manage-subscription">Click here</a> to Manage Subscriptions</td></tr></tbody></table></div>';
                    return ;
                }
                $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_option('siteurl'); ?>/wp-admin/user-edit.php?user_id=<?php echo $result->user_ID; ?>"><?php echo get_the_author_meta('user_login',$result->user_ID);?></a>
                </td>
                <td>
                            <?php if($result->subscriber_id) echo $result->subscriber_id ;else echo 'NA';?>
                </td>
                <td>
                            <?php if($result->txn_id) echo $result->txn_id ;else echo 'NA';?>
                </td>
                <td>
                            <?php if($result->payer_email) echo $result->payer_email ; else echo 'NA'; ?>
                </td>
                <td>
                            <?php  if($result->subscr_date) echo date('j M, Y', strtotime ($result->subscr_date)) ; else echo 'NA'; ?>
                </td>
                <td>
                            <?php
                            if( $result->period){
                            preg_match('/(.*)(\w$)/isU', $result->period, $matches);
                            switch($matches[2]) {
                                case 'D':
                                    echo $matches[1].' Day(s)';
                                    break;
                                case 'W':
                                    echo $matches[1].' Week(s)';
                                    break;
                                case 'M':
                                    echo $matches[1].' Month(s)';
                                    break;
                                case 'Y':
                                    echo $matches[1].' Year(s)';
                                    break;
                                default :
                                    echo $result->period;
                                    break;
                            }

                            }else echo 'NA';
                            ?>
                </td>
                <td>
                            <?php
                            if($result->recurring == 1)
                                echo 'yes';
                            else
                                echo 'no';
                            ?>
                </td>
                <td>
                            <?php echo $result->subscr_status ;?>
                </td>
                <td >
                    <a href="?page=wp-sa-subscription-transaction-log&wpsa_action=edit&item_id=<?php echo $result->id; ?>" title="Edit this item"><img title="Edit!" alt="Edit!" src="<?php echo WP_PLUGIN_URL; ?>/wp-salesautomator/img/icons/Edit.png" width="16px"/></a>
                </td>
                <td>
                    <a href="?page=wp-sa-subscription-transaction-log&wpsa_action=delete&item_id=<?php echo $result->id; ?>" title="Delete this item"><img title="Delete!" alt="Delete!" src="<?php echo WP_PLUGIN_URL; ?>/wp-salesautomator/img/icons/delete.png" onclick="return confirm('Do you really want to delete it?');"/></a>
                </td>

            </tr>
                    <?php
                    $k++;
                }
                ?>
        </tbody>
    </table>
        <?php
        if($count>$per_page) {
            echo $page_links;
        }
        ?>
</div>


    <?php
}

function wpsa_subscription_log_add() {
    global $wpdb;
    if ( isset($_POST['reg_s_submit']) && $_POST['reg_s_submit'] === 'Add') {
        $customer_name = trim($_POST['wpsa_user_name']);
        $customer_email = trim($_POST['email']);
        $customer_tx_id = trim($_POST['tx_id']);
        $customer_sub_id = trim($_POST['sub_id']);
        $customer_sub_type = explode('_|_', $_POST['sub_type']);
        $customer_sub_type_id = $customer_sub_type[0];
        $customer_sub_type_name = $customer_sub_type[1];
        $customer_send_email = $_POST['email_links'];

        //validation
        $error = '';
        $error_flag = 0;

        if ($customer_name == '') {
            $error .= 'Please enter customer name.<br/>';
            $error_flag = 1;
        }
        if ($customer_email == '' || !is_email( $customer_email ) ) {
            $error .= 'Please enter email.<br/>';
            $error_flag = 1;
        }
        if ($customer_tx_id == '') {
            $error .= 'Please enter transaction ID.<br/>';
            $error_flag = 1;
        }
        if ($customer_sub_id == '') {
            $error .= 'Please enter subscription ID.<br/>';
            $error_flag = 1;
        }

        if ( $error_flag ) {
            echo $error;
        }

        if ( !$error_flag ) {

            if ( email_exists( $customer_email ) ) {
                
                $query_user_id = "SELECT ID FROM {$wpdb->users} WHERE user_email='{$customer_email}'";
                $user_id = $wpdb->get_var($query_user_id);

                $update_log_query = "INSERT INTO ".$wpdb->prefix."wpsa_subscription_transaction (`user_ID`, `txn_id`, `subscr_status`, `subscriber_id`, `item_name`, `item_number`, `payer_email`, `subscr_date`) VALUES({$user_id},'{$customer_tx_id}', 'active', '{$customer_sub_id}', '{$customer_sub_type_name}', '{$customer_sub_type_id}', '{$customer_email}', now())";
                $wpdb->query($update_log_query);

                $v = get_usermeta($user_id, 'subscription_id');

                if ( $v!='' ) {
                    $customer_sub_id = $v.','.$customer_sub_id;
                }

                update_usermeta($user_id, 'subscription_id', $customer_sub_id);
                update_usermeta($user_id, 'transaction_id', $customer_tx_id);
                
                echo 'Subscription '.$customer_sub_type_name.' added to user with email '.$customer_email.'.';
                do_action('wpsa_suscr_add_log', $user_id, $_POST['sub_id']);
            }

            else if ( is_email( $customer_email ) ) {
                $customer_name = str_replace(' ', '.', $customer_name);
                $user_pass = wp_generate_password();
                $user_id = wp_create_user( $customer_name, $user_pass, $customer_email );
                if ($customer_send_email === 'yes') {
                    wp_new_user_notification($user_id, $user_pass);
                }
/*
                if(isset($customer_tx_id) && isset($customer_sub_id)) {
                    $update_log_query = "INSERT INTO {$table_name} (`user_ID`, `txn_id`, `subscr_status`, `subscriber_id`, `item_name`, `item_number`) VALUES({$user_id},'{$customer_tx_id}', 'active', '{$customer_sub_id}', '{$customer_sub_type_name}', '{$customer_sub_type_id}')";
                }
                if(!isset($customer_tx_id) && isset($customer_sub_id)) {
                    $update_log_query = "INSERT INTO {$table_name} (`user_ID`,`subscr_status`, `subscriber_id`, `item_name`, `item_number`) VALUES({$user_id}, 'active', '{$customer_sub_id}', '{$customer_sub_type_name}', '{$customer_sub_type_id}')";
                }
                else
                    $update_log_query = "INSERT INTO {$table_name} (`user_ID`, `subscr_status`, `item_name`, `item_number`) VALUES({$user_id},'active', '{$customer_sub_type_name}', '{$customer_sub_type_id}')";
*/
                $update_log_query = "INSERT INTO ".$wpdb->prefix."wpsa_subscription_transaction (`user_ID`, `txn_id`, `subscr_status`, `subscriber_id`, `item_name`, `item_number`, `payer_email`, `subscr_date`) VALUES({$user_id},'{$customer_tx_id}', 'active', '{$customer_sub_id}', '{$customer_sub_type_name}', '{$customer_sub_type_id}', '{$customer_email}', now())";
                $wpdb->query($update_log_query);

                update_usermeta($user_id, 'subscription_id', $customer_sub_id);
                update_usermeta($user_id, 'transaction_id', $customer_tx_id);
                
                echo 'User '.$customer_name.' added and subscription '.$customer_sub_type_name.' added to user.';
            }

            else {
                echo 'Email format not correct. Please try again.';
            }
        }
    }
    ?>
<form name="add-subsc-sales" id="add-subsc-sales" method="post" enctype="multipart/form-data" action="<?php echo "?page=wp-sa-subscription-transaction-log&wpsa_action=add_subscriber"; ?>" enctype="multipart/form-data">
    <table class="form-table" border="0">
        <tr>
            <td class="label" width="14%"><label>Customer Name</label></td>
            <td class="field" width="50%"><input type="text" name="wpsa_user_name" value=""/></td>
            <td class="status"></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>
            <td class="status"></td>
        </tr>

        <tr>
            <td class="label" width="14%"><label>Paypal transaction ID</label></td>
            <td class="field" width="50%"><input name="tx_id" type="text" value="" /></td>
            <td class="status"></td>
        </tr>

        <tr>
            <td class="label" width="14%"><label>Subscription ID</label></td>
            <td class="field" width="50%"><input name="sub_id" type="text" value="" /></td>
            <td class="status"></td>
        </tr>

        <tr>
            <td class="label" width="14%"><label>Subscription</label></td>
            <td class="field" width="50%">
                    <?php
                    $subs_table = $wpdb->prefix . "wpsa_subscriptions";
                    $subs_query = "SELECT id, name FROM {$subs_table}";
                    $subs_results = $wpdb->get_results($subs_query);
                    if (is_array($subs_results)) {
                        ?>
                <select name="sub_type">
                            <?php
                            foreach ($subs_results as $subs_result) {
                                ?>
                    <option value="<?php echo $subs_result->id.'_|_'.$subs_result->name;?>"><?php echo $subs_result->name;?></option>
                                <?php
                            }
                            ?>
                </select>
                        <?php
                    }
                    ?>
            </td>
        </tr>

        <tr>
            <td class="label"><label for="email_links"> Send Email With Registration Detail</label></td>
            <td class="field"><input id="email_links" name="email_links" type="checkbox" value="yes"/></td>
        </tr>

        <tr>
            <td></td>
            <td>
                <input type="submit" value="Add" name="reg_s_submit"/>
            </td>
        </tr>
    </table>
</form>
    <?php
}

function wpsa_subscription_log_edit() {
    global $wpdb;
    ?>
<h3>Edit</h3>
    <?php
    $table_name = $wpdb->prefix . "wpsa_subscription_transaction";
    $id = $_GET['item_id'];
    if (isset($_POST['edit_s_submit'])) {
        $user_id = $_POST['wpsa_user_id'];
        $email = $_POST['email'];
        $tx_id = $_POST['tx_id'];
        $subs_id = $_POST['sub_id'];
        $sub_type = explode('_|_', $_POST['sub_type']);
        $sub_type_id = $sub_type[0];
        $sub_type_name = $sub_type[1];
        $us_query = "UPDATE {$table_name} SET payer_email='{$email}', txn_id='{$tx_id}', subscriber_id='{$subs_id}', item_number={$sub_type_id}, item_name='{$sub_type_name}', edited=1 WHERE id={$id}";
        if ($wpdb->query($us_query)) {
            update_usermeta( $user_id, 'subscription_id', $subs_id);
            echo '<h5>Updated Successfully</h5>';
        }
    }
    $query = "SELECT * FROM {$table_name} WHERE id={$id}";
    $result = $wpdb->get_row($query);
    if ($result) {
        ?>
<form method="post" enctype="multipart/form-data" action="<?php echo "?page=wp-sa-subscription-transaction-log&wpsa_action=edit&item_id={$id}"; ?>" enctype="multipart/form-data">
    <table class="form-table" border="0">
        <tr>

            <td class="label" width="14%"><label>Username</label></td>

            <td class="field" width="50%"><?php echo get_the_author_meta('user_login',$result->user_ID);?>
                <input type="hidden" name="wpsa_user_id" value="<?php echo $result->user_ID;?>"/>
            </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="<?php echo $result->payer_email;?>" /></td>

        </tr>
        <tr>

            <td class="label" width="14%"><label>Paypal transaction ID</label></td>

            <td class="field" width="50%"><input name="tx_id" type="text" value="<?php echo $result->txn_id;?>" /></td>

        </tr>
        <tr>

            <td class="label" width="14%"><label>Subscription ID</label> (Not Recommended)</td>

            <td class="field" width="50%"><input name="sub_id" type="text" value="<?php echo $result->subscriber_id;?>" /></td>

        </tr>
        <tr>

            <td class="label" width="14%"><label>Subscription</label></td>

            <td class="field" width="50%">
                        <?php
                        $subs_table = $wpdb->prefix . "wpsa_subscriptions";
                        $subs_query = "SELECT id, name FROM {$subs_table}";
                        $subs_results = $wpdb->get_results($subs_query);
                        if (is_array($subs_results)) {
                            foreach ($subs_results as $subs_result) {
                                ?>
                <input name="sub_type" type="radio" value="<?php echo $subs_result->id.'_|_'.$subs_result->name;?>" <?php if ($result->item_number === $subs_result->id) {
                                    echo "checked";
                                       }?>/><?php echo $subs_result->name;?><br />
                                       <?php
                                   }
                               }
                               ?>
            </td>

        </tr>

        <tr>
            <td></td>
            <td>
                <input type="submit" value="Save" name="edit_s_submit"/>
            </td>
        </tr>
    </table>
</form>
        <?php
    }
}

function wpsa_subscription_log_delete() {
    global $wpdb;
    $id = $_GET['item_id'];?>
<h3>Delete Subscription</h3>
    <?php
    if ($id) {
        $table_name = $wpdb->prefix . "wpsa_subscription_transaction";
        $del_sql = "DELETE FROM {$table_name} WHERE id={$id} LIMIT 1";
        $wpdb->query($del_sql);
        echo '<h5>Subscription Deleted Successfully</h5>';
        $url = get_bloginfo('url').'/wp-admin/admin.php?page=wp-sa-subscription-transaction-log';
        echo 'Go Back to <a href="'.$url.'">Subscription Log</a>.';
    }
}


?>
