<?php
ob_start();
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
// +----------------------------------------------------------------------+
// | PHP version 4/5                                                      |
// +----------------------------------------------------------------------+
// | This source file is a part of iScripts Multicart                     |
// +----------------------------------------------------------------------+
// | Authors: Programmer<programmer@armia.com>        		              |
// +----------------------------------------------------------------------+
// | Copyrights Armia Systems, Inc and iScripts.com � 2005                |
// | All rights reserved                                                  |
// +----------------------------------------------------------------------+
// | This script may not be distributed, sold, given away for free to     |
// | third party, or used as a part of any internet services such as      |
// | webdesign etc.                                                       |
// +----------------------------------------------------------------------+
?>
<?php
include "../includes/config.php";
include "../includes/session.php";
include "../includes/functions.php";


if (get_magic_quotes_gpc()) {
    $_POST = array_map('stripslashes_deep', $_POST);
    $_GET = array_map('stripslashes_deep', $_GET);
    $_COOKIE = array_map('stripslashes_deep', $_COOKIE); 
} 

if(isset( $_SESSION["sess_adminname"]) and $_SESSION["sess_adminname"]!= ""){
	$adminname = $_SESSION["sess_adminname"];
}else{
	header("Location:login.php");
	exit;
}
$artistlist = makeArtistList();

include "../includes/htmltop.php";

if(trim($_POST['txtCouponStartDate'])<>""){
$txtCouponStartDate=$_POST['txtCouponStartDate'];
$txtCouponStartDate=explode('/',$txtCouponStartDate);
$fromDate=mktime(0, 0, 0, $txtCouponStartDate[0], $txtCouponStartDate[1], $txtCouponStartDate[2]);
}
if(trim($_POST['txtCouponEndDate'])<>""){
$txtCouponEndDate=$_POST['txtCouponEndDate'];
$txtCouponEndDate=explode('/',$txtCouponEndDate);
$toDate=mktime(0, 0, 0, $txtCouponEndDate[0], $txtCouponEndDate[1], $txtCouponEndDate[2]);
$currentDate = mktime(0, 0, 0);
}

$sql    =   "SELECT t1.category_name,t1.category_id  FROM ".$tableprefix."categories AS t1
                    LEFT JOIN ".$tableprefix."categories  as t2 ON t1.category_id = t2.parent_id WHERE t2.category_id IS NULL AND t1.gift_certificate_flag!='Y' order by t1.category_name ";
$rs     =   mysql_query($sql)or die(mysql_error()); 
$num_records    = mysql_num_rows($rs);
 if($num_records>0) { 
     while($row=mysql_fetch_array($rs))
            {
                 $categoryList[$row['category_id']] = getcategoryList($row['category_id']);
            }
            
            asort($categoryList); 
     }
     

$productList = makeProductList();

