<?php session_start();
include ('../inc/dbcon.php');
include ('../inc/functions.php');
include ('../inc/cartfunctions.php');
include ('../inc/repfunctions.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;    
}







function get_avqty($mods,$bwid,$unqid){
global $con;
if($mods=='BR'){    
$sql="SELECT COALESCE ((SELECT avqty FROM tbl_brstock WHERE brid='$bwid' AND unqid='$unqid' LIMIT 1),0) AS avqty";
}elseif($mods=='WH'){
$sql="SELECT COALESCE ((SELECT avqty FROM tbl_whstock WHERE waid='$bwid' AND unqid='$unqid' LIMIT 1),0) AS avqty";    
}
$result=mysqli_query($con,$sql) or die(mysqli_error($con));    
$row=mysqli_fetch_array($result);
return $row['avqty'];    
}

function get_srlinfo($serial,$key){
global $con;
$sql="SELECT ".$key." AS rdata FROM tbl_serial WHERE serial='$serial' LIMIT 1";
$result=mysqli_query($con,$sql) or die(mysqli_error($con));    
$row=mysqli_fetch_array($result);
return $row['rdata'];    
}

function check_trbinvdel($invno){
$flage=0;
global $con;

$sql="SELECT * FROM tbl_traproduct WHERE invno='$invno' AND p_in>0";
$query=mysqli_query($con,$sql)or die(mysqli_error($con));
while ($row=mysqli_fetch_array($query)){
$unqid=$row['unqid'];
$qty=$row['p_in'];
if($row['brid']!=''){
$mods='BR';
$bwid=$row['brid'];    
}else{
$mods='WH';
$bwid=$row['waid'];    
}
$avqty=get_avqty($mods,$bwid,$unqid);
if($qty<$avqty){
$flage=1;
break;    
}else{
$flage=0;    
}    
}    

if($flage>0){
return $flage;
exit;    
}    
 
$sql="SELECT * FROM tbl_serialsale WHERE invno='$invno'";
$query=mysqli_query($con,$sql)or die(mysqli_error($con));
while ($row=mysqli_fetch_array($query)){
$serial=$row['serial'];
$sql="SELECT * FROM tbl_serial WHERE serial='$serial' AND status>0";
$que=mysqli_query($con,$sql)or die(mysqli_error($con));    
if($que->num_rows > 0) {
$flage=1;
break;    
}else{
$flage=0;    
}    
}    

if($flage>0){
return $flage;
exit;    
}    

$sql="SELECT * FROM tbl_trafrbra WHERE invno='$invno'";
$query=mysqli_query($con,$sql)or die(mysqli_error($con));    
$row=mysqli_fetch_array($query);
if($row['ttype']=='BR'){
$key='brid';    
}else{
$key='whid';    
}    
$tid=$row['tsourch'];

$sql="SELECT * FROM tbl_serialsale WHERE invno='$invno'";
$querys=mysqli_query($con,$sql)or die(mysqli_error($con));   
if($querys->num_rows > 0) {
while ($srl=mysqli_fetch_array($querys)){
$serial=$srl['serial'];
$sel=get_srlinfo($serial,$key);
if($sel!=$tid){
$flage=1;
break;    
}    
}    
}else{
$flage=0;    
}        

if($flage>0){
return $flage;
exit;    
}
return $flage;     
}





if(isset($_POST['additem'])){
$unqid=$_POST['additem'];   
edaddbrtransfer($brid,$unqid,1);    
}

if(isset($_POST['remove'])){
$ids = floatval($_POST['remove']);
$unqid=$_SESSION['axes_edtransbr'][$ids]['unqid'];    
remove_edtransbr($ids);
if(isset($_SESSION['axes_edtrbse'])){    
remove_edtrbrslimei($unqid);
}
$max=count($_SESSION['axes_edtransbr']);
if($max <= 0){
unset($_SESSION['axes_edtransbr']);
if(isset($_SESSION['axes_edtrbse'])){
unset($_SESSION['axes_edtrbse']);	
}	
}
if(isset($_SESSION['axes_edtrbse'])){
$smax=count($_SESSION['axes_edtrbse']);
if($smax <= 0){    
unset($_SESSION['axes_edtrbse']);
}
}    
}

