<?php session_start();
include ('../inc/dbcon.php');
include ('../inc/functions.php');
include ('../inc/cartfunctions.php');
include ('../inc/repfunctions.php');
include ('../inc/invfunctions.php');
if(isset($_SESSION["axeslogin"]) && $_SESSION["axeslogin"] == true){
$_SESSION['cuPages']='pur_pinvcteate.php';   
$cuPage='pur_pinvcteate.php';    
$aid=$_SESSION['uid'];
$brid=$_SESSION['abrid'];    
}else{
header('Location:../index.php');
exit;    
}
$mhead='purchase';
$menuh='Purchase';
$phead='pinvcreate';
$page='Purchase Create';
$dtnow = date("Y-m-d h:i:s", time());
?>
<?php
if(isset($_POST['cancon'])){
if(isset($_SESSION['conpor'])){
unset($_SESSION['conpor']);   
unset($_SESSION['coninv']);
unset($_SESSION['supval']);    
}
if(isset($_SESSION['axes_purchase'])){
unset($_SESSION['axes_purchase']);
unset($_SESSION['axes_purde']);
}
if(isset($_SESSION['axes_purse'])){
unset($_SESSION['axes_purse']);	
}    
echo "<script>window.location='pur_pinvcteate.php'</script>";     
}

if(isset($_POST['conpor']) && isset($_SESSION['conpor']) && $_POST['conpor'] == $_SESSION['conpor']){
$invid=$_POST['conpor'];
$sql="SELECT * FROM tbl_purorder WHERE id='$invid'";
$invdata=mysqli_query($con,$sql)or die(mysqli_error($con));
$inv=mysqli_fetch_array($invdata);	
}elseif(isset($_POST['conpor'])){
$poinv = $_POST['conpor'];
$_SESSION['conpor']=$_POST['conpor'];  
$sql="SELECT * FROM tbl_purorder WHERE id='$poinv'";    
$invdata=mysqli_query($con,$sql)or die(mysqli_error($con));
$inv=mysqli_fetch_array($invdata);
$_SESSION['coninv']=$inv['invno'];

$id=$inv['type'].$inv['supid'];    
$ldebit=get_ledgerval($id,'D','N');
$lcredit=get_ledgerval($id,'C','N');
$lnet=($ldebit-$lcredit);    
$_SESSION['supval']=getfloatval($lnet);
    
if(isset($_SESSION['axes_purchase'])){
unset($_SESSION['axes_purchase']);
unset($_SESSION['axes_purde']);
}

$sql="SELECT * FROM tbl_purorderde WHERE invno='".$inv['invno']."' ORDER BY id ASC";   
$result = mysqli_query($con,$sql) or die(mysqli_error($con));
while ($row=mysqli_fetch_array($result)){
$pid=$row['pid'];
$qty=$row['cuqty'];
$col=$row['colid'];    
$siz=$row['sizid'];
$cost=$row['cuprice'];
$disp=$row['disp'];
$disf=$row['disf'];
$disamo=$row['disamo'];   
addtopur($pid,$qty,$col,$siz,'',$cost,$disp,$disf,$disamo);		
}


if(isset($_SESSION['axes_purchase'])){
$max=count($_SESSION['axes_purchase']);	
if($max>0){
if (!isset($_SESSION['axes_purde'])) {
$_SESSION['axes_purde'] = array();
$_SESSION['axes_purde'][0]['disp']=floatval($inv['disp']);
$_SESSION['axes_purde'][0]['disamo']=floatval($inv['disamo']);    
$_SESSION['axes_purde'][0]['vatp']=floatval($inv['vatp']);
$_SESSION['axes_purde'][0]['vatamo']=floatval($inv['vatamo']);
$_SESSION['axes_purde'][0]['taxp']=floatval($inv['taxp']);
$_SESSION['axes_purde'][0]['taxamo']=floatval($inv['taxamo']);
$_SESSION['axes_purde'][0]['freight']=floatval($inv['freight']);
$_SESSION['axes_purde'][0]['spmony']=floatval($inv['spmoney']);
$_SESSION['axes_purde'][0]['name']=floatval($inv['otname']);
$_SESSION['axes_purde'][0]['others']=floatval($inv['otamo']);
$_SESSION['axes_purde'][0]['less']=floatval($inv['less']);
$_SESSION['axes_purde'][0]['gtotal']=floatval($inv['total']);    
}
}else{
if(isset($_SESSION['axes_purde'])){
unset($_SESSION['axes_purde']);    
}    
}
}

}
?>
<?php
include('../layout/head.php');
include('../layout/header.php');
include('../layout/side_nav.php');
?>

<div class="content-wrapper">
<?php include('../layout/page_head.php'); ?>
<!-- Main content -->
<section class="content">
    
