<?
session_start();
$brcode=$_SESSION['brcode'];
$user=$_SESSION['user'];
if(strlen($brcode)<=0)
{
 print "<script> alert('Session timed out'); parent.document.location='inde.php'; </script>";
 return;
}
include("includes/top.php");
include("opendb.php");
if(isset($_POST['upd']))
{
    
    $logdt=date("Y-m-d");
    $logtime=date("H:i:s");
    $ff=$_REQUEST['ff'];
    if($ff !="none")
    {
        $imagename=$_FILES['ff']['name'];
        $filepath= "";
        $tmp = $_FILES['ff']['tmp_name'];
        move_uploaded_file($tmp, $filepath . $imagename) or die(' err:could not copy file');
       // print "File copied :".$fl;
    }
    $fp=fopen($filepath.$imagename,"r") or die("Cant open file");
     
     
     
     
 $ctr=1;
  

  
  $j=1;
  $invno_arr[]='';
  $invno_prv='';
    while(!feof($fp))
  {
      
     $line=fgets($fp,1024);
     $spline=explode("\t",$line);
     if($j==4)
    {
     
        //print_r($spline);
        
        
       $no_col=sizeof($spline);
      for($x=0;$x<=$no_col;$x++)
      {
    
          
        if($spline[$x]=='Invoice No')
          $invno_no1 = $x;
      }
    }
    if($j>3)
    {
 $invno1 = trim($spline[$invno_no1]);

    
    if($invno1!=$invno_prv)
    {
        
        
      $query="select pord_no from sparetransout where pord_no='$invno1'";
        
        $rs=mysqli_query($db,$query);
        if(mysqli_num_rows($rs)>0)
        {
            $invno_arr[$ctr++]=$invno1;
        }
    }
        $invno_prv=$invno1;
        
    }$j++;
  }
  
  //mysqli_query($db,"delete from sparetransout_test");

  //-------------------------------------------------------------
  $fp=fopen($filepath.$imagename,"r") or die("Cant open file");
  $invpr='';
  $i=1;
  while(!feof($fp))
  {
    $line=fgets($fp,1024);
    
    $spline=explode("\t",$line);
    //print_r($spline);
    if($i==4)
    {
    // print_r($spline);
       $no_col=sizeof($spline);
      
      for($x=0;$x<=$no_col;$x++)
      {
           if($spline[$x]=='STO Invoice Date')
         $invdate_no = $x;
          
        if($spline[$x]=='Dealer Invoice No.')
          $ptype_no = $x;
        if($spline[$x]=='Material')
          $itemno_no = $x;
        if($spline[$x]=='')
          $itemdesc_no = $x;
        if($spline[$x]=='Receiving Dealer')
          $grno_no = $x;
        if($spline[$x]=='Supplying Dealer')
          $itemtype_no = $x;  
       

        if($spline[$x]=='pname')
          $partname_no = $x;

      }
    }
    if($i==3)
    {
       $no_col=sizeof($spline);
    
      for($x=0;$x<=$no_col+1;$x++)
      {
            if($spline[$x]=='Invoice Qty')
          $qty_no = $x;
            if(trim($spline[$x])=='Net Order Value')
          $total_no = $x;
          
             if(trim($spline[$x])=='Tax Amount')
          $tax_no = $x;
          
      }
    }
    if($i>2)
    {
        
          $qty = trim($spline[$qty_no]);
          $tot = trim($spline[$total_no]);
          $qty = trim($qty,'"');
          $qty = str_replace(',', '', $qty);
          $tot = trim($tot,'"');
          $tot = str_replace(',', '', $tot);
          
            if(is_numeric($tot) && is_numeric($qty))
            $tot = round($tot / $qty,5);
            else
            $tot=0;
          
          $tax = trim($spline[$tax_no]);
          $tax = trim($tax,'"');
          $tax = str_replace(',', '', $tax);
        
    }   
    if($i>3)
    {

          $ptype = trim($spline[$ptype_no]);
          $invdate = trim($spline[$invdate_no]);
          $invdate = str_replace('.', '-', $invdate);
          $invdate = implode('-', array_reverse(explode('-', $invdate)));
          $itemno = trim($spline[$itemno_no]);
          $itemdesc = trim($spline[$itemdesc_no]);
          $itemdesc =mysqli_real_escape_string($db,$itemdesc);
          $grno = trim($spline[$grno_no]);
          $grno = str_replace(',', '', $grno);
          $itemtype = trim($spline[$itemtype_no]);
          $pname = trim($spline[$partname_no]);
    }


      $k=$i-1; 
          
      if($i>4 && $ptype!='')
      {
               if($invdate_no<='' || $itemno_no<='' || $qty_no<='' || $total_no<='' || $grno_no<='')
               //if( $itemno_no<='' || $qty_no<='' || $total_no<='' || $grno_no<='')
                {
                   print $invdate."<br>1";
                    print $itemno."<br>2";
                     print $qty."<br>3";
                      print $tot."<br>4";
                       print $grno."<br>5";
                print "<script>alert('You $invdate_no have $itemno_no Selected $qty_no ab $total_no Wrong File...!!! $grno_no');</script>";
                
                                return;
                }
                
               
           if(array_search($ptype,$invno_arr)>0)
           {
               print "<font color='red'>Already Inserted.....!!!--".$ptype."<br></font>";
           }
           else
           {
print "okk";

        
        $qry=mysqli_query($db,"select b.brcode from branch b where b.brman='$grno'");
        $qry1=mysqli_fetch_row($qry);
         $item=$qry1[0];
         $tobr=$qry1[0];
         
        $qry1=mysqli_query($db,"select brcode from branch where brman='$itemtype'");
        $qry12=mysqli_fetch_row($qry1);
        $frbrcode=$qry12[0];
        
        $aprice=$qty*$tot;
        $gtot=$aprice+$tax;
        
        $taxp=$tax/$aprice*100;
        $taxp=round($taxp);
 print  $sql="insert into sparetransout (tr_no,trdate,entrydate,partcode,partname,pord_no,qty,to_branch,brcode,amount,saprefno,taxamt,aprice,taxp,gtot,grdate,gramount) values('$ptype','$invdate','$invdate','$itemno','".addslashes($pname)."','$ptype','$qty','$tobr','$frbrcode','$tot','$ptype','$tax','$aprice','$taxp','$gtot','$invdate','$gtot')";
        print $i.". ".$sql."<br>";
        $saprefno = $ptype;
        print "<font color='blue'>Successfuly Inserted.....!!!--".$invno."<br></font>";
        mysqli_query($db,$sql) or die('Insert Err:'.mysqli_error($db));
        
           }
      }
    
    $i++; 
  }
    print "<script> alert('Successfully Uploaded....!!!');</script>";
    //**** Accounts posting.....
    $sql="select sum(qty*amount),sum(taxamt),sum(gtot),brcode,saprefno,entrydate,to_branch,grno,taxamt,taxp from sparetransout where jvno<=0 and saprefno='$saprefno' and brcode='$brcode'  group by taxp";
    $jvres=mysqli_query($db,"select max(jvno) from journal2 where brcode='$brcode'")or die('err'.mysqli_error($db));
    $jvrow=mysqli_fetch_array($jvres)or die('err1'.mysqli_error($db));
    if($jvrow[0]>0)
        $jvno=($jvrow[0]+1);
    else
        $jvno=1;
    $pres=mysqli_query($db,$sql) or die('post err'.mysqli_error($db));
    while($row23=mysqli_fetch_array($pres))
    {
    	$re=mysqli_query($db,"select brled from branch where brcode='$row23[to_branch]'")or die('err2'.mysqli_error($db));
        $rr=mysqli_fetch_row($re);
        $branch_na=$rr[0];
        $sql="update sparetransout set jvno='$jvno' where saprefno='$row23[saprefno]' and brcode = '$row23[brcode]'";
        print $sql."<br>";
        mysqli_query($db,$sql) or die('Insert Err:'.mysqli_error($db));
        //*************** posting
	    $ledger1='STOCK TRANSFER OUT IGST '.$row23[9];
        $ledger2='STOCK TRANSFER OUT';
        $ledger3='OUTPUT IGST STOCK TRANSFER OUT '.$row23[9];
        if($row23['taxamt']<=0)
        {
		    mysqli_query($db,"insert into journal2(date, jvno, type, partic, dramt, cramt, narr, brcode, j_type, against, no, tr_no,prftcntr,docdt) values('$row23[entrydate]','$jvno','Cr','STOCK TRANSFER OUT','0','$row23[0]','Stock Transfer Out No:$row23[saprefno]','$row23[brcode]','Spare trans out','Trans no','$row23[grno]','$row23[saprefno]','$logtime $user','$logdt')");
        }
        else
        {
    		mysqli_query($db,"insert into journal2(date, jvno, type, partic, dramt, cramt, narr, brcode, j_type, against, no, tr_no,prftcntr,docdt) values('$row23[entrydate]','$jvno','Cr','$ledger1','0','$row23[0]','Stock Transfer Out No:$row23[saprefno]','$row23[brcode]','Spare trans out','Trans no','$row23[grno]','$row23[saprefno]','$logtime $user','$logdt')");  
		    mysqli_query($db,"insert into journal2(date, jvno, type, partic, dramt, cramt, narr, brcode, j_type, against, no, tr_no,prftcntr,docdt) values('$row23[entrydate]','$jvno','Cr','$ledger3','0','$row23[1]','Stock Transfer Out No:$row23[saprefno]','$row23[brcode]','Spare trans out','Trans no','$row23[grno]','$row23[saprefno]','$logtime $user','$logdt')");  
        }
        mysqli_query($db,"insert into journal2(date, jvno, type, partic, dramt, cramt, narr, brcode, j_type, against, no, tr_no,prftcntr,docdt) values('$row23[entrydate]','$jvno','Dr','$branch_na','$row23[2]','0','Stock Transfer Out No::$row23[saprefno]','$row23[brcode]','Spare trans out','Trans no','$row23[grno]','$row23[saprefno]','$logtime $user','$logdt')")or die('err2br'.mysqli_error($db));
    }
    
    //****
}
?>
<link rel="stylesheet" href="style.css" type="text/css" />
<style>
body,td{font-family:'calibri';letter-spacing:1;}
tr{background-color:rgb(95, 198, 547);}
.mnu{margin-left:5}
</style>
<center>
<br><br><br><br><br><br>
<form action='' method='post' ENCTYPE="multipart/form-data">
<table border=1 width=60%>
<tr><td> 
<table width=100%>
<th colspan=2><h1>Upload Transfer In</h1>
<tr><td>File <input type=file name='ff'><input type=submit value='Upload' name='upd'></td></tr>
<tr><td>(Convert it to TAB TEXT Format and upload)
 </td></tr>
</table>
</td></tr>
</table>
</form>