if(isset($_POST['upqty'])){
$ids=intval($_POST['upqty']);
$qty=floatval($_POST['qty']);
if($qty<0 || $qty==''){
$redata=array($_SESSION['axes_edtransbr'][$ids]['qty']);
echo json_encode($redata);    
exit;
}
$unqid = $_SESSION['axes_edtransbr'][$ids]['unqid'];
$eqty=(get_selestockinfo($brid,$unqid,'avqty')-get_selestockinfo($brid,$unqid,'sloc'));    
if($qty<=$eqty){
$_SESSION['axes_edtransbr'][$ids]['qty']=$qty;		
}elseif($qty>$eqty){
$_SESSION['axes_edtransbr'][$ids]['qty']=$eqty;		
}    
$redata=array($_SESSION['axes_edtransbr'][$ids]['qty']);
echo json_encode($redata);
}

if(isset($_POST['removeitmsl'])){
$id=intval($_POST['removeitmsl']);
$unqid=$_SESSION['axes_edtrbse'][$id]['unqid'];
$itid=get_transbritmid($unqid);
$itmqty=$_SESSION['axes_edtransbr'][$itid]['qty'];

remove_transbrsl($id);    
if($itmqty<=1){
remove_transbr($itid);    
}else{
$_SESSION['axes_edtransbr'][$itid]['qty']=($itmqty-1);    
}   
$max=count($_SESSION['axes_edtransbr']);
if($max <= 0){
unset($_SESSION['axes_edtransbr']);
if(isset($_SESSION['axes_edtrbse'])){
unset($_SESSION['axes_edtrbse']);	
}	
}    
}

if(isset($_POST['upimei'])){
$ids=intval($_POST['upimei']);
$serialno=strtoupper(remove_junk(escape($_POST['imeidata'])));
$pid=intval($_SESSION['axes_edtrbse'][$ids]['pid']);
if($serialno!=''){
if(transbrserial_exists($pid,$serialno)){
$redata=array($_SESSION['axes_edtrbse'][$ids]['imei']);
echo json_encode($redata);    
return;
exit;    
}
$_SESSION['axes_edtrbse'][$ids]['imei']= $serialno;    
}else{
$_SESSION['axes_edtrbse'][$ids]['imei']='';    
}    
$redata=array($_SESSION['axes_edtrbse'][$ids]['imei']);
echo json_encode($redata); 
}

if(isset($_POST['audimei'])){
$id=$_POST['audimei'];
$ibrid=$_POST['ibrid'];    
$pid=intval($_SESSION['axes_edtrbse'][$id]['pid']);    
$search = $_POST['search'];
	
$sql="SELECT pid,serial FROM tbl_serial WHERE pid='$pid' AND serial LIKE '%$search%' AND brid='$ibrid' AND rci='Y' AND status='0' ORDER BY serial ASC LIMIT 30";		
$result = mysqli_query($con,$sql) or die(mysqli_error($con));
    
while($row = mysqli_fetch_array($result) ){
$response[] = array("value"=>$row['pid'],"label"=>$row['serial']);
}

// encoding array to json format
echo json_encode($response);
exit;    
}

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

if(isset($_POST['trbdata'])){
$edata=array(check_trbserial('S'));
echo json_encode($edata);
}