<div class="parent" style="height: 308px;">
    <div class="left leftclose" id="left">
        <div style="width: calc(100% - 25px);">    
            <div class="box box-solid" id="pdpanel" style="display: none;">
                <div class="box-body">
                    <div class="col-md-12">
                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">  
                                    <div class="input-group">
                                        <span class="input-group-addon"><span class="fa fa-search"></span></span>
                                        <input type="text" class="form-control" name="search" id="search" placeholder="e.g. Product Code or Name" autocomplete="off">    
                                    </div>
                                </div>
                                <div class="form-group text-center">
                                    <ul style="margin-top: 0;" class="pagination alphabets"><li><a data-id="" href="#"><b>ALL</b></a></li><li><a href="#" data-id="A"><b>A</b></a></li><li><a href="#" data-id="B"><b>B</b></a></li><li><a href="#" data-id="C"><b>C</b></a></li><li><a href="#" data-id="D"><b>D</b></a></li><li><a href="#" data-id="E"><b>E</b></a></li><li><a href="#" data-id="F"><b>F</b></a></li><li><a href="#" data-id="G"><b>G</b></a></li><li><a href="#" data-id="H"><b>H</b></a></li><li><a href="#" data-id="I"><b>I</b></a></li><li><a href="#" data-id="J"><b>J</b></a></li><li><a href="#" data-id="K"><b>K</b></a></li><li><a href="#" data-id="L"><b>L</b></a></li><li><a href="#" data-id="M"><b>M</b></a></li><li><a href="#" data-id="N"><b>N</b></a></li><li><a href="#" data-id="O"><b>O</b></a></li><li><a href="#" data-id="P"><b>P</b></a></li><li><a href="#" data-id="Q"><b>Q</b></a></li><li><a href="#" data-id="R"><b>R</b></a></li><li><a href="#" data-id="S"><b>S</b></a></li><li><a href="#" data-id="T"><b>T</b></a></li><li><a href="#" data-id="U"><b>U</b></a></li><li><a href="#" data-id="V"><b>V</b></a></li><li><a href="#" data-id="W"><b>W</b></a></li><li><a href="#" data-id="X"><b>X</b></a></li><li><a href="#" data-id="Y"><b>Y</b></a></li><li><a href="#" data-id="Z"><b>Z</b></a></li></ul>    
                                </div>    
                            </div>    
                        </div>
                        <div class="row">
                            <div class="product-panel style-2" id="purchaseitem">

                            </div>
                        </div>
                    </div>    
                    </div>
                </div>
            </div>
            <div class="slide"><div class="vertical-text text-center">PRODUCT PANEL<span class="arrow vertical-text "></span></div></div>
        </div>
      
  
    <div class="right rightexpand" id="right">
            <div class="box box-solid">
                <div class="box-body">
                    <div class="col-md-12">
                        <div class="row">
                            <div class="col-md-8">
                                <div class="form-group">
                                    <div class="input-group">
                                            <span class="input-group-addon"><span class="fa fa-user-o"></span></span>     
                                            <select class="form-control select2" name="supid" id="supid">
                                                <option value="">-Select-</option>
                                                <?php									
                                                $querys=mysqli_query($con,"SELECT * FROM tbl_supplier ORDER BY name ASC")or die(mysqli_error($con));
                                                while ($rows=mysqli_fetch_array($querys)){
                                                ?>
                                                <?php if(isset($_SESSION['conpor'])){?>
                                                <?php if($rows['id']==$inv['supid']){?>
                                                <option selected value="<?php echo 'SU_'.$rows['id'];?>"><?php echo $rows['code'].'-'.$rows['name'];?></option>    
                                                <?php }else{ ?>
                                                <option value="<?php echo 'SU_'.$rows['id'];?>"><?php echo $rows['code'].'-'.$rows['name'];?></option>    
                                                <?php } ?>    
                                                <?php }else{ ?>    
                                                <option value="<?php echo 'SU_'.$rows['id'];?>"><?php echo $rows['code'].'-'.$rows['name'];?></option>
                                                <?php } ?> 
                                                <?php } ?>
                                            </select>
                                            <span class="input-group-addon"><a id="addsup"><span class="fa fa-plus"></span></a></span>    
                                    </div>    
                                </div>    
                            </div>
                            <div class="col-md-4"><span style="font-size: 20px;color: red;font-weight: bold;">Bal.: </span><span style="font-size: 20px;color: blue;font-weight: bold;" id="supbal"><?php if(isset($_SESSION['supval'])){echo $_SESSION['supval'];}else{echo '0.00';}?></span></div>    
                        </div>
                        <div class="row">
                            <div class="col-md-8">
                                <div class="form-group">  
                                    <div class="input-group">
                                        <span class="input-group-addon"><span class="fa fa-search"></span></span>
                                        <input type="text" class="form-control" id="pcode" placeholder="e.g. Product Code or Name" autocomplete="off">   <span class="input-group-addon"><a id="addpro" href='pro_productcreate.php'><span class="fa fa-plus"></span></a></span>  
                                    </div>
                                </div>       
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">  
                                    <div class="input-group">
                                        <span class="input-group-addon"><span class="fa fa-barcode"></span></span>
                                        <input type="text" class="form-control" id="bcode" placeholder="e.g. Barcode" autocomplete="off">   
                                    </div>
                                </div>
                            </div>       
                        </div>
                        
                        <div class="row">
                                <div class="col-md-5">
                                    <div class="form-group">
                                        <div class="input-group">    
                                            <span class="input-group-addon">C</span>     
                                            <select class="form-control" name="colid" id="colid">
                                                <option value="">-Select-</option>
                                                <?php									
                                                $querys=mysqli_query($con,"SELECT * FROM tbl_color ORDER BY name ASC")or die(mysqli_error($con));
                                                while ($col=mysqli_fetch_array($querys)){
                                                ?>
                                                <?php if(isset($_SESSION['axes_purdata']['colid'])){?>
                                                <?php if($col['id']==$_SESSION['axes_purdata']['colid']){?>
                                                <option value="<?php echo $col['id'];?>" style="background-color: <?php echo $col['sval'] ?>;"><?php echo $col['name'];?></option>
                                                <?php }else{ ?>
                                                <option value="<?php echo $col['id'];?>" style="background-color: <?php echo $col['sval'] ?>;"><?php echo $col['name'];?></option>   
                                                <?php } ?>    
                                                <?php }else{ ?>    
                                                <option value="<?php echo $col['id'];?>" style="background-color: <?php echo $col['sval'] ?>;"><?php echo $col['name'];?></option>
                                                <?php } ?> 

                                                <?php } ?>
                                            </select>
                                            <span class="input-group-addon"><a id="addcol"><span class="fa fa-plus"></span></a></span>    
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-5">
                                    <div class="form-group">
                                        <div class="input-group">    
                                            <span class="input-group-addon">S</span>     
                                            <select class="form-control" name="sizid" id="sizid">
                                                <option value="">-Select-</option>
                                                <?php									
                                                $querys=mysqli_query($con,"SELECT * FROM tbl_size ORDER BY id ASC")or die(mysqli_error($con));
                                                while ($siz=mysqli_fetch_array($querys)){
                                                ?>
                                                <?php if(isset($_SESSION['axes_purdata']['colid'])){?>
                                                <?php if($siz['id']==$_SESSION['axes_purdata']['colid']){?>
                                                <option value="<?php echo $siz['id'];?>"><?php echo $siz['name'];?>-<?php echo $siz['sval'] ?></option>
                                                <?php }else{ ?>
                                                <option value="<?php echo $siz['id'];?>"><?php echo $siz['name'];?>-<?php echo $siz['sval'] ?></option>   
                                                <?php } ?>    
                                                <?php }else{ ?>    
                                                <option value="<?php echo $siz['id'];?>"><?php echo $siz['name'];?>-<?php echo $siz['sval'] ?></option>
                                                <?php } ?> 

                                                <?php } ?>
                                            </select>
                                            <span class="input-group-addon"><a id="addsiz"><span class="fa fa-plus"></span></a></span>    
                                        </div>    
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <div class="form-group">
                                        <input type="text" maxlength="5" class="form-control" id="hartz" onkeypress="return isNumberKey(event)" placeholder="e.g. 124Hz" autocomplete="off">   
                                    </div>    
                                </div>    
                        </div>
                        
                        <div class="row">
                            <div class="cart cart-sm">     
                                <table class="table table-bordered table-striped" style="margin-bottom: 0;">
                                    <thead>
                                        <th width="30px">SN</th>
                                        <th width="190px">Item</th>
                                        <th width="60px">Qty</th>
                                        <th width="60px">Cost</th>
                                        <th width="35px">SL/RN</th>    
                                        <th width="65px">SubTotal</th>
                                        <th width="60px">Price</th>
                                        <th width="25px"><a class="empty" style="cursor: pointer;"><i class="fa fa-trash"></i></a></th>    
                                    </thead>
                                </table>
                                <div class="cart-msg style-3 item" style="padding:0px;">    
                                    <table class="table table-bordered table-striped" style="margin-bottom: 0;">    
                                    <tbody id="itemdata">

                                    </tbody>    
                                    </table>
                                </div>
                                <table class="table table-bordered table-striped" style="margin-bottom: 0;">
                                    <tfoot id="itemfoot">

                                    </tfoot>
                                </table>    
                            </div>    
                        </div>
                        
                        <div class="row" id="serialpro">
                            
                            
                        </div>    
                    
                        <div class="row" id="extra">
                        
                        </div>     

                    </div> 

                </div>
            </div>
    </div>

