<?php

function wpsa_coupon_activate() {
    global $wpdb;

    $table_name = $wpdb->prefix . 'wpsa_coupon';
    $wpsa_coupon_log = $wpdb->prefix . 'wpsa_coupon_log';

    //detects if this is a new installation or simply an update.
    $new_installation = $wpdb->get_var("show tables like '$table_name'") ;

    if ( !$new_installation ) {
        $sql = "CREATE TABLE " . $table_name . " (
                        id mediumint(9) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
                        `product_id` INT NOT NULL ,
                        `coupon_code` VARCHAR( 200 ) NOT NULL ,
                        `validity` DATETIME NOT NULL ,
                        `purchase_limit` VARCHAR( 200 ) NULL ,
                        `discount_type` ENUM( 'cur', 'per' ) NOT NULL DEFAULT 'cur',
                        `discount` FLOAT(10,2) NOT NULL
		);";
        $sql .= "CREATE TABLE " . $wpsa_coupon_log . " (
                    id mediumint(9) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
                  `product_details` longtext NOT NULL,
                  `total_product_sold` int(11) NOT NULL,
                  `payment_date` varchar(200) NOT NULL,
                  `txn_id` varchar(100) NOT NULL,
                  `gross_sell` varchar(100) NOT NULL,
                  `coupon_code` varchar(200) NOT NULL,
                  `discount` varchar(100) NOT NULL
		);";

        require_once( ABSPATH . 'wp-admin/includes/upgrade.php');  
        dbDelta($sql);
    }
}

function wpsa_coupon_uninstall() {
    global $wpdb;
    $wp_sa_setting = get_option('wp_sa_setting');

    if ( $wp_sa_setting['wp_sa_keep_data'] != 1) {
        if ((get_option( 'wpsa_coupon_version' ) == WPSA_COUPON_VERSION ) && ((get_option( 'wpsa_coupon_purgeUponDeactivation' )))) {
            $table_name = $wpdb->prefix . 'wpsa_coupon';
            $wpsa_coupon_log = $wpdb->prefix . 'wpsa_coupon_log';

            if ($wpdb->get_var("SHOW TABLES LIKE '".$table_name."'") == $table_name) {
                $wpdb->query( "DROP TABLE $table_name, $wpsa_coupon_log ");
            }
        }
    }
}

if(function_exists('wpsa_install')) {
    add_action('admin_menu', 'wpsa_coupon_menu', 12);
    function wpsa_coupon_menu() {
        global $handler;
        //$handler = sa_rt_get_addonsubmenu('wpsa-coupon-options');
        if(!isset($submenu['wpsa-addon']) && count($submenu['wpsa-addon']<=0))  $handler = 'wpsa-addon';
        else $handler = 'wpsa-coupon-options';

        $page = add_submenu_page('wpsa-addon', 'WPSA Coupons', 'Coupons', 'manage_options', $handler, 'wpsa_coupon_options_html');
    }
}

if(is_admin() && strpos($_SERVER['REQUEST_URI'], $handler ) !== false)
        wp_enqueue_style('jquery-ui-css','http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css');

// Loads CSS files
add_action( 'wp_print_styles', 'wpsa_coupon_options_load_css' );
function wpsa_coupon_options_load_css() {

    if(!is_admin()) {
        wp_enqueue_style('fancybox-css', WPSA_COUPON_URL.'/fancybox/jquery.fancybox-1.3.1.css');
        wp_enqueue_style('wpsa_coupon_style', WPSA_COUPON_URL.'/css/wpsa_style.css');
    }
}

// Loads JavaScript files
add_action( 'wp_print_scripts', 'wpsa_coupon_options_load_js' );
function wpsa_coupon_options_load_js() {
    global $handler;
    if ( strpos($_SERVER['REQUEST_URI'], $handler ) !== false ) {
        wp_enqueue_script('jquery-api','http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js');
        wp_enqueue_script('jquery-ui-api','http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js');
        wp_enqueue_script('wpsa-coupon-js-admin',WPSA_COUPON_URL.'/js/wpsa-coupon-admin.js');
        wp_enqueue_script('jquery-validate',WPSA_COUPON_URL.'/js/jquery.validate.js');
        
    }
    if(!is_admin()){
	    wp_enqueue_script('jquery');
        wp_enqueue_script('mousewheel',WPSA_COUPON_URL.'/fancybox/jquery.mousewheel-3.0.2.pack.js', array('jquery'));
        wp_enqueue_script('fancybox',WPSA_COUPON_URL.'/fancybox/jquery.fancybox-1.3.1.js');
        wp_enqueue_script('wpsa-coupon-js',WPSA_COUPON_URL.'/js/wpsa-coupon.js');
        wp_localize_script('wpsa-coupon-js', 'wpsa_coupon_var', array(
            'admin_ajax_php' => get_option('siteurl').'/wp-admin/admin-ajax.php'
        ));
    }
}   

function wpsa_get_product($pid) {
    global $wpdb;
    $sql = "SELECT * FROM ".$wpdb->prefix."wpsa_product_details where id = ".$pid;
    $rows = $wpdb->get_row($sql);
    return $rows;
}
//------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------
add_action('wpsa_product_list_head', 'wpsa_product_list_head_coupon');
function wpsa_product_list_head_coupon() {
    echo '<th width="20%"></th>';
}

add_action('wpsa_product_list_col', 'wpsa_product_list_col_coupon', 10, 1);
function wpsa_product_list_col_coupon($pid) {
    echo '<td align="center"><span class="coupon_code_hidden"></span></td>';
}

