<?php 
date_default_timezone_set('Asia/Calcutta');
include('./includes/Class_Branch.php');
include('./includes/AccountGroupMaster_Class.php');
//$lcrdata=array('8','10','11','12','14','15');
$modid=$_REQUEST['modid'];
$frmid=$_REQUEST['frmid'];
$VPrefix=$_REQUEST['VPrefix'];
$debit_side=array('6','4','8','11','12','14','15');
$lcrdata=array('5','3','11','8','13','12','15');
?>
<input type="hidden"  name="Vprefixtype" id="Vprefixtype" value="<?php echo $VPrefix; ?>" />
<script src="js/function-ajax.js" language="javascript"></script>
<script language="javascript">


function deleteRowOrder(tableID) 
{
  
    if($('#'+tableID).find('input[type="checkbox"]:checked').length == 0)
    { 
      alert('Please select at least one row to delete.');
      return false;
    }
  try 
  {
    var table = document.getElementById(tableID);
    //alert(table);
    var rowCount = table.rows.length;
    //alert(rowCount);
    for(var i=0; i<rowCount; i++) 
      {
        var row = table.rows[i];
        
        var chkbox = row.cells[0].childNodes[0];
        if(null != chkbox && true == chkbox.checked) 
        {
          if(rowCount <= 1) 
          {
            alert("Cannot delete all the rows.");
            break;
          }
        table.deleteRow(i);
        rowCount--;
        i--;
        }
        
      }
      //alert(rowCount);
  //document.getElementById("hiditemcount1").value=parseInt(rowCount);    
  
  }
  catch(e) 
  {
    alert(e);
  }
   if(document.getElementById("convrate"))
    {
      var convrate=document.getElementById("convrate");

calculate_conversion(convrate);
    }
    else
    {
     var convrate='';
 calculate_conversion(convrate);
    }

}
</script>

<?php 

/***********************************INSERT HERE*******START HERE******************AMIt***********************************/
if($_REQUEST['save']) //
{

  $dataArray['Branch']              =$_REQUEST['Branch'] ;
  //$dataArray['Voucher_NO']          =$FinalCostCeNo ;
  $dataArray['voucher_date']   =FormatDateForSQL($_REQUEST['Dates']);
  $dataArray['funding_by']        =$_REQUEST['funding_by'];
  $dataArray['budget_id']       =$_REQUEST['Ref_no'] ;
  $dataArray['budget_date']       =FormatDateForSQL($_REQUEST['ref_date']);
  $dataArray['modified_date']     =date('Y-m-d');
  $dataArray['modified_by']=$_SESSION['UserID'];
  $dataArray['CompanyId']=$_SESSION['ACGCompanyId'];
  $dataArray['funding_amount']        =$_REQUEST['funding_amt'];
  $dataArray['narration']        =$_REQUEST['narration'];
  $dataArray['type']        =$_REQUEST['type'];
  $dataArray['revenue_head']        =$_REQUEST['revenue_head'];

   $cond="id='".$_REQUEST['id']."'";
   $s->RecordEdit('account_fund_receipt', $dataArray,$cond);

  $getlastid=DB_Last_Insert_ID($db,'account_fund_receipt', 'id');
  
  // echo $_REQUEST['hiditemcount1'];
  // exit;
    $del_hrd_items=DB_query("delete from account_fund_receipt_dtls where fund_receipt_dtls_id='".$_REQUEST['id']."'",$db);
   
 for($cnt=0;$cnt<count($_REQUEST['mstitemid']);$cnt++)
    { 
     
        $data_array1['fund_receipt_dtls_id']=$_REQUEST['id'];
        $data_array1['category_id']=$_REQUEST['mstitemid'][$cnt];  
        $data_array1['budgeted_amount']=$_REQUEST['budget_amount'][$cnt];
        $data_array1['funding_amount']=$_REQUEST['funding_amount_sub'][$cnt];                       
        $data_array1['remarks']=$_REQUEST['remarks'][$cnt];  

        $s->RecordInsert('account_fund_receipt_dtls', $data_array1); 

     
    }

   
   $s->pageLocation("index.php?route=fund_receipt_index".$rurl);
}
?>
  