</div>
    
<div class="rotate btn-cat-con">
<button type="button" id="open-brands" class="btn btn-info open-brands" tabindex="-1">Brands</button>
<button type="button" id="open-subcategory" class="btn btn-warning open-subcategory" tabindex="-1">Sub Categories</button>
<button type="button" id="open-category" class="btn btn-primary open-category" tabindex="-1">Categories</button>
</div>
    
<div id="brands-slider">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-search"></span></span>    
<input type="text" class="form-control form-control-lg" id="searchbrands" placeholder="Search by Name" autocomplete="off">
</div>
</div>
</div>    
</div>
<div class="col-md-2"></div>
<div id="brands-list" class="ps-container style-2">
<button id="brand_0" type="button" value="0" class="btn-prni brand" tabindex="-1"><img src="../img/product/no_image.png" class="img-rounded img-thumbnail"><span>ALL Brands</span></button>
<?php
$sql="SELECT * FROM tbl_brand ORDER BY name ASC";	
$query=mysqli_query($con,$sql)or die(mysqli_error($con));
while ($rowc=mysqli_fetch_array($query)){
$id=$rowc['id'];
?>
<button id="brand_<?php echo $rowc['id']?>" type="button" value="<?php echo $rowc['id']?>" class="btn-prni brand" tabindex="-1"><img src="../img/product/<?php if(empty($rowc['image']) || $rowc['image']==''){echo 'no_image.png';}else{echo $rowc['image'];}?>" class="img-rounded img-thumbnail"><span class="bname"><?php echo $rowc['name']?></span></button>    
<?php } ?>
<div class="ps-scrollbar-x-rail" style="width: 0px; display: none; left: 0px; bottom: 3px;"><div class="ps-scrollbar-x" style="left: 0px; width: 0px;"></div></div><div class="ps-scrollbar-y-rail" style="top: 0px; height: 0px; display: none; right: 3px;"><div class="ps-scrollbar-y" style="top: 0px; height: 0px;"></div></div>
</div>
</div>

<div id="category-slider">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-search"></span></span>     
<input type="text" class="form-control form-control-lg" id="searchcategory" placeholder="Search by Name" autocomplete="off">
</div>
</div>
</div>   
<div class="col-md-2"></div>
</div>
<div id="category-list" class="ps-container style-2">
<button id="category_0" type="button" value="0" class="btn-prni category" tabindex="-1"><img src="../img/product/<?php if(empty($rowc['image']) || $rowc['image']==''){echo 'no_image.png';}else{echo $rowc['image'];}?>" class="img-rounded img-thumbnail"><span>All Categories</span></button>
<?php
$sql="SELECT * FROM tbl_category ORDER BY name ASC";	

$query=mysqli_query($con,$sql)or die(mysqli_error($con));
while ($rowc=mysqli_fetch_array($query)){
$id=$rowc['id'];
?>
<button id="category_<?php echo $rowc['id']?>" type="button" value="<?php echo $rowc['id']?>" class="btn-prni category" tabindex="-1"><img src="../img/product/<?php if(empty($rowc['image']) || $rowc['image']==''){echo 'no_image.png';}else{echo $rowc['image'];}?>" class="img-rounded img-thumbnail"><span class="cname"><?php echo $rowc['name']?></span></button>    
<?php } ?>
<div class="ps-scrollbar-x-rail" style="width: 0px; display: none; left: 0px; bottom: 3px;"><div class="ps-scrollbar-x" style="left: 0px; width: 0px;"></div></div><div class="ps-scrollbar-y-rail" style="top: 0px; height: 0px; display: none; right: 3px;"><div class="ps-scrollbar-y" style="top: 0px; height: 0px;"></div></div>
</div>
</div>

