<?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){    
$aid=$_SESSION['uid'];
$brid=$_SESSION['abrid'];    
$today = strftime("%Y-%m-%d", time());    
$dtnow = date("Y-m-d h:i:s", time());    
}else{
header('Location:../index.php');
exit;    
}

if(isset($_POST['additem'])){
$id=$_POST['additem'];   
addbadclim($id);    
}

if(isset($_POST['remove'])){
$ids = floatval($_POST['remove']);  
remove_badstclaim($ids);
$max=count($_SESSION['axes_badstclaim']);
if($max <= 0){
unset($_SESSION['axes_badstclaim']);	
}
}

if(isset($_POST['clear'])){
if(isset($_SESSION['axes_badstclaim'])){
unset($_SESSION['axes_badstclaim']);   
}
}

if(isset($_POST['upimei'])){
$imei=strtoupper(remove_junk(escape($_POST['imeidata'])));   
if(check_eximei($imei)){
$redata='';
}else{
$redata=$imei;    
}
echo $redata;   
}

if(isset($_POST['addclaim'])){
$invno = gen_newinvno('tbl_badstockclaim','BSC');
$note = remove_junk(escape($_POST['note']));    
$apdate = remove_junk(escape($_POST['cladt']));
    
if(!isset($_SESSION['axes_badstclaim'])){
echo json_encode(array(
'status' => 'error',
'message'=> 'Sorry! No item found!!'
));
return;
exit;  
}

$supid=get_warrantyinfo($_SESSION['axes_badstclaim'][0]['id'],'supid');    
    
$sql="INSERT INTO tbl_badstockclaim (invno,type,supid,amount,note,apdate,brid,uid,date) VALUES ('$invno','SU','$supid','0','$note','$apdate','$brid','$aid','$dtnow')";
$result = mysqli_query($con,$sql) or die(mysqli_error($con));
$sid=$con->insert_id;    
$efid=mysqli_affected_rows($con);     
if($efid>0){
$max=count($_SESSION['axes_badstclaim']);
for($i=0;$i<$max;$i++){
$id=$_SESSION['axes_badstclaim'][$i]['id'];    
$sql="UPDATE tbl_waranty SET b_out='1',binvno='$invno' WHERE id='$id'";
$result = mysqli_query($con,$sql) or die(mysqli_error($con));    
}
    
unset($_SESSION['axes_badstclaim']);
          
$act =remove_junk(escape('Claim No: '.$invno));    
write_activity($aid,'BSC','New bad stock claim has been Created',$act);
echo json_encode(array(
'status' => 'success',
'message'=> 'Claim Save Successfully!!'   
));
exit;    
}else{
echo json_encode(array(
'status' => 'error',
'message'=> 'Sorry! Data Fail to Saved!!'
));    
}    
}

if(isset($_POST['badclrec'])){
$dtot=0;
$invno='';    
if(isset($_POST['data']) && !empty($_POST['data'])){
$deitems=$_POST['data'];
foreach($deitems as $item){
$id = remove_junk(escape($item['id']));    
$srl = remove_junk(escape($item['newserial']));
$amo = remove_junk(escape($item['amount']));    
if($srl!='' || $amo>0){
$dtot+=1;    
}else{
$dtot+=0;    
}    
}       
}

if($dtot<=0){
echo json_encode(array(
'status' => 'error',
'message'=> 'Sorry! No item found!!'
));
return;
exit;  
}    

foreach($deitems as $item){
$id = remove_junk(escape($item['id']));    
$srl = remove_junk(escape($item['newserial']));
$amo = remove_junk(escape($item['amount']));
if($amo=='' || $amo<=0){$amo=0;}     
$cty = 'SU';
$cid = get_productinfo($id,'supid');
$invno = get_productinfo($id,'binvno');
$pid = get_productinfo($id,'pid');
$unqid = get_productinfo($id,'unqid');
$col = get_productinfo($id,'colid');  
$siz = get_productinfo($id,'sizid');
$ibrid = get_productinfo($id,'brid');
    
$purinv = get_salesinfo($unqid,'invno');    
$icdis = get_salesinfo($unqid,'icdis');
$icinvdis = get_salesinfo($unqid,'icinvdis');
$cost = get_salesinfo($unqid,'cost');
    
if($srl!=''){    
$sql="INSERT INTO tbl_traproduct (type,tid,invno,refinv,pid,unqid,colid,sizid,icdis,icinvdis,cost,price,p_qty,p_in,s_qty,p_out,taxp,taxamo,disp,disf,disamo,subtot,wday,mods,brid,waid,tramod,isinv,pnote,uid,apdate,date) VALUES ('$cty','$cid','$invno',NULL,'$pid','$unqid','$col','$siz','$icdis','$icinvdis','$cost','0','0','1','0','0','0','0','0','0','0','0','0','WR','$ibrid',NULL,NULL,'Y',NULL,'$aid','$today','$dtnow')";
mysqli_query($con,$sql) or die(mysqli_error($con));

$sql="UPDATE tbl_waranty SET sat_amount='0',bst='1',bsrserial='$srl' WHERE id='$id'";
mysqli_query($con,$sql) or die(mysqli_error($con));
    
$ducode = mysqli_query($con,"SELECT * FROM tbl_serial WHERE serial = '$srl'");
if($ducode->num_rows > 0) {
    
}else{
$sql="INSERT INTO tbl_serial (purinv,pid,unqid,serial,rci,rcno,brid,whid,status) VALUES ('$purinv','$pid','$unqid','$srl','Y','$invno','$ibrid',NULL,'0')";
mysqli_query($con,$sql) or die(mysqli_error($con));    
}         
}   
if($amo>0){    
$sql="UPDATE tbl_waranty SET sat_amount='$amo',bst='1' WHERE id='$id'";
mysqli_query($con,$sql) or die(mysqli_error($con));    
}         
}
if($dtot>1){
$act =remove_junk(escape('Warranty Received: '.$invno));    
write_activity($aid,'BSC','Warranty Bad Stock Claim has been received!!',$act);    
echo json_encode(array(
'status' => 'success',
'message'=> 'Data Save Successfully!!'   
));
exit;
}else{
echo json_encode(array(
'status' => 'error',
'message'=> 'Sorry! Data Fail to Save!!'
));    
}            
}

