<?
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");
$acpd=mysqli_query($db,"select * from acperiod") or die ('err'.mysqli_error($db));
     $acrow=mysqli_fetch_row($acpd);

      $acf= $acrow[0];
      $act= $acrow[1];
      
      $fag10=0;
if(isset($_POST['upd']))
{
    $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='';
  $invno_arr2[]='';
  $invno_prv2='';

    while(!feof($fp))
  {
     $line=fgets($fp,1024);
     $spline=explode("\t",$line);
    if($j==1)
    {
      $no_col=sizeof($spline);
      for($x=0;$x<=$no_col;$x++)
      { 
           if($spline[$x]=='Material Document')
            $invno_no1 = $x;
      }
    }
    if($j>1)
    {
		 $invno1 = trim($spline[$invno_no1]);
    
    if($invno1!=$invno_prv)
    {
        $query="select invno from mb51 where invno='$invno1' and brcode='$brcode'";
        $rs=mysqli_query($db,$query);
        if(mysqli_num_rows($rs)>0)
        {
            $invno_arr[$ctr++]=$invno1;
        }
        
    }
        $invno_prv=$invno1;
        
    }$j++;
  }
  
  
  
  //-------------------------------------------------------------
  $fp=fopen($filepath.$imagename,"r") or die("Cant open file");
  
  $i=1;
  while(!feof($fp))
  {
     $line=fgets($fp,1024);
     $spline=explode("\t",$line);
              if($i==1)
    {
      $no_col=sizeof($spline);
      for($x=0;$x<=$no_col;$x++)
      {
        
         if($spline[$x]=='Material Document')
          $invno_no = $x;
         if($spline[$x]=='Invoice Type Desc.')
          $invtype_no = $x;
         if($spline[$x]=='Posting Date')
          $invdate_no = $x;
          if($spline[$x]=='Document Date')
          $docdate_no = $x;
          if($spline[$x]=='Entry Date')
          $entrydate_no = $x;
         if($spline[$x]=='SO No.')
          $so_no = $x;
            if($spline[$x]=='Customer Code')
            $vendor_no = $x;
         if($spline[$x]=='Customer Name')
          $cname_no = $x;
         if($spline[$x]=='Material')
          $itemno_no = $x;
         if($spline[$x]=='Material Description')
          $itemdesc_no = $x;
         if($spline[$x]=='Quantity')
          $qty_no = $x;
         if($spline[$x]=='Amount in LC')
          $lstprice_no = $x;
         if($spline[$x]=='Spares Discount')
          $disc_no = $x;
         if($spline[$x]=='Total taxable')
          $tottax_no = $x;
         
          if(trim($spline[$x])=='Grand Total')
          $total_no = $x;
       
       
          if($spline[$x]=='Material Type')
          $itemtype_no = $x;
          if($spline[$x]=='Plant')
          $dlco_no = $x;
         
          if($spline[$x]=='SAP Invoice no')
          $sapinv_no = $x;
          
          if($spline[$x]=='Total Tax Amount')
          $tottaxa_no = $x;
          
               }
    }
    if($i>1)
    {
         
          $invno = $spline[$invno_no];
          $invtype = trim($spline[$invtype_no]);
          $invdate = trim($spline[$invdate_no]);
          $invdate = str_replace('/', '-', $invdate);
          $invdate = implode('-', array_reverse(explode('-', $invdate)));
          
          $docdate = trim($spline[$docdate_no]);
          $docdate = str_replace('/', '-', $docdate);
          $docdate = implode('-', array_reverse(explode('-', $docdate)));
          
          $entrydate = trim($spline[$entrydate_no]);
          $entrydate = str_replace('/', '-', $entrydate);
          $entrydate = implode('-', array_reverse(explode('-', $entrydate)));
          
          $sono = trim($spline[$so_no]);
          $cname = trim($spline[$cname_no]);
          $itemno = trim($spline[$itemno_no]);
          $itemdesc = trim($spline[$itemdesc_no]);
          $itemdesc =mysqli_escape_string($itemdesc);
          $qty = trim($spline[$qty_no]);
          $lstprice = trim($spline[$lstprice_no]);
          $tottax = trim($spline[$tottax_no]);
          $disc = trim($spline[$disc_no]);
          $hnd = trim($spline[$hnd_no]);
          $tax = trim($spline[$tax_no]);
          $vat = trim($spline[$vat_no]);
          $tot = trim($spline[$total_no]);
          $itemtype = trim($spline[$itemtype_no]);
          $dlco = trim($spline[$dlco_no]);
          $invcan = trim($spline[$invcan_no]);
          $oth = trim($spline[$oth_no]);
         
         
          
      $sapinv = trim($spline[$sapinv_no]);
      $tottaxa_amount = trim($spline[$tottaxa_no]);
      
          $cname = trim($cname, '"');
          $cname=str_replace("'","", $cname);
          $qty = trim($qty,'"');
          $qty = str_replace(',', '', $qty);
          $lstprice = trim($lstprice,'"');
          $lstprice = str_replace(',', '', $lstprice);
         
          
          
          $tottax = trim($tottax,'"');
          $tottax = str_replace(',', '', $tottax);
          $disc = trim($disc,'"');
          $disc = str_replace(',', '', $disc);
          $hnd = trim($hnd,'"');
          $hnd = str_replace(',', '', $hnd);
          $tax = trim($tax,'"');
          $tax = trim($tax,'%-');
          $tax = str_replace(',', '', $tax);
          $tot = trim($tot,'"');
          $tot = str_replace(',', '', $tot);
          $vat = trim($vat,'"');
          $vat = str_replace(',', '', $vat);
          $itemtype = str_replace(',', '', $itemtype);
          $dlco = str_replace(',', '', $dlco);
          $invcan = trim($invcan, '"');
          $invcan=str_replace("'","", $invcan);
          $oth = trim($oth,'"');
          $oth = str_replace(',', '', $oth);
          $hsn = trim($hsn,'"');
          
          
          $tottaxa_amount = str_replace(',', '', $tottaxa_amount);
            $tottaxa_amount = trim($tottaxa_amount,'"');
        
            //if($tot<='')
            //$tot=0;
          $vendor_code = trim($spline[$vendor_no]);
          

       $cname=$cname." "."(".$vendor_code.")";  
       $pq="select brman from branch where brman='$dlco' and brcode='$brcode'";
       //print $pq;
       if($dlco!='')
       {
        $query=mysqli_query($db,"select brman from branch where brman='$dlco' and brcode='$brcode'");
        if(mysqli_num_rows($query)<=0 )
        {
            //print "<script>alert('You Are Selected a Wrong Branch...!!!');</script>";
            //return;
        }
       }
       
      
       
       
       /* print"inv ". $invno_no."<br>";
        print "inv d ".$invdate_no."<br>";
        print " part ".$itemno_no."<br>";
        print "part nam ".$itemdesc_no."<br>";
        print "qty".$qty_no."<br>";
       /* print "lst ".$lstprice_no."<br>";
        print "ttax ".$tottax_no."<br>";
        print "tax ".$tax_no."<br>";
        print "tot ".$total_no."<br>";
        print "grn ".$grno_no."<br>";
        */
        
        if($invno_no<=''  || $invdate_no<=''  || $itemno_no<='' || $itemdesc_no<='' || $qty_no<='')
        
        {
            print "<script>alert('You Are Selected a Wrong  File 2...!!!');</script>";
            return;
        }
      $k=$i-1;
      
      if(strlen($invno)>0     && $invdate>=$acf && $invdate<=$act)
      {
          //print "hello";
         /* if($tax==''||$tax=='0')
          {
              $tax='14.50';
              $vat=$tottax*$tax/100;
              $tot=$vat+$tottax;
          }*/
          $hnd=$hnd+$oth;
          if(array_search($invno,$invno_arr)>0)
           {
               print "<font color='red'>Already Inserted.....!!!--".$invno."<br></font>";
           }
           else
           {
               if($qty<0)
               {
                   $lstprice=$lstprice*-1;
                $qty=$qty*-1;
        $sql="insert into mb51 (invno,invdate,entrydate,partcode,partname,outqty,price,tot,brcode,docdate) 
        values('$invno','$invdate','$entrydate','$itemno','$itemdesc','$qty','$lstprice','$lstprice','$dlco','$docdate')";
         print $sql."<br>";
        mysqli_query($db,$sql) or die('Insert Err:'.mysqli_error($db));
               }
               else
               {
                  
        $sql="insert into mb51 (invno,invdate,entrydate,partcode,partname,inqty,price,tot,brcode,docdate) 
        values('$invno','$invdate','$entrydate','$itemno','$itemdesc','$qty','$lstprice','$lstprice','$dlco','$docdate')";
         print $sql."<br>";
        mysqli_query($db,$sql) or die('Insert Err:'.mysqli_error($db));
               }
         print "<font color='blue'>Successfuly Inserted.....!!!--".$invno."<br></font>";
      
           }
      }
      else
      {
          //print "no";
      }
     
    }
    $i++;
  }
  print "<script> alert('Successfully Uploaded....!!!');document.location='upld_mb51.php';</script>";

}
?>
<link rel="stylesheet" href="style.css" type="text/css" />
<style>
body,td{font-family:'calibri';letter-spacing:1;}
tr{background-color:rgb(95, 197, 187);}
.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 MB51</h1>
<tr ><td bgcolor='yellow'><font color='red'>PLEASE  DELETE K,L,M,N,O,P,Q FIELD FROM EXCEL FILE</font></td></tr>

<tr><td>File <input type=file name='ff'><input type=submit value='Upload' name='upd'></td></tr>
<tr><td>Always download the spare invoices from SAP with below columns in ANY ORDER(Invoice Type Desc.,Invoice date,SO No.,Customer Name,Material,<br>Material Desc.,Delivered Qty,List price Per Unit,Spares Discount,Total taxable,Handling charges,VAT Rate,VAT Amount,Grand Total,Material Type,Dealer Code) <br>(Convert it to TAB TEXT Format and upload)
 </td></tr>
</table>
</td></tr>
</table>
</form>