<div id="subcategory-slider">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-search"></span></span>     
<input type="text" class="form-control form-control-lg" id="searchsubcategory" placeholder="Search by Name" autocomplete="off">
</div>
</div>   
</div>
<div class="col-md-2"></div>
</div>
<div id="subcategory" class="ps-container style-2">
    
</div>
</div>

<?php include('../layout/quick.php');?>    
</section>
<!-- /.main content -->
<?php include('../layout/rside.php'); ?>
<?php include('../layout/checkout.php'); ?>
<div id="invdata" style="display: none;"></div>
<form action="pur_pinvcteate.php" id="cancon" method="post" >
<input type="hidden" name="cancon" value="0" />
</form>    
</div>
<?php
include('../layout/footer.php');
?>
<!-- page script -->
<script type="text/javascript">
$(document).on('click', '.slide', function () {    
if ($("#left").hasClass("leftopen")) {
$("#pdpanel").fadeOut(700, function() {
$("#pdpanel").css("display", "none");
});    
$("#left").removeClass("leftopen");
$("#right").removeClass("rightopen");
$("#left").addClass("leftclose");
$("#right").addClass("rightexpand");
$(".arrow").addClass("active");
panel_status(0);    
}else{
$("#left").removeClass("leftclose");
$("#right").removeClass("rightexpand");    
$("#left").addClass("leftopen");
$("#right").addClass("rightopen");
$("#pdpanel").fadeIn(700, function() {
$("#pdpanel").css("display", "block");
});
$(".arrow").removeClass("active");
panel_status(1);    
}
ReadItem();    
});    

function panel_status(sval){
$.ajax({
url: "arc_cart.php",
method: "POST",
data:{ 
purpan:1, skey:'PURPAN', sval:sval
},
success: function(data){

}
});    
}    
    
$(function(){
var divHeight = $(".parent").height();    
$('.parent').css({ height: $(window).innerHeight()-150 });
$('.product-panel').css({ height: $('.parent').innerHeight()-118 });    
$(window).resize(function(){
$('.parent').css({ height: $(window).innerHeight()-150 });
$('.product-panel').css({ height: $('.parent').innerHeight()-118 });    
});
});    
     
   
    
function take_action(id) {
document.getElementById(id).submit(); 
}    
    
ReadItem();
    
function ReadItem() {
$.ajax({
url: "pur_item.php",
method: "POST",
success: function(data) {
$('#purchaseitem').html(data);
}
})
}

ReadData();
function ReadData(){
$.ajax({
url: "pur_invview.php",
method: "POST",
data:{ 
body:1
},
success: function(data){
$('#itemdata').html(data);
}
})

$.ajax({
url: "pur_invview.php",
method: "POST",
data:{ 
foot:1
},
success: function(data){
$('#itemfoot').html(data);
}
})
ReadButon();    
ReadIMEI();    
};    

function ReadFoot(){
$.ajax({
url: "pur_invview.php",
method: "POST",
data:{ 
foot:1
},
success: function(data){
$('#itemfoot').html(data);
}
})	
}    

function ReadButon(){
$.ajax({
url: "pur_invview.php",
method: "POST",
data:{ 
buton:1
},
success: function(data){
$('#extra').html(data);
}
})	
}     
    
function ReadIMEI() {
$.ajax({
url: "pur_serialview.php",
method: "POST",
success: function(data) {
$('#serialpro').html(data);
}
})
}    
    
var search = $("#search").on('input',function(){
var matcher = new RegExp($(this).val(), 'i');

$('.puritem').show().not(function(){
return matcher.test($(this).find('.name, .sku').text())
}).hide();
}); 

$(document).on('click', '.alphabets a', function () {
si=$(this).data('id');
var matcher = new RegExp(si, 'i');

$('.puritem').show().not(function(){
return matcher.test($(this).find('.indexg').text())
}).hide();   
});

$(document).on('keyup', '#searchcategory', function () {
var search = $("#searchcategory").on('input',function(){
var matcher = new RegExp($(this).val(), 'i');

$('.category').show().not(function(){
return matcher.test($(this).find('.cname').text())
}).hide();
})
});

$(document).on('keyup', '#searchsubcategory', function () {
var search = $("#searchsubcategory").on('input',function(){
var matcher = new RegExp($(this).val(), 'i');

$('.subcat').show().not(function(){
return matcher.test($(this).find('.sname').text())
}).hide();
})
});

$(document).on('keyup', '#searchbrands', function () {
var search = $("#searchbrands").on('input',function(){
var matcher = new RegExp($(this).val(), 'i');

$('.brand').show().not(function(){
return matcher.test($(this).find('.bname').text())
}).hide();
})
});

$(".open-brands").click(function () {
$('#brands-slider').toggle('slide', { direction: 'right' }, 700);
});
$(".open-category").click(function () {
$('#category-slider').toggle('slide', { direction: 'right' }, 700);
});
$(".open-subcategory").click(function () {
$('#subcategory-slider').toggle('slide', { direction: 'right' }, 700);
});
    
$(document).on('click', function(e){
if (!$(e.target).is(".open-brands, .cat-child") && !$(e.target).parents("#brands-slider").length && $('#brands-slider').is(':visible')) {
$('#brands-slider').toggle('slide', { direction: 'right' }, 700);
}
if (!$(e.target).is(".open-category, .cat-child") && !$(e.target).parents("#category-slider").length && $('#category-slider').is(':visible')) {
$('#category-slider').toggle('slide', { direction: 'right' }, 700);
}
if (!$(e.target).is(".open-subcategory, .cat-child") && !$(e.target).parents("#subcategory-slider").length && $('#subcategory-slider').is(':visible')) {
$('#subcategory-slider').toggle('slide', { direction: 'right' }, 700);
}
if (!$(e.target).is(".right-side-add, .side-cont") && !$(e.target).parents(".right-side-add").length && $('.right-side-add').hasClass('open-right-add')) {
if($('.right-side-add').is(':visible')) { $('.right-side-add').toggle('slide', { direction: 'right' }, 300); }
$('#addsitem').html('');
}    
});
    
