<?php 
function wpsa_coupon_options_html() {
    global $handler;
    ?>

<div class="wrap">

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

    <div id="icon-wpsa_coupon" class="icon32"><img src="<?php echo $icon_url; ?>"></div><h2><?php _e('WPSA Coupon codes');?></h2>

    <p class="">
        <a href="?page=<?php echo $handler;?>&action=list" class="row-title">List Product</a> |
        <a href="?page=<?php echo $handler;?>&action=add" class="row-title">Add Coupon</a>
    </p>
        <?php
        switch($_GET['action']) {
            case 'list':
                wpsa_coupon_product_list();
                break;
            case 'add':
            case 'edit':
                wpsa_coupon_add();
                break;
            case 'view':
                wpsa_coupon_view();
                break;
            case 'delete':
                wpsa_coupon_delete();
                break;
            default:
                wpsa_coupon_product_list();
                break;
        }
        echo '</div>';
    }

function wpsa_coupon_product_list() {
    global $wpdb, $handler;
    $sql = "SELECT * FROM ".$wpdb->prefix."wpsa_product_details";
    $rows = $wpdb->get_results($sql);
    if(isset($_GET['msg'])) {
        echo '<div class="updated"><p><strong>'.$_GET['msg'].'</strong></p></div>';
    }
    ?>
<table class="widefat post fixed" id="messagelist">
    <thead>
        <tr class="tablemenu">
            <th width="10%">#</th>
            <th width="60%">Product Name</th>
            <th width="30%">View Coupons</th>
        </tr>
    </thead>
        <?php
        foreach($rows as $k => $row) {
            ?>
    <tr class="read">
        <td><?php _e($k);?></td>
        <td><?php echo $row->name;?></td>
        <td><a href="?page=<?php echo $handler;?>&amp;action=view&amp;pid=<?php echo $row->id;?>">View Coupons</a></td>

    </tr>
            <?php
        }
        ?>
    <tr class="read">
        <td><?php _e($k+1);?></td>
        <td><?php _e('All');?></td>
        <td><a href="?page=<?php echo $handler;?>&amp;action=view&amp;pid=0">View Coupons</a></td>

    </tr>
</table>

 <?php
}


function wpsa_coupon_view() {
    global $wpdb, $handler;
    
    $sql = "SELECT * FROM ".$wpdb->prefix."wpsa_coupon WHERE product_id = ".$_GET['pid'];
    $rows = $wpdb->get_results($sql);

    if($_GET['pid']!=0){
        if( $rows ) $msg = 'List of coupon code for product "' . wpsa_get_product( $_GET['pid'] )->name . '"';
        else $msg = 'There is no coupon code for product "' . wpsa_get_product( $_GET['pid'] )->name . '"';
    }
    else $msg = 'List of coupon code for all products.';
    
    echo '<div class="updated"><p><strong>';
    _e($msg);
    echo '</strong></p></div>';

    if(isset($_GET['msg'])) {
        echo '<div class="updated"><p><strong>'.$_GET['msg'].'</strong></p></div>';
    }
    ?>
<table class="widefat post fixed" id="messagelist">
    <thead>
        <tr class="tablemenu">
            <th width="5%">#</th>
            <th width="25%">Coupon Code</th>
            <th width="20%">Discount</th>
            <th width="20%">Validity</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);?></td>
        <td><?php echo $row->coupon_code;?></td>
        <td><?php echo $row->discount; if($row->discount_type == 'cur') echo 'USD'; else echo '%'?></td>
        <td><?php echo date("M j, Y, g:i a", strtotime( $row->validity ) ) ;?></td>
        <td><a href="?page=<?php echo $handler;?>&amp;action=edit&amp;pid=<?php echo $_GET['pid'];?>&amp;cid=<?php echo $row->id;?>">Edit</a></td>
        <td><a href="?page=<?php echo $handler;?>&amp;action=delete&amp;pid=<?php echo $_GET['pid'];?>&amp;cid=<?php echo $row->id;?>">Delete</a></td>
    </tr>
            <?php
        }
        ?>
</table>

 <?php
}


