<?
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']))
{
    $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]=='Dealer Invoice no')
            $invno_no1 = $x;
      }
    }
    if($j>1)
    {
		 $invno1 = trim($spline[$invno_no1]);
    
    if($invno1!=$invno_prv)
    {
        $query="select invno from spareinvoice 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]=='Dealer Invoice no')
          $invno_no = $x;
         if($spline[$x]=='Invoice Type Desc.')
          $invtype_no = $x;
         if($spline[$x]=='Invoice date')
          $invdate_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 Desc.')
          $itemdesc_no = $x;
         if($spline[$x]=='Delivered Qty')
          $qty_no = $x;
         if($spline[$x]=='List price Per Unit')
          $lstprice_no = $x;
         if($spline[$x]=='Spares Discount')
          $disc_no = $x;
         if($spline[$x]=='Total taxable')
          $tottax_no = $x;
         if($spline[$x]=='Handling charges')
          $hnd_no = $x;
         if($spline[$x]=='VAT Rate')
          $tax_no = $x;
         if($spline[$x]=='VAT Amount')
          $vat_no = $x;
         if($spline[$x]=='Grand Total')
          $total_no = $x;
          if($spline[$x]=='Material Type')
          $itemtype_no = $x;
          if($spline[$x]=='Dealer Code')
          $dlco_no = $x;
         if($spline[$x]=='Invoice cancelled')
          $invcan_no = $x;
          if($spline[$x]=='Other charges')
          $oth_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)));
          $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]);
         
          $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);
         
          $vendor_code = trim($spline[$vendor_no]);
if (substr($vendor_code,-4)=='3776')
    $cname = $cname.', COCHIN';
if (substr($vendor_code,-4)=='3793')
    $cname = $cname.', PAVANGAD';
if (substr($vendor_code,-4)=='3774')
    $cname = $cname.', KANHANGAD';
if (substr($vendor_code,-4)=='3771')
    $cname = $cname.', KANNUR';
if (substr($vendor_code,-4)=='3770')
    $cname = $cname.', MALAPARAMBA';
if (substr($vendor_code,-4)=='3772')
    $cname = $cname.', MANJERY';
if (substr($vendor_code,-4)=='3773')
    $cname = $cname.', S.BATHERY';
if (substr($vendor_code,-4)=='3775')
    $cname = $cname.', VENGALAM';
if (substr($vendor_code,-4)=='3777')
    $cname = $cname.', EDAYAR';
if (substr($vendor_code,-4)=='3781')
    $cname = $cname.', MUKKAM';
if (substr($vendor_code,-4)=='3779')
    $cname = $cname.', KUTTIYADY';
if (substr($vendor_code,-4)=='3780')
    $cname = $cname.', KUTTIPURAM';
       $cname=$cname." "."(".$vendor_code.")";   
        $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;
        }
        if($invno_no<='' || $invtype_no<='' || $invdate_no<='' || $cname_no<='' || $itemno_no<='' || $itemdesc_no<='' || $qty_no<='' || $lstprice_no<='' || $tottax_no<='' || $tax_no<='' || $vat_no<='' || $total_no<='')
        {
            print "<script>alert('You Are Selected a Wrong  File...!!!');</script>";
            return;
        }
      $k=$i-1;
      if(strlen($invno)>0 && $invdate<'2017-07-01' && $invcan!='YES' && ($invtype!='Cancel.Inv.spares-S1' && $invtype!='Spares Credit Memo' && $invtype!='Cancl.Inv.service-S1'))
      {
          
          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($itemtype=='ZLUB')
                                $mitemtype='Lubricant';
                            else
                                $mitemtype='Spares';
                                
        $sql="insert into spareinvoice (invno,invtype,invdate,entrydate,saleordno,customer,partcode,partname,qty,price,disc,aprice,hand,tax,taxamt,tot,brcode,itemtype,msno) 
        values('$invno','$invtype','$invdate','$invdate','$sono','$cname','$itemno','$itemdesc','$qty','$lstprice','$disc','$tottax','$hnd','$tax','$vat','$tot','$brcode','$mitemtype','$vendor_code')";
        print "<font color='blue'>Successfuly Inserted.....!!!--".$invno."<br></font>";
        mysqli_query($db,$sql) or die('Insert Err:'.mysqli_error($db));
        
           }
      }
      
      if(strlen($invno)>0 && $invdate<'2017-07-01' && $invtype=='Spares Credit Memo')
      {
          
           if($tax=='')
          {
              $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($itemtype=='ZLUB')
                                $mitemtype='Lubricant';
                            else
                                $mitemtype='Spares';
        $sql="insert into salesretnew (invno,invtype,invdate,entrydate,saleordno,customer,partcode,partname,qty,price,disc,aprice,hand,tax,taxamt,tot,brcode,itemtype,msno,taxp) 
        values('$invno','$invtype','$invdate','$invdate','$sono','$cname','$itemno','$itemdesc','$qty','$lstprice','$disc','$tottax','$hnd','$tax','$vat','$tot','$brcode','$mitemtype','$vendor_code',0)";
        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....!!!');document.location='upld_spareinvoice.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 Spare Invoices</h1>
<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>