$(document).on('click', '.category', function () {
id_arr = $(this).attr('id');
id = id_arr.split("_");
var ids = id[1];
$.ajax({
url: 'pur_item.php',
method: "POST",
data:{ 
catid: ids
},
success: function(data){
$('#purchaseitem').html(data);
}
});
    
$.ajax({
url: 'pur_subcat.php',
method: "POST",
data:{ 
catid: ids
},
success: function(data){
$('#subcategory').html(data);
}
});    
});
    
$(document).on('click', '.subcat', function () {
sid_arr = $(this).attr('id');
sid = sid_arr.split("_");    
var scid = sid[1];
$.ajax({
url: 'pur_item.php',
method: "POST",
data:{ 
subcatid: scid
},
success: function(data){
$('#purchaseitem').html(data);
}
});    
});
    
$(document).on('click', '.brand', function () {
sid_arr = $(this).attr('id');
sid = sid_arr.split("_");    
var brid = sid[1];
$.ajax({
url: 'pur_item.php',
method: "POST",
data:{ 
brandid: brid
},
success: function(data){
$('#purchaseitem').html(data);
}
});    
});
    
$(document).on('click', '#icon', function() {
if(!$("#icon").hasClass('cart-icon-rotate')){
$("#icon").addClass('cart-icon-rotate');
$(".cart tr.dshow").toggle();
}else{
$("#icon").removeClass('cart-icon-rotate');	
$(".cart tr.dshow").hide();
}	
});

$(document).on('click', '.puritem', function () {
var col=$('#colid').val();
var siz=$('#sizid').val();    
var id = $(this).attr('id');
pid_arr = $(this).attr('id');
pid = pid_arr.split("_");    
var gid = pid[1];
    
$.ajax({
url: 'pur_cart.php',
method: "POST",
data:{ 
additem: gid, col:col, siz:siz
},
success: function(data){
ReadData();
}
});    
});




$(document).on('keydown', '#pcode', function () {
var itCOL = document.getElementById("colid");
var itSIZ = document.getElementById("sizid");
   
var col=''; var siz='';
if(itCOL){
col=$('#colid').val();	
}else{
col='';	
}

if(itSIZ){
siz=$('#sizid').val();	
}else{
siz='';	
}    

$('#pcode' ).autocomplete({
    source: function( request, response ) {
        $.ajax({
            url: 'pur_cart.php',
            type: 'post',
            dataType: 'json',
            data: {
                search: request.term,itmsear:1
            },
            success: function(data) {
                response(data);
            }
        });
    }, 
    focus: function(event, ui) {
            // Prevent the input field from being updated with raw HTML
            event.preventDefault();
    },
    select: function (event, ui) {
        var te='';
        $(this).val(te); // display the selected text
        var pid = ui.item.value; // selected id to input

        var myEle = document.getElementById("hartz");
        if(myEle){
            var hz= myEle.value;
        }else{
            var hz='';	
        }

        $.ajax({
            url: 'pur_cart.php',
            type: 'post',
            data: {additem:pid, col:col, siz:siz},
            success:function(response){
                ReadData();
            }
        });
        return false;
    }
}).autocomplete("instance")._renderItem = function(ul, item) {
        // Render the item with HTML
        return $("<li>")
            .append('<div><strong>' + item.label + '</strong> <br>' +
                    '<small><b> Cost: ' + item.cost + '</b></small> | ' +
                    '<small> Unit: ' + item.unit + '</small> | ' + '</div>')
            .appendTo(ul);
    };        
});    


    
$(document).on('click', '.remove', function () {
var id = $(this).attr('id');
$.ajax({
url: 'pur_cart.php',
method: "POST",
data:{ 
remove: id
},
success: function(data){
ReadData();
}
});    
});

//barcode 
var bscode='';   
$(document).scannerDetection({
timeBeforeScanTest: 200,
//startChar: [120],
endChar: [13],
avgTimeByChar: 30,
onComplete: function(barcode,event){ 
bscode = barcode; 
$('#bcode').val(bscode);
    
var bsid = 0;
if ($('.bscan').is(":checked")){
bsid = $('.bscan:checked').val();
}else{
bsid = 0;	
}
	
$.ajax({
url: 'pur_cart.php',
method: "POST",
data:{ 
scanbarcode: bscode , qty: 1, mod:bsid
},
dataType: 'json',    
success: function(data){       
$('#bcode').val('');
if(data.status==='fail'){
toastr.info(data.message);
}else if(data.status==='invno'){
viewinvoice(data.invoice);    
}else if(data.status==='bcode'){
toastr.warning(data.message);	
}else if(data.status==='exits'){
toastr.info(data.message);	
}else if(data.status==='success'){     
ReadData();
toastr.success(data.message);    
}
}
});	
bscode='';        
},
onKeyDetect: function(event){
if(event.keyCode === 13 || event.keyCode === 17 || event.keyCode === 74 ){
if (event.target.tagName == "INPUT" || event.target.tagName == "TEXTAREA") {
if(bscode.length>1){
event.preventDefault();    
}    
}else{
event.preventDefault();    
}  
}
}   
});    

function viewinvoice(invno){
$.ajax({
url: 'axe_globalview.php',
method: "POST",
data:{sbcode: invno},
success: function(data){
var foundSomething = false;
for(var i=0; i<data.length; ++i) {
if(data[i] !== null) foundSomething = true;
break;
}    
if(foundSomething){
$('#datacon').html(data);   
$('.right-side-free').toggle('slide', { direction: 'right' }, 300);
}
}
});    
}    
    