function wpsa_coupon_add() {
    global $wpdb,$handler;

    if($_POST) {
    //validation
    $error_msg ='';

    //check discount code

    if($_GET['action'] == 'add') {
        $sql = "SELECT id FROM ".$wpdb->prefix."wpsa_coupon WHERE coupon_code = '" .$_POST['coupon_code']. "'";
        $rows = $wpdb->get_row($sql);
        if($rows) $error_msg .= 'Discount code already used. </br>';
    }

    //check discount amt and %
    if($_POST['discount_type'] == 'per' ) {
        if($_POST['discount'] > 100)
            $error_msg .= 'Discount percentage should be less than 100. </br>';
    }
    else {
        if($_POST['product'] > 0) {
            $sql_product = "SELECT price FROM ".$wpdb->prefix."wpsa_product_details WHERE id = ".$_POST['product'];
            $rows_product = $wpdb->get_row($sql_product);

            if($rows_product->price < $_POST['discount'] )
                $error_msg .= 'Discount should be less than product price. </br>';
        }
        else {
            if($_POST['discount'] > $_POST['purchase_limit'] )
                $error_msg .= 'Purchase limit should be more than discount amount.';
        }
    }

    //check validity
    if(isset($_POST['validity']) && strtotime($_POST['validity'] )< time()) {
        $error_msg .= 'Validity date should be greater than today. </br>';
    }

    if($error_msg){
        echo '<div class="error"><p><strong>';
        _e($error_msg);
        echo '</strong></p></div>';
    }
    else{
        if( $_GET['action'] == 'add' ) {
            $sql = "INSERT INTO " . $wpdb->prefix . "wpsa_coupon ( `product_id`, `coupon_code`, `validity`, `discount_type`, `discount`, `purchase_limit`) VALUES
                                            ( '" . $_POST['product'] . "', '" . $_POST['coupon_code'] . "', '" . $_POST['validity'] . "', '" . $_POST['discount_type'] . "', '" . $_POST['discount'] . "', '" . $_POST['purchase_limit'] . "')";
            $wpdb->query($sql);
            $msg = 'Coupon code added successfully!';
        }
        else {
                $sql = "UPDATE " . $wpdb->prefix . "wp_wpsa_coupon SET
                    `product_id` = '" . $_POST['product'] . "',
                    `coupon_code` = '" . $_POST['coupon_code'] . "',
                    `validity` = '" . $_POST['validity'] . "',
                    `discount_type` = '" . $_POST['discount_type'] . "',
                    `discount` = '" . $_POST['discount'] . "',
                    `purchase_limit` = '" . $_POST['purchase_limit'] . "'
                    WHERE id = ".$_GET['cid'];
                $msg = 'Coupon code edited successfully!';
        }
        //            echo '<div class="updated"><p><strong>';
//            _e($msg);
//            echo '</strong></p></div>';
    ?>
<script type="text/javascript">
location.href = '?page=<?php echo $handler;?>&action=list&msg=<?php echo $msg;?>';
</script>
<?php
    }
}


if( $_GET['action'] == 'edit' ) {
    $sql = "SELECT * FROM ".$wpdb->prefix."wpsa_coupon WHERE id = ".$_GET['cid'];
    $coupon = $wpdb->get_row($sql);
}

?>

<form name="coupon_form" id="coupon_form"  method="post" action="<?php echo "?page=".$handler."&action=".$_GET['action']; ?>" >
<table class="form-table" border="0">
    <tr>
        <td class="label" width="10%"><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( $coupon->product_id == $row->id) echo 'selected'; ?> ><?php echo $row->name . ' ( '. $row->price .')'; ?></option><?php
                }
                ?>
                    <option value="0">All</option>
            </select>
        </td>
        <td class="status" width="60%"></td>
    </tr>
    <tr>
        <td class="label"><label id="lcoupon_code" for="coupon_code">Coupon Code</label><br/><small><i>(required)</i></small></td>
        <td class="field"><input type="text" id="coupon_code" name="coupon_code" value="<?php if($_POST) echo $_POST['coupon_code']; else echo $coupon->coupon_code?>"/> </td>
        <td class="status"></td>
    </tr>
    <tr>
        <td class="label"><label id="ldiscount" for="discount">Discount Amount</label><br/><small><i>(required)</i></small></td>
        <td class="field"><input id="discount" name="discount" type="text" value="<?php if($_POST) echo $_POST['discount']; else echo $coupon->discount?>" maxlength="10" /></td>
        <td class="status"></td>
    </tr>
    <tr id="purchlimit" style="display: none;">
        <td class="label"><label id="lpurchase_limit" for="purchase_limit">Minimum Purchase Amount (USD)</label><br/><small><i>(required)</i></small></td>
        <td class="field"><input id="purchase_limit" name="purchase_limit" type="text" value="<?php if($_POST) echo $_POST['purchase_limit']; else echo $coupon->purchase_limit?>" maxlength="10" /></td>
        <td class="status"></td>
    </tr>

    <tr>
        <td class="label" width="10%"><label id="ldiscount_type" for="discount_type">Discount Type</label><br/><small><i>(required)</i></small></td>
        <td class="field" width="30%">
            <select id="discount_type" name="discount_type" >
                <option value="per" <?php if($_POST && $_POST['discount_type'] == 'per') echo 'selected'; else if( $coupon->discount_type == 'per') echo 'selected'; ?>>%</option>
                <option value="cur" <?php if($_POST && $_POST['discount_type'] == 'cur') echo 'selected'; else if( $coupon->discount_type == 'cur') echo 'selected'; ?>>USD</option>
            </select>
        </td>
        <td class="status" width="60%"></td>
    </tr>

    <tr>
        <td class="label"><label id="ldatepicker" for="datepicker">Validity till</label><br/><small><i>(required)</i></small></td>
        <td class="field"><input type="text" id="datepicker" name="validity" value="<?php if($_POST) echo $_POST['validity']; else if($coupon->validity!='' ) echo date('Y-m-d', strtotime($coupon->validity ) );?>"/> </td>
        <td class="status"></td>
    </tr>


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

</form>
<?php }

function wpsa_coupon_delete() {
    global $wpdb, $handler;
    $sql = "DELETE FROM ".$wpdb->prefix."wpsa_coupon WHERE id = ".$_GET['cid'];
    $wpdb->query($sql);
    //echo '<div class="updated"><p><strong>Coupon deleted successfully ! </strong></p></div>';
    ?>
<script type="text/javascript">
location.href = '?page=<?php echo $handler;?>&action=view&pid=<?php echo $_GET['pid'];?>&msg=Coupon deleted successfully !';
</script>
<?php
}
?>