function get_productinfo($id,$key){
global $con;
$sql="SELECT ".$key." AS rdata FROM tbl_waranty WHERE id='$id'"; 
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
$row=mysqli_fetch_array($result);
return $row['rdata'];    
}
?>

<?php 
if(isset($_POST['savecla'])){
$supid=$_POST['supid'];    
?>

<div class="col-md-12 popup_details_div addtransfer">
<div class="row">
<div class="col-md-12">
<div class="col-md-1"></div>
<div class="col-md-10">
<div class="form-group" >
<label>Claim Date</label>
<input type="text" class="form-control datetimepicker" name="cladt" id="cladt" value="<?php echo $today;?>" placeholder="Claim Date" autocomplete="off" readonly>
<input type="hidden" name="addclaim" readonly />    
<input type="hidden" name="supid" value="<?php echo $supid; ?>" readonly />     
</div>
    
<div class="form-group">
<label>Note</label>
<textarea class="form-control" maxlength="150" rows="3" name="note" placeholder="Note"></textarea>
</div>    
</div>    
<div class="col-md-1"></div>    
</div>    
</div>
</div>
<div class="clearfix" ></div>
<div class="col-md-12 nopadding widgets_area"></div>    
<div class="row"style="margin-top: 15px" >
<div class="col-md-8"></div>
<div class="col-md-3 text-right" >
<input type="button" id="fincla" class="btn btn-flat bg-purple btn-sm " value="Save Claim"/>
</div>
<div class="col-md-1"></div>    
</div>

<script type="text/javascript">
function chek_error(){
var cladt = $('#cladt').val();

var result = true;    

$('.LV_invalid_field').removeClass('LV_invalid_field');     
$('.LV_validation_message').remove();    

if(cladt.length<=0){
$('#cladt').addClass('LV_invalid_field');   
$('#cladt').after("<span class='LV_validation_message LV_invalid'>Enter Claim Date!</span>").addClass('has-error');
result=false;    
}else{
$('#cladt').removeClass('LV_invalid_field');
result=true;    
}     

if(cladt == '' || !result){
return false;    
}else{
return true;     
}    
   
}
        
$(document).on('blur', '#cladt', function() {
chek_error();    
});    
    
$('.datetimepicker').datepicker({format: "yyyy-mm-dd", autoclose: true, clearBtn: true, orientation: 'auto bottom'});    
</script>    
<?php } ?>