$(document).on('blur', '.quantity', function() {
id_arr = $(this).attr('id');
id = id_arr.split("_");
var ids = id[1];
var qty = parseFloat($('#qty_'+id[1]).val());
$.ajax({
url: 'pur_cart.php',
method: "POST",
data:{ 
upqty: ids, qty: qty
},
dataType: 'json',
success: function(data){
$('#qty_'+id[1]).val(data[0]);
$('#cost_'+id[1]).val(data[1]);
$('#stotal_'+id[1]).html(data[5]);    
$('#disp_'+id[1]).val(data[2]);
$('#disf_'+id[1]).val(data[3]);
$('#disamo_'+id[1]).html(data[9]);    
$('#wdays_'+id[1]).val(data[4]);
$('#price_'+id[1]).val(data[6]);
$('#sdisp_'+id[1]).val(data[7]);
$('#sdisf_'+id[1]).val(data[8]);    
ReadFoot();
ReadIMEI();    
}
});     
});
    
$(document).on('blur', '.cost', function() {
id_arr = $(this).attr('id');
id = id_arr.split("_");
var ids = id[1];
var amo = parseFloat($('#cost_'+id[1]).val());
$.ajax({
url: 'pur_cart.php',
method: "POST",
data:{ 
upcost: ids, amo: amo
},
dataType: 'json',
success: function(data){
$('#qty_'+id[1]).val(data[0]);
$('#cost_'+id[1]).val(data[1]);
$('#stotal_'+id[1]).html(data[5]);    
$('#disp_'+id[1]).val(data[2]);
$('#disf_'+id[1]).val(data[3]);
$('#disamo_'+id[1]).html(data[9]);    
$('#wdays_'+id[1]).val(data[4]);
$('#price_'+id[1]).val(data[6]);
$('#sdisp_'+id[1]).val(data[7]);
$('#sdisf_'+id[1]).val(data[8]); 
ReadFoot();
}
});     
});

$(document).on('change', '.bscan', function () {
id_arr = $(this).attr('id');
id = id_arr.split("_");
var ids = id[1];
var chkid = 0;	
$('.bscan').not(this).prop('checked', false);
if ($('.bscan').is(":checked")){
chkid = 1;
}else{
chkid = 0;	
}

$.ajax({
url: 'pur_cart.php',
method: "POST",
data: {
check: chkid, pid:ids
},
success: function(data) {
ReadData();
}
});

});    




$(document).on('change', '.rscan', function () {
id_arr = $(this).attr('id');
id = id_arr.split("_");
var ids = id[1];
var chkid = 0;	
$('.rscan').not(this).prop('checked', false);
if ($('.rscan').is(":checked")){
chkid = 1;
}else{
chkid = 0;	
}

$.ajax({
url: 'pur_cart.php',
method: "POST",
data: {
rcheck: chkid, pid:ids
},
success: function(data) {
ReadData();
}
});

}); 



$(document).on('blur', '.rstart', function () {
var srstart = $('#rstart').val();
$.ajax({
url: 'pur_cart.php',
method: "POST",
data: {
    uprstart: srstart
},
dataType: 'json',
success: function(data) {
ReadIMEI();
}
});

}); 


    
$(document).on('blur', '.price', function() {
id_arr = $(this).attr('id');
id = id_arr.split("_");
var ids = id[1];
var amo = parseFloat($('#price_'+id[1]).val());
$.ajax({
url: 'pur_cart.php',
method: "POST",
data:{ 
upprice: ids, amo: amo
},
dataType: 'json',
success: function(data){
$('#qty_'+id[1]).val(data[0]);
$('#cost_'+id[1]).val(data[1]);
$('#stotal_'+id[1]).html(data[5]);    
$('#disp_'+id[1]).val(data[2]);
$('#disf_'+id[1]).val(data[3]);
$('#disamo_'+id[1]).html(data[9]);    
$('#wdays_'+id[1]).val(data[4]);
$('#price_'+id[1]).val(data[6]);
$('#sdisp_'+id[1]).val(data[7]);
$('#sdisf_'+id[1]).val(data[8]);
ReadFoot();
}
});     
});
    
$(document).on('blur', '.disp', function() {
id_arr = $(this).attr('id');
id = id_arr.split("_");
var ids = id[1];
var dic = parseFloat($('#disp_' + id[1]).val());
$.ajax({
url: 'pur_cart.php',
method: "POST",
data: {
itemdisp: ids,
disp: dic
},
dataType: 'json',
success: function(data) {
$('#qty_'+id[1]).val(data[0]);
$('#cost_'+id[1]).val(data[1]);
$('#stotal_'+id[1]).html(data[5]);    
$('#disp_'+id[1]).val(data[2]);
$('#disf_'+id[1]).val(data[3]);
$('#disamo_'+id[1]).html(data[9]);    
$('#wdays_'+id[1]).val(data[4]);
$('#price_'+id[1]).val(data[6]);
$('#sdisp_'+id[1]).val(data[7]);
$('#sdisf_'+id[1]).val(data[8]);
ReadFoot();
}
});
});
    
$(document).on('blur', '.disf', function() {
id_arr = $(this).attr('id');
id = id_arr.split("_");
var ids = id[1];
var dica = parseFloat($('#disf_' + id[1]).val());
$.ajax({
url: 'pur_cart.php',
method: "POST",
data: {
itemdisf: ids,
disf: dica
},
dataType: 'json',
success: function(data) {
$('#qty_'+id[1]).val(data[0]);
$('#cost_'+id[1]).val(data[1]);
$('#stotal_'+id[1]).html(data[5]);    
$('#disp_'+id[1]).val(data[2]);
$('#disf_'+id[1]).val(data[3]);
$('#disamo_'+id[1]).html(data[9]);    
$('#wdays_'+id[1]).val(data[4]);
$('#price_'+id[1]).val(data[6]);
$('#sdisp_'+id[1]).val(data[7]);
$('#sdisf_'+id[1]).val(data[8]);
ReadFoot();
}
});
});
    