if(isset($_POST['addbrtrns'])){
    
$invno = $_SESSION['editbrtrinv'];

$ibrid=$brid;
    
if(check_trbinvdel($invno)){
save_msg('w','Transfer Depend on others data!!!');
echo "<script>window.location='inv_bratra.php'</script>";
return;    
}    




    $stype='BR';    
    $sbrid = remove_junk(escape($_POST['sbrid']));
    $desid = explode('_',remove_junk(escape($_POST['desid'])));    
    $ttype=$desid['0'];    
    $toid = $desid['1'];
    if($ttype=='BR'){$ibrid="'".$toid."'";$iwhid='NULL';}else{$ibrid='NULL';$iwhid="'".$toid."'";}    
    $media = remove_junk(escape($_POST['media']));
    if($media==0){$media='NULL';}else{$media="'".$media."'";}     
    $note = remove_junk(escape($_POST['note']));    
    $apdate = remove_junk(escape($_POST['trbdt']));
    
    if(!isset($_SESSION['axes_edtransbr'])){
        echo json_encode(array(
        'status' => 'error',
        'message'=> 'Sorry! No item found!!'
        ));
        return;
        exit;  
    }
    
    if(check_trbvalidqty($sbrid)){
        echo json_encode(array(
        'status' => 'error',
        'message'=> 'Sorry! Quantity not available!!'
        ));
        return;
        exit;     
    }


    $sql="UPDATE tbl_trafrbra SET ftype='$stype',fsourch='$sbrid',ttype='$ttype',tsourch='$toid',media='$media',note='$note',apdate='$apdate',brid='$brid' WHERE invno='$invno'";
       
    $result = mysqli_query($con,$sql) or die(mysqli_error($con));
    
    $efid=mysqli_affected_rows($con);    

    if($efid>0){
        $sql="SELECT * FROM tbl_serialsale WHERE invno='$invno'";
        $querys=mysqli_query($con,$sql)or die(mysqli_error($con));   
        if($querys->num_rows > 0) {
        while ($srl=mysqli_fetch_array($querys)){
        $serial=$srl['serial'];    
        $sql="UPDATE tbl_serial SET brid='$ibrid',whid=NULL WHERE serial='$serial'";
        mysqli_query($con,$sql)or die(mysqli_error($con));    
        }
        $sql="DELETE FROM tbl_serialsale WHERE invno='$invno'";
        mysqli_query($con,$sql)or die(mysqli_error($con));    
        }
            
        $sql="DELETE FROM tbl_traproduct WHERE invno='$invno'";
        mysqli_query($con,$sql)or die(mysqli_error($con));
        

        $max=count($_SESSION['axes_edtransbr']);
        for($i=0;$i<$max;$i++){
            $pid = $_SESSION['axes_edtransbr'][$i]['pid'];
            $unqid= $_SESSION['axes_edtransbr'][$i]['unqid'];   
            $col=$_SESSION['axes_edtransbr'][$i]['col'];
            $siz=$_SESSION['axes_edtransbr'][$i]['siz'];
            $cost=$_SESSION['axes_edtransbr'][$i]['cost'];
            $puqty=0;    
            $qtyin=$_SESSION['axes_edtransbr'][$i]['qty'];
            $soqty=0;    
            $qtyout=$_SESSION['axes_edtransbr'][$i]['qty'];
            $taxp=0;
            $taxamo=0;
            $idisp=0;
            $idisf=0;
            $disamo=0;
            $sdisp=0;
            $sdisf=0;
            $price=$_SESSION['axes_edtransbr'][$i]['price'];
            $isubtot=0;
            $wday=$_SESSION['axes_edtransbr'][$i]['wday'];
            $pnote='';    
                
            $sql="INSERT INTO tbl_traproduct (type,tid,invno,refinv,pid,unqid,colid,sizid,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 (NULL,NULL,'$invno',NULL,'$pid','$unqid','$col','$siz','$cost','$price','$puqty','0','$soqty','$qtyout','$taxp','$taxamo','$idisp','$idisf','$disamo','$isubtot','$wday','TR','$brid',NULL,NULL,'Y',NULL,'$aid','$apdate','$dtnow'),(NULL,NULL,'$invno',NULL,'$pid','$unqid','$col','$siz','$cost','$price','$puqty','$qtyin','$soqty','0','$taxp','$taxamo','$idisp','$idisf','$disamo','$isubtot','$wday','TR',$ibrid,$iwhid,NULL,'Y',NULL,'$aid','$apdate','$dtnow')";
                
            $result = mysqli_query($con,$sql) or die(mysqli_error($con));    
        }
    
        if(isset($_SESSION['axes_edtrbse'])){
            $max=count($_SESSION['axes_edtrbse']);
            for($i=0;$i<$max;$i++){
                $pid=$_SESSION['axes_edtrbse'][$i]['pid'];
                $unqid=$_SESSION['axes_edtrbse'][$i]['unqid'];    
                $serial=$_SESSION['axes_edtrbse'][$i]['imei'];    
                $sql="INSERT INTO tbl_serialsale (invno,pid,unqid,serial,mods) VALUES ('$invno','$pid','$unqid','$serial','T')";
                $result = mysqli_query($con,$sql) or die(mysqli_error($con));
                $sql="UPDATE tbl_serial SET brid=$ibrid,whid=$iwhid WHERE serial='$serial'";   
                $result = mysqli_query($con,$sql) or die(mysqli_error($con));    
            }    
        }
    
        unset($_SESSION['axes_edtrde']);
        
        unset($_SESSION['axes_edtransbr']);
        if(isset($_SESSION['axes_edtrbse'])){
            unset($_SESSION['axes_edtrbse']);
        }    
            
        $act =remove_junk(escape('Transfer No: '.$invno));    
        write_activity($aid,'TRB','Update Successfully',$act);
        echo json_encode(array(
        'status' => 'success',
        'message'=> 'Transfer Update Successfully!!'   
        ));
        exit;    
    }else{
        echo json_encode(array(
        'status' => 'error',
        'message'=> 'Sorry! Data Fail to Saved!!'
        ));    
    }        
}
?>