if(isset($_POST['add']))
{

	/*check whether coupon with the same name exists in the database*/	
 	$select_coupon = "SELECT * FROM ".$tableprefix."couponcode WHERE LOWER(ccCode) = ".GetSQLValueString(strtolower($_POST['txtCouponCode']),"text");
	$result_coupon = mysql_query($select_coupon) or die(mysql_error());
	if(mysql_num_rows($result_coupon)>0)
	{
		$message = CC_EXISTS;
	}
		elseif($fromDate>$toDate)
	{
		$message = END_DATE_ERROR;
	}
	elseif($currentDate>$toDate)
	{
		$message = END_DATE_PASSED_ERROR;
	}
	else
	{										
	$txtCouponStartDate=$_POST['txtCouponStartDate'];
	$txtCouponStartDate=explode('/',$txtCouponStartDate);
	$txtCouponStartDate=$txtCouponStartDate[2]."-".$txtCouponStartDate[0]."-".$txtCouponStartDate[1];
	
	$txtCouponEndDate=$_POST['txtCouponEndDate'];
	$txtCouponEndDate=explode('/',$txtCouponEndDate);
	$txtCouponEndDate=$txtCouponEndDate[2]."-".$txtCouponEndDate[0]."-".$txtCouponEndDate[1];
        
        
        if($_POST['product_id']!=''){
            $product_ids  = implode(',',$_POST['product_id']);
        }else {
            $product_ids ='';
        }
        
         if($_POST['category_id']!=''){
            $product_cat_ids  = implode(',',$_POST['category_id']);
        }else {
            $product_cat_ids ='';
        }

	
 	$insert_gift_coupon = "INSERT INTO ".$tableprefix."couponcode(ccStartDate, ccEndDate, ccCode, ccDescription, ccDiscount,coupon_type,sellerId,categoryId,productId,subscriptionStatus,ccStatus)
										   VALUES(".GetSQLValueString($txtCouponStartDate,"text").","
													.GetSQLValueString($txtCouponEndDate,"text").","
													.GetSQLValueString($_POST['txtCouponCode'],"text").","
													.GetSQLValueString($_POST['txtCouponDescription'],"text").","
													.GetSQLValueString($_POST['txtCouponDiscount'],"text").","
                                                                                                        .GetSQLValueString($_POST['coupon_type'],"text").","
                                                                                                        .GetSQLValueString($_POST['sellerId'],"int").","
                                                                                                        .GetSQLValueString($product_cat_ids,"text").","
                                                                                                        .GetSQLValueString($product_ids,"text").","
                                                                                                        ."'Y','Y')";
																				
                                    mysql_query($insert_gift_coupon) or die(mysql_error());
					
					$insert_id = mysql_insert_id();									
					header('Location:couponCodes.php?msg='.CC_ADDED_SUCC);
					exit();					  
						  
	}						  





}




?>
<script src="../js/calendar2.js"></script>
<script>
    
$(document).ready(function(){
    //Load seller products
    var sellerid =  $("#cmbSeller").val();
    getsellerproducts(sellerid);
    
    $('#cmbSeller').change(function(){
        var sellerid    =   $(this).val();
        getsellerproducts(sellerid);
    });  
    // seller product ends
    
    //Load seller Categories    
    getsellercategories(sellerid);    
    $('#cmbSeller').change(function(){
        var sellerid    =   $(this).val();
        getsellercategories(sellerid);
    });  
    // seller Categories ends    
    
    $('.apply_to').click(function(){
        
        if($('input[name=coupon_type]:checked').val()=="seller"){
            
            $("#product_div").hide();
            $("#category_div").hide();
        }else if($('input[name=coupon_type]:checked').val()=="category"){
            $("#category_div").show();
            
            $("#product_div").hide();
        }else if($('input[name=coupon_type]:checked').val()=="product"){
            $("#product_div").show();
            $("#category_div").hide();
                    
        }
     
        
    });
   
       $("#txtCouponDiscount").keydown(function (e) {
       // Allow: backspace, delete, tab, escape, enter and .
       if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
            // Allow: Ctrl+A
           (e.keyCode == 65 && e.ctrlKey === true) || 
            // Allow: home, end, left, right, down, up
           (e.keyCode >= 35 && e.keyCode <= 40)) {
                // let it happen, don't do anything
                return;
       }
       // Ensure that it is a number and stop the keypress
       if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
           e.preventDefault();
       }
   });
   
});    

function getsellerproducts(sellerid){
    var action='couponcode';
    $.ajax({url: "<?php echo SITE_URL?>/utils.php",
        data :{"action":action,"sellerId":sellerid,"type":"products"},
        success: function(result){
        $("#seller_products").html(result);
    }});
}

function getsellercategories(sellerid){
    var action='couponcode';
    $.ajax({url: "<?php echo SITE_URL?>/utils.php",
        data :{"action":action,"sellerId":sellerid,"type":"category"},
        success: function(result){
        $("#seller_category").html(result);
    }});
}
    