$(document).on('blur', '.wdays', function() {
id_arr = $(this).attr('id');
id = id_arr.split("_");
var ids = id[1];
var wday = parseFloat($('#wdays_'+id[1]).val());
$.ajax({
url: 'pur_cart.php',
method: "POST",
data:{ 
warranty: ids, wday: wday
},
dataType: 'json',
success: function(data){
$('#qty_'+id[1]).val(data[0]);
$('#cost_'+id[1]).val(data[1]);
$('#stotal_'+id[1]).html(data[5]);    
$('#disp_'+id[1]).val(data[2]);
$('#disf_'+id[1]).val(data[3]);
$('#disamo_'+id[1]).html(data[9]);    
$('#wdays_'+id[1]).val(data[4]);
$('#price_'+id[1]).val(data[6]);
$('#sdisp_'+id[1]).val(data[7]);
$('#sdisf_'+id[1]).val(data[8]);
ReadFoot();
}
});     
});
    
$(document).on('blur', '.sdisp', function() {
id_arr = $(this).attr('id');
id = id_arr.split("_");
var ids = id[1];
var per = parseFloat($('#sdisp_'+id[1]).val());
$.ajax({
url: 'pur_cart.php',
method: "POST",
data:{ 
seldisp: ids, per: per
},
dataType: 'json',
success: function(data){
$('#qty_'+id[1]).val(data[0]);
$('#cost_'+id[1]).val(data[1]);
$('#stotal_'+id[1]).html(data[5]);    
$('#disp_'+id[1]).val(data[2]);
$('#disf_'+id[1]).val(data[3]);
$('#disamo_'+id[1]).html(data[9]);    
$('#wdays_'+id[1]).val(data[4]);
$('#price_'+id[1]).val(data[6]);
$('#sdisp_'+id[1]).val(data[7]);
$('#sdisf_'+id[1]).val(data[8]);
ReadFoot();
}
});     
});
    
$(document).on('blur', '.sdisf', function() {
id_arr = $(this).attr('id');
id = id_arr.split("_");
var ids = id[1];
var per = parseFloat($('#sdisf_'+id[1]).val());
$.ajax({
url: 'pur_cart.php',
method: "POST",
data:{ 
seldisf: ids, per: per
},
dataType: 'json',
success: function(data){
$('#qty_'+id[1]).val(data[0]);
$('#cost_'+id[1]).val(data[1]);
$('#stotal_'+id[1]).html(data[5]);    
$('#disp_'+id[1]).val(data[2]);
$('#disf_'+id[1]).val(data[3]);
$('#disamo_'+id[1]).html(data[9]);    
$('#wdays_'+id[1]).val(data[4]);
$('#price_'+id[1]).val(data[6]);
$('#sdisp_'+id[1]).val(data[7]);
$('#sdisf_'+id[1]).val(data[8]);
ReadFoot();
}
});     
});
    
function get_foot(){
$.ajax({
url: 'pur_cart.php',
method: "POST",
data: {
foot: 1
},
dataType: 'json',
success: function(data) {	
$('#discount').val((Math.round(data[0] * 100) / 100).toFixed(2));
$('#disitems').html((Math.round(data[1] * 100) / 100).toFixed(2));
if(parseFloat(data[2])>0){
$('#totdisamo').html((Math.round(data[2] * 100) / 100).toFixed(2));
}
$('#vatp').val((Math.round(data[3] * 100) / 100).toFixed(2));
$('#vatamo').html((Math.round(data[4] * 100) / 100).toFixed(2));

$('#taxp').val((Math.round(data[8] * 100) / 100).toFixed(2));
$('#taxamo').html((Math.round(data[9] * 100) / 100).toFixed(2));
    
$('#speed').val((Math.round(data[10] * 100) / 100).toFixed(2));
$('#spmoney').html((Math.round(data[10] * 100) / 100).toFixed(2));
    
$('#others').val(data[11]);
$('#othersamo').html((Math.round(data[11] * 100) / 100).toFixed(2));
    
$('#otdname').html(data[12]);

$('#freight').val((Math.round(data[5] * 100) / 100).toFixed(2));
$('#freightd').html((Math.round(data[5] * 100) / 100).toFixed(2));
$('#less').val((Math.round(data[6] * 100) / 100).toFixed(2));
$('#lessd').html((Math.round(data[6] * 100) / 100).toFixed(2));
$('#grtotal').html((Math.round(data[7] * 100) / 100).toFixed(2));
}
});	
}

$(document).on('blur', '#discount', function() {
var disp = parseFloat($('#discount').val());
$.ajax({
url: 'pur_cart.php',
method: "POST",
data: {
purdis: disp
},
success: function(data) {
get_foot();
}
});
});
    
$(document).on('blur', '#vatp', function() {
var vatp = parseFloat($('#vatp').val());
$.ajax({
url: 'pur_cart.php',
method: "POST",
data: {
purvat: vatp
},
success: function(data) {
get_foot();
}
});
});
    
$(document).on('blur', '#taxp', function() {
var taxp = parseFloat($('#taxp').val());
$.ajax({
url: 'pur_cart.php',
method: "POST",
data: {
purtax: taxp
},
success: function(data) {
get_foot();
}
});
});
    
$(document).on('blur', '#others', function() {
var others = parseFloat($('#others').val());
$.ajax({
url: 'pur_cart.php',
method: "POST",
data: {
others: others
},
success: function(data) {
get_foot();
}
});
});

$(document).on('blur', '#otname', function() {
var otname = $('#otname').val();
$.ajax({
url: 'pur_cart.php',
method: "POST",
data: {
otname: otname
},
success: function(data) {
get_foot();
}
});
});
    
$(document).on('blur', '#speed', function() {
var sped = parseFloat($('#speed').val());
$.ajax({
url: 'pur_cart.php',
method: "POST",
data: {
spmoney: sped
},
success: function(data) {
get_foot();
}
});
});
    