<?php 
if(isset($_POST['savetra'])){
$ibrid=$_POST['brid'];   


$invno=$_SESSION['axes_edtrde'][0]['invno'];
$ftype=$_SESSION['axes_edtrde'][0]['ftype'];
$fsourch=$_SESSION['axes_edtrde'][0]['fsourch'];  
$ttype=$_SESSION['axes_edtrde'][0]['ttype'];
$tsourch=$_SESSION['axes_edtrde'][0]['tsourch']; 
$apdate=$_SESSION['axes_edtrde'][0]['apdate'];
$note=$_SESSION['axes_edtrde'][0]['note'];





?>
<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>Transfer Date</label>
<input type="text" class="form-control datetimepicker" name="trbdt" id="trbdt" value="<?php echo $apdate;?>" placeholder="Transfer Date" autocomplete="off" readonly>
</div>    
<div class="form-group">
<label>Transfer To</label>    
<select class="form-control select2" name="desid" id="desid">
<option value="">-Select-</option>
<optgroup label="Branch"> 
<?php if($ibrid!=0){ ?>   
<option <?php if($ttype=='BR' && $tsourch==0){ echo 'Selected';} ?> value="BR_0">No Branch</option>    
<?php } ?>    
<?php
$sql="SELECT id,name FROM tbl_branch WHERE id!='$ibrid' ORDER BY name ASC";
$query=mysqli_query($con,$sql)or die(mysqli_error($con));
if($query->num_rows > 0) {    
while ($rows=mysqli_fetch_array($query)){
?>
<option <?php if($ttype=='BR' && $tsourch==$rows['id']){ echo 'Selected';} ?> value="<?php echo 'BR_'.$rows['id'];?>"><?php echo $rows['name'];?></option>
<?php } ?>   
<?php } ?>
</optgroup>
<optgroup label="Warehouse">     
<?php
$sql="SELECT id,name FROM tbl_warehouse ORDER BY name ASC";
$query=mysqli_query($con,$sql)or die(mysqli_error($con));
if($query->num_rows > 0) {    
while ($rows=mysqli_fetch_array($query)){
?>
<option <?php if($ttype=='WH' && $tsourch==$rows['id']){ echo 'Selected';} ?> value="<?php echo 'WH_'.$rows['id'];?>"><?php echo $rows['name'];?></option>
<?php } ?>   
<?php } ?>
</optgroup>    
</select>
<input type="hidden" name="addbrtrns" readonly />
<input type="hidden" name="sbrid" value="<?php echo $ibrid; ?>" readonly />    
</div>

<div class="form-group">
<label>Transfer Type</label>
<select class="form-control select2" name="media" id="media">    
<option value="0">Direct</option>
<?php
$sql="SELECT id,name FROM tbl_shipline ORDER BY name ASC";
$query=mysqli_query($con,$sql)or die(mysqli_error($con));
if($query->num_rows > 0) {
?>
<optgroup label="Media">    
<?php    
while ($rows=mysqli_fetch_array($query)){
?>    
<option value="<?php echo $rows['id'];?>"><?php echo $rows['name'];?></option>    
<?php } ?>
</optgroup>    
<?php } ?>    
</select>    
</div>    
    
<div class="form-group">
<label>Note</label>
<textarea class="form-control" maxlength="150" rows="3" name="note" placeholder="Note"><?php echo $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-4 text-right" >
<input type="button" id="fintrb" class="btn btn-flat bg-purple btn-sm " value="Save Transfer"/>
</div> 
</div>

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

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

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

if(desid == '-Select-' || desid == ''){
$('#desid').addClass('LV_invalid_field');   
$('#desid').after("<span class='LV_validation_message LV_invalid'>Can't be empty!</span>").addClass('has-error');
result=false;    
}else{
$('#desid').removeClass('LV_invalid_field');     
}    
    
if(desid == '' || !result){
return false;    
}else{
return true;     
}    
   
}
        
$(document).on('blur', '#trbdt, #desid', function() {
chek_error();    
});

$('.datetimepicker').datepicker({format: "yyyy-mm-dd", autoclose: true, clearBtn: true, orientation: 'auto bottom'});    
</script>    
<?php } ?>