add_action('wpsa_product_list_end', 'wpsa_product_list_end_coupon', 10);
function wpsa_product_list_end_coupon() {
    ?>
<p><small>
    <a href="#couponForm" class="add_coupon" id="pid">Enter coupon +</a>
    <a href="#emptyCart" id="empty_cart">Empty Cart</a></small>
    <span id="all_coupon"></span>
    <span id="coupon_disc"></span>
<p>
    <div id="add_coupon_form">
        <form  id="couponForm" method="post" action="">
            <p id="error" style="display: block">Please select a product, then enter the coupon code.</p>
            <p>
                <label for="coupon_code">Coupon Code: </label>
                <input type="text" id="coupon_code" name="coupon_code" size="30" />
                <input type="hidden" name="action" value="wpsa_validate_coupon"/>
                <input type="hidden" id="product_id" name="product_id" value=""/>
            </p>
            <p>
                <input type="submit" value="ADD" />
            </p>
        </form>
    </div>
    <?php
}

//If user not logged in
add_action('wp_ajax_nopriv_wpsa_validate_coupon', 'wpsa_validate_coupon');
//if user logged in
add_action('wp_ajax_wpsa_validate_coupon', 'wpsa_validate_coupon');

function wpsa_validate_coupon() {
    global $wpdb;

    $pid_list = explode(',', $_POST['product_id']);
    $pcnt = count($pid_list);

    $sql = "SELECT * FROM wp_wpsa_coupon WHERE product_id in ( " .$_POST['product_id']. ", 0 ) and coupon_code = '" .$_POST['coupon_code']. "'";
    $row = $wpdb->get_row($sql);

    if($row) {
        $msg = '';

        if($row->discount_type == 'cur') $discount_type = 'USD';
        else $discount_type = '%';
 
        //if coupon code of "all", i.e. product_id = 0
        if($row->product_id == 0){
            $sql_product = "SELECT  sum(price) as price FROM ".$wpdb->prefix."wpsa_product_details WHERE id in ( ".$_POST['product_id']. ")";
            $rows_product = $wpdb->get_row($sql_product);
            $rows_product_price = $rows_product->price;

            if($row->discount_type == 'per'){
                $discount =  ( $rows_product->price * $row->discount ) / 100;
                $discount_price = $rows_product->price - $discount;
            }
            else{
                if($rows_product->price < $row->discount) {
                    $msg = $row->discount;
                    die ( $msg);
                }
                $discount_price = $rows_product->price -  $row->discount ;
//                $discount = $row->discount;
            }
        }
        //if coupon code for single product
        else{
            $sql_product_all = "SELECT  sum(price) as price FROM ".$wpdb->prefix."wpsa_product_details WHERE id in ( ".$_POST['product_id']. ")";
            $rows_product_all = $wpdb->get_row($sql_product_all);

            $sql_product = "SELECT price FROM ".$wpdb->prefix."wpsa_product_details WHERE id = ".$row->product_id;
            $rows_product = $wpdb->get_row($sql_product);
            $rows_product_price = $rows_product->price;

            if($row->discount_type == 'per'){
                $discount = ( $rows_product->price * $row->discount ) / 100;
                $discount_price = $rows_product_all->price - $discount;
            }
            else{
                if($rows_product->price < $row->discount) {
                    $msg = $row->discount;
                    die ( $msg);
                }
                $discount = $row->discount;
                $discount_price = $rows_product_all->price -  $row->discount ;
            }
        }

//        $discount = round($discount, 2);

        $product_price = round($rows_product_all->price, 2);
        $discount_price = round($discount_price, 2);
        $discount = $product_price - $discount_price ;

        $msg = $row->product_id.'|' .$product_price. '|' .$discount_price. '|<p> Success! You get a discount of ' .$row->discount.$discount_type.'.</p>|'.$_POST['coupon_code'].'|'.$discount;
        
        die ( $msg);
    }
    die ('0');
}

//to add hidden inputs to paypal product form
add_action('wpsa_product_paypal_form', 'wpsa_coupon_product_paypal_form', 11);

function wpsa_coupon_product_paypal_form() {
    //special case if coupon addon present

    ?><input type="hidden" name="discount_amount_cart" value="<?php echo $_POST['coupon_disc'];?>"><?php
    if($_POST['all_coupon'] != ''){
        ?>
        <input type="hidden" name="os1_1" value="coupon_code_all"/>
        <input type="hidden" name="on1_1" value="<?php echo $_POST['all_coupon'];?>">
        <?php
    }

    else if($_POST['coupon_code'] != '')  {
        $coupon_codes = explode('|', $_POST['coupon_code'] );
        //for coupon code
        if(is_array($coupon_codes)) {
        $coupon_code_count = 1;
            foreach ($coupon_codes as $coupon_code) {
                ?>
                <input type="hidden" name="os1_<?php echo $coupon_code_count?>" value="coupon_code"/>
                <input type="hidden" name="on1_<?php echo $coupon_code_count?>" value="<?php echo $coupon_code;?>">
                <?php
                $coupon_code_count++;
            }
        }
    }
    
}

/**************************************************************
    SHOW NOTIC WHEN WPSA PLUGIN IS ABSENT OR INACTIVE
**************************************************************/
add_action( 'admin_notices', 'wpsa_coupon_notice' );

function wpsa_coupon_notice() {
    global $cache_enabled;
    if (!function_exists('wpsa_install'))
        echo '<div class="error"><p><strong>The WP SalesAutomator plugin must be installed to use the coupon addon.</strong></p></div>';
}
?>