$(document).on('blur', '#freight', function() {
var frei = parseFloat($('#freight').val());
$.ajax({
url: 'pur_cart.php',
method: "POST",
data: {
freight: frei
},
success: function(data) {
get_foot();
}
});
});				
				
$(document).on('blur', '#less', function() {
var less = parseFloat($('#less').val());
$.ajax({
url: 'pur_cart.php',
method: "POST",
data: {
less: less
},
success: function(data) {
get_foot();
}
});
});
        
$(document).on('click', '.slremove', function () {
var id = $(this).attr('id');
$.ajax({
url: 'pur_cart.php',
method: "POST",
data:{ 
removeitmsl: id
},
success: function(data){
ReadData();
}
});    
});
    
$(document).on('blur', '.imei', function() {
id_arr = $(this).attr('id');
id = id_arr.split("_");
var ids = id[1];
var imei = $('#imei_'+id[1]).val();
$.ajax({
url: 'pur_cart.php',
method: "POST",
data:{ 
upimei: ids, imeidata: imei
},
dataType: 'json',
success: function(data){
$('#imei_'+id[1]).val(data[0]);
//ReadData();
}
});     
});

$(document).on('keypress', '.imei', function(event) {
id_arr = $(this).attr('id');
id = id_arr.split("_");
var ids = id[1];
var imei = $('#imei_'+id[1]).val();
	
if (event.keyCode == 13 || event.which == 13){
var bsid = 0;
if ($('.bscan').is(":checked")){
bsid = $('.bscan:checked').val();
}else{
bsid = 0;
}

$.ajax({
url: 'pur_cart.php',
method: "POST",
data:{ 
typeserial: imei , qty: 1, mod:bsid
},
dataType: 'json',
success: function(data){
ReadData();
fid=parseFloat(data[0]-1);
setTimeout(function() {$('#imei_'+fid).focus() }, 500);
}
});

}
});
    
$(document).on('click', '#emptycart', function () {
var id = $(this).attr('id');    
$.ajax({
url: 'pur_cart.php',
method: "POST",
data:{ 
clear: id
},
success: function(data){
ReadData();
}
});    
});
    
$(document).on('change', '#supid', function () {
var id = $(this).val();     
$.ajax({
url: 'pur_cart.php',
method: "POST",
data:{ 
supbal: id
},
success: function(data){
$('#supbal').html(data);
}
});    
}); 

$(document).on('click', '#addsup', function() {
$('#addsitem').html('');    
$.ajax({
url: "axe_additem.php",
method: "POST",
data:{addsup:1},
success: function(data){
$('#addsitem').html(data);
$('.right-side-add').toggle('slide', { direction: 'right' }, 300);     
}
})       
});    
    
$(document).on('click', '#save_purchase', function() {
var supid = $('#supid').val(); 
toastr.options = {'positionClass': 'toast-top-center'};    
$.ajax({
url: 'pur_cart.php',
method: "POST",
data:{ 
purdata:1
},
dataType: 'json',
success: function(response) {

if(supid == '-Select-' || supid == ''){
toastr.info('Please Select Supplier!');
return;
}    
    
//var itc = response[0];
//var prc = response[1];
//var imc = response[2];
//var ime = response[3];
//var emt = response[4];
//var spc = response[5];
//
//if(itc!=prc){
//toastr.warning('Missing Cost Information!!')	
//return;
//}
//    
//if(itc!=spc){
//toastr.warning('Missing Sales Price Information!!')	
//return;
//}
//
//if(imc!=ime){
//toastr.warning('Missing IMEI / Serial Information!!')	
//return;	
//}
//if(emt>0){
//toastr.warning('Missing IMEI Information!!')	
//return;	
//}    
if(response.status !== 'ok'){
toastr.error(response.message);
return;    
}    
pursave();    
}
});          
});       

function pursave(){
var supid = $('#supid').val();    

$.ajax({
url: "pur_cart.php",
method: "POST",
data:{checkview:1,cusid:supid},
success: function(data){
$('#checkview').html('');
$('#checkview').html(data); 
}
})    
    
$.ajax({
url: "pur_cart.php",
method: "POST",
data:{checkout:1,cusid:supid},
success: function(data){
$('#invhold').html('');
$('#invhold').html(data);       
}
})
$('.right-side-checkout').addClass('open-right-checkout');     
}    

$(document).on('click', '#closechk', function() {
$('.right-side-checkout').removeClass('open-right-checkout');
$('#addsitem').html('');    
});    
    
$(document).on('click', '#closepop', function() {    
if($('.right-side-add').is(':visible')) { $('.right-side-add').toggle('slide', { direction: 'right' }, 300); }
$('#addsitem').html('');    
});
    
$(document).on('click', '.saveseinv', function() {
var stype = $(this).attr('id');
var cash_data = $('.addpurchase input, .addpurchase select, .addpurchase textarea');    
toastr.options = {'positionClass': 'toast-top-center'};    
    
if(!chek_error()){return;}
    
$.ajax({
url: "pur_cart.php",
data: cash_data,
type: 'post',
dataType: 'json',    
success: function(data){
if(data.status === "success"){
$('.right-side-checkout').removeClass('open-right-checkout');
$('#addsitem').html('');
$("#supid").val("").trigger("change");
$("#supbal").html('0.00');
ReadItem();    
ReadData();    
toastr.success(data.message);
if(stype!='saveinv'){
print_inv(data.invid,stype);       
}    
}else{
toastr.error(data.message);    
}         
}
})    
    
});

function print_inv(id,key){
var mode = 'iframe'; //popup
var close = mode == "popup";
var options = {
mode: mode,
popClose: close
};    
$.ajax({
url: "pur_print.php",
data:{print:id,key:key}, 
type: 'post',    
success: function(data){
$("#invdata").html(data);    
$("div.printableArea").printArea(options);
$("#invdata").html('');    
}
})    
};    
</script>    
<!-- /page script -->
</html>    