<?
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]=='GR No.')
            $invno_no1 = $x;
           if($spline[$x]=='Dealer Plant')
            $deal_plant_no = $x;
      }
    }
    if($j>1)
    {
		 $invno1 = trim($spline[$invno_no1]);
		 $deal_plant = trim($spline[$deal_plant_no]);
    
    if($invno1!=$invno_prv)
    {
            $query11=mysqli_query($db,"select brcode from branch where brman='$deal_plant'");
            $row_br=mysqli_fetch_row($query11);    
            $brcode = $row_br[0];
        $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++;
  }
  
  
$prevdt= date('Y-m-d', strtotime(' -5 day'));
  //-------------------------------------------------------------
  $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+1;$x++)
      {
        if(trim($spline[$x])=='Vendor Invoice No.')
          $invno_no = $x;
        if($spline[$x]=='Dealer Plant')
          $deal_plant_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]=='GR Qty.')||($spline[$x]=='Quantity'))
          $qty_no = $x;
        //if($spline[$x]=='List Price per Unit')
          if($spline[$x]=='NDP per Unit')
          $lstprice_no = $x;
          if($spline[$x]=='Local Part Price')
          $lstprice1_no = $x;
          if($spline[$x]=='Lubricant List Price Per Unit')
          $lstprice2_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]=='HSN Code')
            $hsncode_no = $x;
          if($spline[$x]=='Tax Description')
            $tax_desc_no = $x;
          if($spline[$x]=='Purchase Order Descr')
                $ord_type_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]);
          $tax_desc = trim($spline[$tax_desc_no]);
          $ord_type = trim($spline[$ord_type_no]);
        if($tax_desc=='CGST & SGST Input 5%' || $tax_desc=='IGST Input 5%')
            $tax='5.00';
        if($tax_desc=='CGST & SGST Input 12%' || $tax_desc=='IGST Input 12%')
            $tax='12.00';
        if($tax_desc=='CGST & SGST Input 18%' || $tax_desc=='IGST Input 18%')
            $tax='18.00';
        if($tax_desc=='CGST & SGST Input 28%' || $tax_desc=='IGST Input 28%')
            $tax='28.00';
        if($tax_desc=='CGST & SGST Input 0%' || $tax_desc=='IGST Input 0%')
            $tax='0.00';
        if($tax=='ZO')
          $tax='0.00';
          
          $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]);
          $cname =mysqli_escape_string($cname);
          $lstprice1 = trim($spline[$lstprice1_no]);
          $lstprice2 = trim($spline[$lstprice2_no]);
          $deal_plant = trim($spline[$deal_plant_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 = str_replace(';', '', $cname);
          $lstprice1 = trim($lstprice1,'"');
          $lstprice1 = str_replace(',', '', $lstprice1);
          $lstprice2 = trim($lstprice2,'"');
          $lstprice2 = str_replace(',', '', $lstprice2);
          $vendor_code = trim($spline[$vendor_no]);
          $hsncode = trim($spline[$hsncode_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';
          
        //if($tax=='VA')
            //$tax='14.50';
        //else
            //$tax='5.00';
    $query11=mysqli_query($db,"select brcode from branch where brman='$deal_plant'");
    $row_br=mysqli_fetch_row($query11);    
    $brcode1 = $row_br[0];
   /* if($gr_1>'')
    {
        if($gr_1!=$row_br[0])
        {
            print "<script>alert('You have Selected different Branch File...!!!');</script>";
            return;
        }
    }*/
    if($invno_no<=''|| $invdate_no<='' || $itemno_no<='' || $itemdesc_no<='' || $qty_no<='' || $lstprice_no<='' || $tottax_no<='' || $tax_no<='' || $vat_no<='' || $total_no<='' || $grno_no<='')
    {
        print "<script>alert('You Are Selected a Wrong File...!!!');</script>";
        return;
    }
      $k=$i-1;
      if(strlen($grno)>0)
      {
          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='$brcode1'");
        $row=mysqli_fetch_row($query);
        if(mysqli_num_rows($query)<=0)
            $purno=1;
        else
            $purno=$row[0]+1;
        }
                            if($itemtype=='ZLUB' || $ord_type =='Lubricants Order')
                                $mitemtype='Lubricant';
                            else
                                $mitemtype='Spares';
                                
                                $lstprice = ($tot-$vat)/$qty;
                                print "$lstprice = ($tot-$vat)/$qty";
                                print $lstprice."List Price";
                                $tottax = $tot-$vat;
          //if($invdate>$prevdt || $user=='thomas')
          if( $user=='das')
          {
        $sql="insert into sparepurchase (purno,suplier,purdate,entrydate,partcode,partname,supqty,price,disc,aprice,hand,tax,taxamt,tot,brcode,taxtype,itemtype,grno,hsncode) 
        values('$purno','$cname','$invdate','$invdate','$itemno','$itemdesc','$qty','$lstprice','$disc','$tottax','$hnd','$tax','$vat','$tot','$brcode1','VAT','$mitemtype','$grno','$hsncode')";
        print $i.". ".$sql."<br>";
        //print "<font color='blue'>Successfuly Inserted.....!!!--".$invno."<br></font>";
          mysqli_query($db,$sql) or die('Insert Err:'.mysqli_error($db));
          }
        
        }
      }
      }
    }
    $invpr=$grno;
    $i++;
  }
  //print "<script> alert('Successfully Uploaded....!!!');document.location='upld_sparepurchasegst_br.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>
<?//<marquee style="font-family:Arial;color:red;" BEHAVIOR=ALTERNATE >UPLOAD OF PURCHASE BEFORE 5 DAYS ARE NOT ALLOWED...!!!</marquee>?>
<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>