<?php 
if(isset($_POST['rcvdet'])){
$invid=$_POST['invid'];
$invno=$_POST['invno'];    
?>
<div class="col-md-12 badstockrec">
<div class="col-md-1"></div>
<div class="col-md-10">
<div class="row">
<div class="cart cart-sm">     
<table class="table table-bordered table-striped" style="margin-bottom: 0;">
<thead>
<th style="width:35px; text-align:center;">SN</th>
<th style="width:60px; text-align:center;">Image</th>
<th style="width:180px; text-align:left;">Product</th>
<th style="width:100px; text-align:center;">Code</th>
<th style="width:100px; text-align:center;">Serial</th>    
<th style="width:100px; text-align:center;">New Serial</th>
<th style="width:100px; text-align:center;">Amount</th>   
</thead>
</table>
<div class="cart-tra style-3 item" style="padding:0px;">    
<table class="table table-bordered table-striped results" style="margin-bottom: 0;">     
<tbody>   
<?php     
$sql="SELECT wst.id,wst.pid,itm.name,itm.image,itm.code,wst.colid,wst.sizid,wst.serial,wst.sel_date,wst.apdate,wst.exp_date FROM (SELECT id,pid,colid,sizid,serial,sel_date,exp_date,apdate FROM (SELECT id,pid,colid,sizid,serial,sel_date,exp_date,apdate FROM tbl_waranty WHERE binvno='".$invno."' AND bst='0') stwar) wst LEFT JOIN (SELECT id,name,image,code FROM tbl_item) itm ON itm.id=wst.pid ORDER BY name ASC";
$querys=mysqli_query($con,$sql)or die(mysqli_error($con));
while ($rows=mysqli_fetch_array($querys)){    
$name='';
$name=$rows['name'];
if($rows['colid']!='0'){$name.=' - '.get_fild_data('tbl_color',$rows['colid'],'name');}
if($rows['sizid']!='0'){$name.=' - '.get_fild_data('tbl_size',$rows['sizid'],'sval');}
?>
<tr>
<td style="width:35px; text-align:center;"><?php echo count_id(); ?></td>
<td style="width:60px; text-align:center;"><img src="../img/product/<?php if(empty($rows['image'])){ echo 'no_image.png';}else{echo $rows['image'];} ?>" height="40px" width="40px"></td>    
<td style="width:280px; text-align:left;"><?php echo $name; ?>
<input type="hidden" name="data['<?php echo $rows['id']; ?>'][id]" value="<?php echo $rows['id']; ?>" readonly>    
</td>
<td style="width:100px; text-align:center;"><?php echo $rows['code']; ?></td>
<td style="width:100px; text-align:center;"><?php echo $rows['serial']; ?></td>
<td style="width:100px; text-align:center;"><input type="text" maxlength="25" name="data['<?php echo $rows['id']; ?>'][newserial]" class="form-control nserial" id="nsl_<?php echo $rows['id']; ?>" value="" style="width:100%; height: 24px; text-align:center;"></td>
<td style="width:100px; text-align:center;"><input type="text" min="0" maxlength="8" onkeypress="return isNumberKey(event)" name="data['<?php echo $rows['id']; ?>'][amount]" class="form-control namount" id="nam_<?php echo $rows['id']; ?>" value="" step="any" style="width:100%; height: 24px; text-align:center;"></td>    
</tr>    
<?php } ?>    
</tbody>    
</table>
</div>   
</div>    
</div>
    
<div class="clearfix" ></div>
<div class="col-md-12 nopadding widgets_area"></div>    
<div class="row"style="margin-top: 15px" >
<div class="col-md-8"></div>
<div class="col-md-4 text-right" >
<input type="button" id="reccla" class="btn btn-flat bg-purple btn-sm " value="Receive Item"/>
<input type="hidden" name="badclrec" readonly />    
</div>   
</div>
    
</div>
<div class="col-md-1"></div>    
</div>
<script type="text/javascript">
$(document).on('blur', '.nserial', function () {
csrl= ($(this).val()).toLowerCase();
fsval=($(this).val()).toUpperCase();    
idval=$(this).attr('id');
id = idval.split("_");
var ids = id[1];
    
if(csrl.length>0){
$('.nserial').each(function() {
cidval = $(this).attr('id');
esrl = ($(this).val()).toLowerCase();   
if(idval !== cidval){
if(csrl===esrl){
$('#'+idval).val('');    
}else{
$.ajax({
url: 'war_badcart.php',
method: "POST",
data:{ 
upimei: 1, imeidata: csrl
},
success: function(data){
$('#'+idval).val(data);
if(data.length>0){
$('#nam_'+ids).val('');    
}    
}
});        
}    
}
    
});    
}    
});
    
$(document).on('keyup', '.namount', function () {
id_arr = $(this).attr('id');
id = id_arr.split("_");
var ids = id[1];    
amo = parseFloat($(this).val());
if(isNaN(amo)){return;}
if(amo>0){
$('#nsl_'+ids).val('');    
}    
});
    
$(document).on('click', '#reccla', function() {
var cash_data = $('.badstockrec input');    
toastr.options = {'positionClass': 'toast-top-center'};

$.ajax({
url: "war_badcart.php",
data: cash_data,
type: 'post',
dataType: 'json',    
success: function(data){
if(data.status === "success"){
$('.right-side-checkout').removeClass('open-right-checkout');
$('#datacon').html('');
if($('.right-side-free').is(':visible')) {
$('.right-side-free').toggle('slide', { direction: 'right' }, 300);
}   
toastr.success(data.message);    
}else{
toastr.error(data.message);    
}         
}
})   
})    
</script>    
<?php } ?>