<div id="PickedItems" style="display:none"></div>
<div id="div_id" style="display:none"></div>
<style type="text/css">
.modal22 {
  display: none;
  position: fixed;
  z-index: 1000;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  background: rgba( 105, 105, 105, .4 )50% 50%no-repeat;
}
</style>
<?php 
$sql_fetch=DB_query("select * from account_fund_receipt where id='".$_REQUEST['id']."'",$db);

$row_fetch=DB_fetch_array($sql_fetch);

?>
<link rel="stylesheet" href="css/new_mxerp.css">
<div class="body_contain">
  <div class="modal22"><center><div style="font-size:50px;margin-top:200px;">Loading...</div></center></div>
<div class="tab_div">
<h1><?php echo $fromtitle= $s->getField('voucher_master','VoucherType',$_REQUEST['VPrefix'],'GroupName');?></h1>
<form action="" method="post">

<?php if(count($msgErr)>0){?>
<p align="center">
  <div class='error'><?php
     for($i=0;$i<count($msgErr);$i++)
     {
     echo "".$msgErr[$i].'<br>';
     }?>
  </div>
  </p>
   <?php } ?>
<table width="100%" border="0" cellspacing="0" cellpadding="3">
<tr class="row1">
  <td width="13%" align="right"><strong>Branch</strong></td>
    <td width="20%"><?php //echo $ClassBranch->Branch($Branch,$VPrefix);
          $sql_state=DB_query("SELECT loccode,locationname FROM  locations 
          WHERE CompanyId='".$_SESSION['ACGCompanyId']."' AND loccode in('".$_SESSION['AssignedBranch']."')",$db);  ?>
      <select name="Branch" id="Branch" style="width:98%;" onchange="getLedgerName(this.value,'<?php echo $BillBookType;?>');"> <!--
                       onchange="getLedgerName(this.value,'<?php echo $BillBookType;?>');"
            onchange=generateCode(this.value,'<?php //echo $VPrefix; ?>')-->
        <option value=""> Select</option>
        <?php 
          while($row_branch=DB_fetch_array($sql_state))
          {
             $p='';
             if($row_branch['loccode']==$row_fetch['branch'])
             $p='selected';
            echo "<option value='".$row_branch['loccode']."' $p >".$row_branch['locationname']."</option>";
          }?>
  </select> 
  </td>
    <td width="13%" align="right"><strong>Voucher No.</strong></td>
    <td width="20%"><input name="voucher_no" type="text"  value="<?php echo $row_fetch['voucher_no']; ?>" id="voucher_no" style="width:98%;"  readonly='true'/></td>
    <td width="13%" align="right"><strong>Date</strong></td>
    <td><input name="Dates" id="Dates" type="text" style="width:98%;" class="datepicker" value="<?php echo date('d/m/Y',strtotime($row_fetch['voucher_date']));?>"  
     onchange="validate_date(this.id)" onkeypress="return isNumberKey1(event)" placeholder="dd/mm/yyyy" /></td>
</tr>
<tr class="row1">
     <td align="right"><strong>Funding By/To</strong></td>
    <td><select name="funding_by" id="funding_by" style="width:98%;">
            <option value="0">Select</option>
           <?php 
               $sql_client=DB_query("select AccountsID as id,AccountName as c_name
                  from accountledger where vender_client in(select id from clientmaster) and ledgertype='client' ",$db);
               while($result_client=DB_fetch_array($sql_client))
               {
           ?>   
            <option value="<?php echo $result_client['id']; ?>" <?php if($row_fetch['funding_by']==$result_client['id']) { ?> selected="selected" <?php }?> ><?php echo $result_client['c_name']; ?></option>
            <?php } ?> 
            </select>
    </td>
    <td align="right"><strong>Budget No.</strong></td>
    <td>
        <select name="Ref_no" id="Ref_no" style="width:98%;">
         <option value="0">Select</option>
        <?php
                $sql_budget="select * from account_budget_entry";
                $result_budget=DB_query($sql_budget,$db);
                while($rs_budget=DB_fetch_array($result_budget))
                {
           ?> 
            <option value="<?php echo $rs_budget['id']; ?>" <?php if($row_fetch['budget_id']==$rs_budget['id']) { ?> selected="selected" <?php } ?> ><?php echo $rs_budget['budget_no']; ?></option>
              <?php } ?>
          </select> 
    </td>
    <td align="right"><strong>Ref. Date</strong></td>
    <td><input name="ref_date" id="ref_date" type="text"  style="width:98%;" value="<?php echo date('d/m/Y',strtotime($row_fetch['budget_date']))  ?>"  onchange="validate_date(this.id)" onkeypress="return isNumberKey1(event)"  class="datepicker" placeholder="dd/mm/yyyy" /></td>  
</tr>
</table>
<p align="left">
  <input type="button" name="profile_popup" value="Pick Items" id="profile_popup"  onclick="open_items()" class="search" />
  <input type="button" class="search"   onclick="deleteRowOrder('dataTable');getSumT()" value="Delete" />
  <input type="hidden" id="multipledr" value="true" > 
</p>

<table width="100%" border="1" cellpadding="3" cellspacing="0" style="border:#808080 1px solid; border-collapse:collapse; background:#fff;" id="tableDataProduction">   
  <tr>  
    <th width="5%">S. No.</th>
    <th width="1"></th>
    <th width="15%">Code</th>
    <th>Category Name</th>
    <th width="10%">Budget Amount</th>
    <th width="10%">Funding Amount</th>
    <th width="25%">Remarks</th>
  </tr>

  <tbody id="dataTable">
   <?php
      $i=1;
     // echo "select * from account_fund_receipt_dtls where fund_receipt_dtls_id='".$_REQUEST['id']."'";
      //echo "select * from account_fund_receipt_dtls where fund_receipt_dtls_id='".$_REQUEST['id']."'";
      $sql_child=DB_query("select * from account_fund_receipt_dtls where fund_receipt_dtls_id='".$_REQUEST['id']."'",$db);
      while($row_child=DB_fetch_array($sql_child))
      { 
        //echo $row_child['category_id'];

         $code=$s->getField('account_cost_category','id',$row_child['category_id'],'code');
        $category_name=$s->getField('account_cost_category','id',$row_child['category_id'],'category_name');
       
       ?>
  <tr bgcolor="#fff">
    <td><input name="delitem[]" type="checkbox" /></td>
    <td><input type="hidden" name="mstitemid[]" id="itemid" value="<?php echo $row_child['category_id']; ?>"></td>
    <td><input type="text" name="code[]" id="code" value="<?php echo $code; ?>" style="width:98%;"></td>
    <td><input type="text" name="category_name[]" id="categoryname" style="width:98%;" value="<?php echo $category_name; ?>"/></td>
    <td><input type="text" name="budget_amount[]" id="budgetamount" style="width:98%;" value="<?php echo $row_child['budgeted_amount']; ?>"/></td>
    <td><input type="text" name="funding_amount_sub[]" id="fundingamountsub" class="sum_funding_amount"  onkeyup="calculateAmount(this.id)"; style="width:98%;" value="<?php echo $row_child['funding_amount']; ?>" /></td>
    <td><textarea name="remarks[]" id="remarks" rows="5" cols="20" style="width:98%;"><?php echo $row_child['remarks']; ?></textarea></td>
    </tr>
   <?php $i++; } ?> 
  </tbody>
</table>
<input type="hidden" name="hiditemcount1" id="hiditemcount" value="<?php echo $i+1; ?>" />
 <input type="hidden" name="" value="<?php echo $i+1; ?>" id="edit_cnt" />
   <input type="hidden" name="rowcount1" id="rowcount1" value="<?php echo $i+1; ?>" />
<br>
  <!--<div id='hid-Bankdetails'>-->
<table width="100%" cellpadding="3" cellspacing="0" border="0" style="border:0;">  
<tr class="row1">
    <td width="13%" align="right"><strong>Funding Amt.</strong></td>
    <td width="20%" id="INSNO"><input type="text" name="funding_amt" style="width:98%;" value="<?php echo $row_fetch['funding_amount'];?>"  id='funding_amt'  /></td>    
    <td width="13%" align="right"><strong>Type</strong></td>
    <td width="20%" id="INSNO">
                      <select name="type" id="type" style="width:98%">
                        <option value="0">Select</option>
                        <option value="Receipt" <?php if($row_fetch['type']=='Receipt') {?> selected="selected" <?php } ?>>Receipt</option>
                        <option value="Payment" <?php if($row_fetch['type']=='Payment') {?> selected="selected" <?php } ?>>Payment</option>
                     </select>  
               </td>    
     <td width="13%" align="right"><strong>Revenue Head</strong></td>
    <td>
         <select name="revenue_head" id="revenue_head" style="width:98%;">
          <option value="0">Select</option>
          <?php 
                  $sql_ledger="select AccountsID,Accountname,ledgertype from accountledger where ledgertype in ('income','bank') order by Accountname";
                  $result_ledger=DB_query($sql_ledger,$db);
                  while($rs_ledger=DB_fetch_array($result_ledger))
                  {
                    ?>
                    <option value="<?php echo $rs_ledger['AccountsID']; ?>" <?php if($row_fetch['revenue_head']==$rs_ledger['AccountsID']) { ?> selected="selected" <?php } ?> ><?php echo $rs_ledger['Accountname']; ?></option>
                   <?php   

                  }
          ?>
        </select>  
    </td>
  </tr>
<tr class="row1">
    <td align="right"><strong>Narration</strong></td>
    <td colspan="5"><textarea name="narration" id="narration" cols="95" rows="5" style="width:99%; height:50px;" ><?php echo $row_fetch['narration'];?></textarea></td>
    </tr>
        </table>

<p style="text-align:center;">
  <input type="submit" name="save" value="Update" class="search" onclick="return validateForm();"/>
</p>
<?php 

 //if(array_sum($total_cr)==array_sum($total_dr)  && (array_sum($total_cr)!=0 && array_sum($total_dr)!=0)) {?>
  
 <?php //}?>
</form>
</div>
</div>



<script language="javascript" type="text/javascript">

 function open_items()
{

  if(document.getElementById("Branch").value=='0')
  {
    alert("Please Select Branch First"); 
  }
  else
  { 
    //window.open("directTelephonicItems_direct.php?modid=<?php echo $_REQUEST['modid'];?>&frmid=<?php echo $_REQUEST['frmid'] ?>&action=<?php echo $_REQUEST['action']?>","itempopup_window","height=500,width=600,toolbar=no,menubar=no,dependent=yes,resizable =yes, scrollbars=yes");

    $("#PickedItems").dialog({
      title:'Item List',
      modal: true,
      resizable: false,
      width:900,
      height:400,
      closeText: 'fechar',
      draggable: true,
      show: 'fade',
      hide: 'fade',
      dialogClass: 'main-dialog-class',
      buttons: {
        Exit: function()
        {
          $(this).dialog("close");
        }
      }
    });
    
     var budget_no=document.getElementById("Ref_no").value;
  //  var site=document.getElementById("Branch").value;
  //  var party=document.getElementById("Client").value;
   // var date=document.getElementById("TelephonicDate").value;


    $.post('fund_receipt_code.php?id='+budget_no,function(data){
      $('#PickedItems').html(data);
    });
    


  }
}

function getItemsList(obj,id,code,shade,ctr,amount)
{  
//alert(code);
  var dup='empty';
  var itemcount=parseInt(document.getElementById('rowcount1').value)+1;
  var edit_cnt=document.getElementById('edit_cnt').value;
  //alert(itemcount);
  if(edit_cnt=='')
  {
    var counter=1;
  } 
  else if(edit_cnt>itemcount)
  {
    var counter=edit_cnt;
    var itemcount=parseFloat(counter)+parseFloat(itemcount);
  }
  else
  {
    var counter=edit_cnt;
  }
     //   alert(edit_cnt);
  //alert(counter);
        //alert(itemcount);
//IF WE CHECK THE CHECK BOX FOR SELECT ANY ITEM***********************START HERE******************************************
  if(document.getElementById("row_id_"+ctr).checked==true)
  {
    // alert(edit_cnt); 
    if(document.getElementById('itemid') && document.getElementById('itemid').value=='')
    {
      if(edit_cnt=='')
      {
        var counter=0;
      }
    
      for(var j=0; j<counter; j++)
      {
        if(document.getElementById('itemid1_'+j).value==id)
        {
          alert("Duplicate Value"); 
          document.getElementById("row_id_"+ctr).checked=false;
          var dup = "dup";
          break;
        }
      }
      //alert(dup);
      if(dup=='empty')
      { 
        //var data=addRow('dataTable');
        document.getElementById('itemid').value = id;
        document.getElementById('code').value = code;
        document.getElementById('categoryname').value =  shade; 
        document.getElementById('budgetamount').value = amount; 
        
        
      }
    } 
    
    else
    {               
               
    
    
      for(var i=counter; i<=itemcount; i++)
      { 
      
      
        if(edit_cnt=='')
        {
          var counter=0;
        }
                                
        for(var j=0; j<=itemcount; j++)
        {
          //alert(j);
                   if(document.getElementById('itemid_'+j))
          {
                                  
          if(document.getElementById('itemid_'+j).value==id)
          {        
                          var dup = "dup";
            
          }
                                
        }            

                 }

        if(document.getElementById('itemid'))
        {
          if(document.getElementById('itemid').value==id)
          {      
                      var dup = "dup";
            alert("Duplicate Value");
            document.getElementById("row_id_"+ctr).checked=false;
            break;
          }
        }
        
        if(dup=="dup")
        {
          alert("Duplicate Value"); 
            document.getElementById("row_id_"+ctr).checked=false;
            break;
        }
        //alert(dup);
        if(dup=='empty')
        {
        if(!document.getElementById('itemid_'+i))
        {         
        var data= addRow('dataTable');  
        }
          if(document.getElementById('itemid_'+i))
          { 
          
          if(document.getElementById('itemid_'+i).value=='')
          { 
            document.getElementById('itemid_'+i).value = id;
            document.getElementById('code_'+i).value = code;
            document.getElementById('categoryname_'+i).value = shade;
            document.getElementById('budgetamount_'+i).value = amount;
            //document.getElementById('instrumentname_'+i).value = desc;  
                        
            break;
          }
          }
          else
          {
            continue;
          }
        }
      }
    }
  }
  
//IF WE CHECK THE CHECK BOX FOR SELECT ANY ITEM***********************END HERE******************************************


//IF WE UNCHECK THE CHECK BOX FOR DESELECT ANY ITEM***********************START HERE******************************************
  else
  {
    if(document.getElementById('itemid').value==document.getElementById("row_id_"+ctr).value)
    {
          document.getElementById('itemid').value = '';
        document.getElementById('code').value = '';
        document.getElementById('categoryname').value = ''; 
        document.getElementById('budgetamount').value = '';
       
      //document.getElementById('instrumentname').value = '';
    }
    else
    {
      for(var i=counter; i<=itemcount; i++)
      {


        if(document.getElementById('itemid_'+i).value==document.getElementById("row_id_"+ctr).value)
        {
          
         document.getElementById('itemid').value = '';
        document.getElementById('code').value = '';
        document.getElementById('categoryname').value = ''; 
        document.getElementById('budgetamount').value = '';
        
          //document.getElementById('instrumentname_'+i).value = '';
        }
      }
    }
  }
//IF WE UNCHECK THE CHECK BOX FOR DESELECT ANY ITEM***********************END HERE******************************************
}
function addRow(tableID) 
  {
  if(document)
  var table = document.getElementById(tableID);
  var rowCount = table.rows.length;
  var rowCount = table.rows.length;
  if(document.getElementById("hiditemcount").value=='')
  r =rowCount+1;
  else
  {
  var t=0;
  var t1=document.getElementById("hiditemcount").value;
  r=parseInt(t1)+parseInt(t)+1;
  }
  var row = table.insertRow(rowCount);
  document.getElementById("hiditemcount").value=r;
  document.getElementById("rowcount1").value=r+1;
  var colCount = table.rows[0].cells.length;
  for(var i=0; i<colCount; i++) {   
  var newcell = row.insertCell(i);
  //newcell.style.background='#e7e7e7';
  //newcell.className='tabledata1';
  newcell.innerHTML = table.rows[0].cells[i].innerHTML;
  //alert(newcell.childNodes[0].type);
  switch(newcell.childNodes[0].type) 
  {
  case "text":
  newcell.childNodes[0].value = "";
  var nod_id = newcell.childNodes[0].id.split("_");
  newcell.childNodes[0].id = nod_id[0]+'_'+r;
  break;   
  case "textarea":
  newcell.childNodes[0].value = "";
  var nod_id = newcell.childNodes[0].id.split("_");
  newcell.childNodes[0].id = nod_id[0]+'_'+r;
  break;   
  case "hidden":
  newcell.childNodes[0].value = "";
  var nod_id = newcell.childNodes[0].id.split("_");
  newcell.childNodes[0].id = nod_id[0]+'_'+r;
  break;
  case "button":
  var nod_id = newcell.childNodes[0].id.split("_");
  newcell.childNodes[0].id = nod_id[0]+'_'+r;
  break;
  case "checkbox":
  newcell.childNodes[0].checked = false;
  var nod_id = newcell.childNodes[0].id.split("_");
  newcell.childNodes[0].id = nod_id[0]+'_'+r;
  break;
  case "select-one":
  
  newcell.childNodes[0].selectedIndex = 0;
  var nod_id = newcell.childNodes[0].id.split("_");
  newcell.childNodes[0].id = nod_id[0]+'_'+r;
  break;  
  }
    //document.getElementById("stock_perunit_"+rowCount).value=1;
  }
  //document.getElementById("AccType_"+r).value='DR';
} 

function getdataforSearch()
{  
  var group=document.getElementById('under_group').value;
  var code=document.getElementById('asset_code').value;
  var name=document.getElementById('asset_name').value;
  //var title=document.getElementById('title').value;
  //var titletext=document.getElementById('title_text').value;

  
  var xmlhttp;
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
  else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
  {
  var data=xmlhttp.responseText;   
  document.getElementById("ItemListDiv").innerHTML=data;
  }
  }
  xmlhttp.open("GET","cost_search_issue.php?code="+code+"&name="+name+"&under_group="+group,true);
  xmlhttp.send();
} 


function get_budget_date(str)
{  
  //alert("hi");
  var xmlhttp;
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
  else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
  {
  var data=xmlhttp.responseText;   
  document.getElementById("ref_date1").innerHTML=data;
  }
  }
  xmlhttp.open("GET","get_budget_date.php?id="+str,true);
  xmlhttp.send();
} 

function calculateAmount()
{
   var sumOfArea=0;
  
  $('#tableDataProduction').find('input[type="text"][class="sum_funding_amount"]').each(function(){
    if($(this).val()!='')
    sumOfArea= sumOfArea + parseFloat($(this).val());
    else
    sumOfArea= sumOfArea;
    });

   
    document.getElementById("funding_amt").value=sumOfArea.toFixed(2);
   
}

</script>