function checkAddCouponForm()
{

  var form_name = new Array('frmAddCoupon');		
  var display_name = new Array('Coupon Name');
  var count = 2;	

  if(check_fields('frmAddCoupon','ccDiscount'))	
  {
  
  	 if(trimSpaces(document.frmAddCoupon.txtCouponCode.value==""))
	 {	 
	 	alert('<?php echo PLS_ENTER_CC;?>');
		document.frmAddCoupon.txtCouponCode.focus();
		return false;		 	 
	 }  
         
         if(trimSpaces(document.frmAddCoupon.txtCouponCode.value)!='')
             {
                
                 if(isSpclChar(trimSpaces(document.frmAddCoupon.txtCouponCode.value)))
                 {
                	alert('<?php echo SPECIAL_CHARA_NOT_ALLOWED;?>');
                     return false;
                 }
             }
        if(trimSpaces(document.frmAddCoupon.sellerId.value==""))
            {	 
                   alert('<?php echo PLS_SELECT_SELLER;?>');
                   document.frmAddCoupon.sellerId.focus();
                   return false;		 	 
            }          
        if($('input[name=coupon_type]:checked').val()=="category"){
           
            var size = $('#category_id option').size();
           
              if(size=='0'){
                     alert('<?php echo PLS_SELECT_CATEGORY;?>');
                     $("#category_id").focus();
                     return false;
               }
            
            
        }else if($('input[name=coupon_type]:checked').val()=="product"){
        
            var size = $('#product_id option').size();
           
              if(size=='0'){
                     alert('<?php echo PLS_SELECT_PRODUCT;?>');
                     $("#product_id").focus();
                     return false;
               }
                   
        }    
    

	
 if(trimSpaces(document.frmAddCoupon.txtCouponStartDate.value==""))
	 {	 
	 alert('<?php echo PLS_START_DATE;?>');
		document.frmAddCoupon.txtCouponStartDate.focus();
		return false;		 	 
	 } 	 
 if(trimSpaces(document.frmAddCoupon.txtCouponEndDate.value==""))
	 {	 
	 alert('<?php echo PLS_END_DATE;?>');
		document.frmAddCoupon.txtCouponEndDate.focus();
		return false;		 	 
	 } 	 	 

 if(!check_numeric(trimSpaces(document.frmAddCoupon.txtCouponDiscount.value)))
	 {
	 
	 alert('<?php echo PLS_ENTER_NUM;?>');
		document.frmAddCoupon.txtCouponDiscount.focus();
		return false;		 
	 
	 }
	 if(trimSpaces(document.frmAddCoupon.txtCouponDiscount.value==""))
	 {	 
		 alert('<?php echo PLS_ENTER_DISCOUNT;?>');
		document.frmAddCoupon.txtCouponDiscount.focus();
		return false;		 	 
	 } 	 
  }
  else
  {
  
  		return false;
  
  }
   
}

</script>

		<body onLoad="document.getElementById('txtCouponCode').focus();">
		
		<center>
		
		<div align="left" id="layout">
		
		
				
				
				<!--header area start -->
<?php

	include_once("../includes/topheader_admin.php")

?>
				
				<!--header area end -->
				
				
				
				
				<div align="left" class="main_body">
				<!--main body start -->
				
				
				
<?php
		include_once("../includes/admintopmenu.php")
