<?
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];
      
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='';
    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]=='GR No.')
            $invno_no1 = $x;
      }
    }
    if($j>1)
    {
		 $invno1 = trim($spline[$invno_no1]);
    
    if($invno1!=$invno_prv)
    {
        $query="select grno from sparepurchase where grno='$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");
  $invpr='';
  $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]=='Vendor Invoice No.')
          $invno_no = $x;
          if($spline[$x]=='Vendor Name')
          $cname_no = $x;
 
          if($spline[$x]=='Vendor Code')
            $vendor_no = $x;
         if($spline[$x]=='GR Date')
          $invdate_no = $x;
         if($spline[$x]=='Material')
          $itemno_no = $x;
         if($spline[$x]=='Material Descirption')
          $itemdesc_no = $x;
         //if($spline[$x]=='Quantity')
          //$qty_no = $x;
          
          if($spline[$x]=='GR Qty.')
          $qty_no = $x;
         if($spline[$x]=='List Price per Unit')
          $lstprice_no = $x;
          if($spline[$x]=='Local Part Price Per Unit')
          $lstprice1_no = $x;
          //if($spline[$x]=='Lubricant List Price Per Unit')
          //$lstprice2_no = $x;
          
          if($spline[$x]=='Lubricant Net Dealer Price Per Unit')
          $lstprice2_no = $x;
         
         if($spline[$x]=='NDP per Unit')
          $lstprice3_no = $x;
         
         
         if($spline[$x]=='Discount % on MRP')
          $disc_no = $x;
         if($spline[$x]=='Total Taxable Amount')
          $tottax_no = $x;
         if($spline[$x]=='Handling Charges')
          $hnd_no = $x;
         if($spline[$x]=='Tax Code')
          $tax_no = $x;
         if($spline[$x]=='Tax Amount')
          $vat_no = $x;
         if($spline[$x]=='Amount')
          $total_no = $x;
          if($spline[$x]=='Material Type')
          $itemtype_no = $x;
           if($spline[$x]=='GR No.')
          $grno_no = $x;
         if($spline[$x]=='Tax Description')
          $tper_no = $x;
          if($spline[$x]=='HSN Code')
          $hsn_no = $x;
               }
    }
    if($i>1)
    {
         
          $invno = $spline[$invno_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_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]);
          $grno = trim($spline[$grno_no]);
          $cname = trim($spline[$cname_no]);
          
          $tper = trim($spline[$tper_no]);
         $hsn = trim($spline[$hsn_no]);
          $lstprice1 = trim($spline[$lstprice1_no]);
          $lstprice2 = trim($spline[$lstprice2_no]);
          $lstprice3 = trim($spline[$lstprice3_no]);
         
          $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);
          $grno = str_replace(',', '', $grno);
          $cname = str_replace(',', '', $cname);
          $cname = trim($cname, '"');
          $cname=str_replace("'","", $cname);
          $lstprice1 = trim($lstprice1,'"');
          $lstprice1 = str_replace(',', '', $lstprice1);
          $lstprice2 = trim($lstprice2,'"');
          $lstprice2 = str_replace(',', '', $lstprice2);
          $lstprice3 = trim($lstprice3,'"');
          $lstprice3 = str_replace(',', '', $lstprice3);
         
          $vendor_code = trim($spline[$vendor_no]);

        $cname=mysqli_escape_string($cname);
        $query="select supname from sup_master where code='$vendor_code' ";
    //print $q="select supname from sup_master where code='$vendor_code' ";
        
        $rss=mysqli_query($db,$query);
        $rsrw=mysqli_fetch_array($rss);
        if($rsrw[0]!='')
        {
        //print  
        $sname1=trim($rsrw[0]);
        $cname=$sname1." "."(".$vendor_code.")"; 
        //print "aa";
        }
        else
        {
        //print 
        $cname=$cname." "."(".$vendor_code.")";
        //print "bb";
        }
        
       $vc=$vendor_code;
        
        
        
        /*if($tax=='VA')
            $tax='14.50';
        else
            $tax='5.00';*/
     //if($invno_no<=''|| $invdate_no<='' || $itemno_no<='' || $itemdesc_no<='' || $qty_no<='' || $tottax_no<='' || $tax_no<=''  || $total_no<='' || $grno_no<='')
  
    if($itemno_no<='' || $itemdesc_no<='' || $qty_no<='' || $tottax_no<='' || $tax_no<=''  || $total_no<='' || $grno_no<='')
    {
       /* 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>";
        */
        print "<script>alert('You Are Selected a Wrong File...!!!');</script>";
        return;
    }
      $k=$i-1;
        if(strlen($grno)>0 && $qty>0 && ($invdate>=$acf && $invdate<=$act) )
      {
          if($cname!='')
      {
          if(array_search($grno,$invno_arr)>0)
           {
               print "<font color='red'>Already Inserted.....!!!--".$grno."<br></font>";
           }
           else
           {
        if($invpr!=$grno) 
        {
        $query=mysqli_query($db,"select max(purno) from sparepurchase where brcode='$brcode'");
        $row=mysqli_fetch_row($query);
        if(mysqli_num_rows($query)<=0)
            $purno=1;
        else
            $purno=$row[0]+1;
        }
                            if($itemtype=='ZLUB')
                                $mitemtype='Lubricant';
                            else
                                $mitemtype='Spares';
                                
                                $lstprice = $lstprice1+$lstprice2+$lstprice+$lstprice3;
          $ttper= preg_replace('/[^0-9\.]/', '', $tper);
      $tax=number_format($ttper,2);
      $ttype=substr($tper,0,3);
    
        $sql="insert into sparepurchase (purno,suplier,purdate,entrydate,partcode,partname,supqty,price,disc,aprice,hand,tax,taxamt,tot,brcode,taxtype,itemtype,grno,porderno,hsncode) 
        values('$purno','$cname','$invdate','$invdate','$itemno','$itemdesc','$qty','$lstprice','$disc','$tottax','$hnd','$tax','$vat','$tot','$brcode','GST','$mitemtype','$grno','$vc','$hsn')";
       print $i.". ".$sql ."<br>";
         mysqli_query($db,$sql) or die('Insert Err:'.mysqli_error($db));
          print "<font color='blue'>Successfuly Inserted.....!!!--".$invno."<br></font>";
      
        $cname="";
           }
      }
      }
    }
    $invpr=$grno;
    $i++;
  }
  print "<script> alert('Successfully Uploaded....!!!');document.location='upld_sparepurchasegst.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, 117);}
.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 Spare Purchase</h1>
<tr><td>File <input type=file name='ff'><input type=submit value='Upload' name='upd'></td></tr>
<tr><td>Always download the spare purchases from SAP with below columns in ANY ORDER (Dealer Invoice no,Invoice date,Material,Material Desc.,<br>Delivered Qty,List price Per Unit,Category Discount Value,Total taxable,Handling charges,VAT Rate,VAT Amount,Grand Total,Material Type)<br>(Convert it to TAB TEXT Format and upload)
 </td></tr>
</table>
</td></tr>
</table>
</form>