?>		
																					
								
					<div align="left" class="content_area">
					
					<!--content area start -->
							
					<div align="left" class="page_title"><?php echo ADD_CC;?></div>
					<div align="center" class="text_information grey_tr"><?php echo $message?></div>
            		<br>
											
					<div align="left">									
															
					<form name="frmAddCoupon" action="#" method="POST" onSubmit="return  checkAddCouponForm();">
					
					<table width="100%" border="0" cellpadding="0" cellspacing="0" class="manage_table">
					
						<tr><td colspan="3">&nbsp;</td></tr>
						
						<tr><td colspan="3" align="right"><span class="required">*</span>&nbsp;<?php echo FIELDS_ARE_MANDATORY;?></td></tr>
						<tr><td width="21%" align="left" valign=top><?php echo COUPON_CODE;?>&nbsp;<span class="required">*</span></td><td width="2%" >&nbsp;</td>
							<td width="77%" align="left" valign=top><input class="textbox" type="text" name="txtCouponCode" id="txtCouponCode" value="<?php echo $_POST['txtCouponCode'];?>" size="25" maxlength="150"></td>
						</tr>
                                                <tr id="seller_div" ><td align="left" ><?php echo SELLER; ?>&nbsp;<span class="required">*</span></td><td >&nbsp;</td>
                                                    <td align="left">
                                                    <?php
                                                    echo makeDropDownList("sellerId",$artistlist, $_POST['sellerId'], false, "textarea", $properties, $behaviors);
                                                    ?>
                                                    </td>
                                                </tr>                                                
                                                <tr><td align="left" ><?php echo COUPON_CODE_TYPE; ?>&nbsp;<span class="required">*</span></td><td >&nbsp;</td>
                                                    <td align="left">
                                                        <input type="radio" class="apply_to" name="coupon_type" value="seller" checked="checked"><?php echo STORE;?>
                                                        <input type="radio" class="apply_to" name="coupon_type" value="category" ><?php echo CATEGORY;?>
                                                        <input type="radio" class="apply_to" name="coupon_type" value="product" ><?php echo PRODUCTS;?>
                                                    </td>
                                                </tr>  
                                                
                                                <tr id="category_div" style="display: none;"><td align="left" ><?php echo CATEGORIES; ?>&nbsp;<span class="required">*</span></td><td >&nbsp;</td>
                                                    <td align="left">
                                                        <div id="seller_category"></div>
                                                    <?php
                                                    //echo makeDropDownList("category_id",$categoryList, $_POST['category_id'], false, "textarea", $properties, $behaviors);
                                                    ?>
                                                    </td>
                                                </tr>   
                                                <tr id="product_div" style="display: none;"><td align="left" ><?php echo PRODUCTS; ?>&nbsp;<span class="required">*</span></td><td >&nbsp;</td>
                                                    <td align="left">
                                                        <div id="seller_products"></div>
                                                    <?php
                                                    //echo makeDropDownList("product_id",$productList, $_POST['product_id'], false, "textarea", $properties, $behaviors);
                                                    ?>
                                                    </td>
                                                </tr>                                                
						<tr>
						  <td align="left" valign=top><?php echo DESCRIPTION;?>&nbsp;</td>
						  <td >&nbsp;</td>
							<td valign=top align="left">
								<textarea name="txtCouponDescription" rows="8" cols="30" class="textbox"><?php echo $_POST['txtCouponDescription'];?></textarea>
							</td>
						</tr>
						<tr><td width="21%" align="left" valign=top><?php echo START_DATE;?>&nbsp;<span class="required">*</span></td><td width="2%" >&nbsp;</td>
							<td width="77%" align="left" valign=top>
<input type="text" name="txtCouponStartDate" class="textbox" readonly="readonly" value="<?php $_POST['txtCouponStartDate'];?>">
										<a href="javascript:cal1.popup();"><img src="../images/cal.gif" width="16" height="16" border="0" Title="Click Here to Pick up From Date"></a>
							</td>
						</tr>	
						<tr><td width="21%" align="left" valign=top><?php echo END_DATE;?>&nbsp;<span class="required">*</span></td><td width="2%" >&nbsp;</td>
							<td width="77%" align="left" valign=top>
							<input type="text" name="txtCouponEndDate" class="textbox" readonly="readonly" value="<?php $_POST['txtCouponEndDate'];?>">
							<a href="javascript:cal2.popup();"><img src="../images/cal.gif" width="16" height="16" border="0" Title="Click Here to Pick up From Date"></a>
							</td>
						</tr>	
						<tr><td width="21%" align="left" valign=top><?php echo DISCOUNT;?>(%) &nbsp;<span class="required">*</span></td><td width="2%" >&nbsp;</td>
							<td width="77%" align="left" valign=top><input class="textbox" type="text" name="txtCouponDiscount" id="txtCouponDiscount" value="<?php echo $_POST['txtCouponDiscount'];?>" size="25" ></td>
						</tr>																	
						<tr>
							<td colspan="3" align="center">
								<input type="button" class="button" name="back" value="&nbsp;<?php echo BACK;?>&nbsp;" onClick="Javascript:history.go(-1)">
								<input type="submit" value="&nbsp;<?php echo ADD_TEXT;?>&nbsp;" name="add" class="button">
							</td>
						</tr>
						<tr><td colspan="3">&nbsp;</td></tr>
					</table>
					
				</form>
				
				</div>
									
				<!--content area end-->
								
				</div>
				
								
					<div align="left" class="clear_float"><img src="<?php echo $imagefolder;?>/clear.gif" alt="" width="1" height="1" /></div>
				<!--main body end -->
				</div>
<script>
 var cal1 = new calendar2(document.forms['frmAddCoupon'].elements['txtCouponStartDate']);
	 cal1.year_scroll = true;
	 cal1.time_comp = false;

var cal2 = new calendar2(document.forms['frmAddCoupon'].elements['txtCouponEndDate']);
	 cal2.year_scroll = true;
	 cal2.time_comp = false;		 	
	 
</script>				
				
<?php
	include "../includes/footer.php";
	
	ob_end_flush();
?>