<?php  use Cake\ORM\TableRegistry;
    $bproducts = TableRegistry::get('Branches'); 
    $uproducts = TableRegistry::get('Users');
    $brproducts = TableRegistry::get('Brokers');  	
?>

<?php  //use Cake\ORM\TableRegistry;
    //$products = TableRegistry::get('Filenames');  
?>
<nav class="large-3 medium-4 columns" id="actions-sidebar">
      <?= $this->element('admin_sidebar') ?>
</nav>
<div class="customers index large-9 medium-8 columns content">
<div class="col-md-6">
    <h3><?= __('Brokerage Reconciliation Data') ?></h3>
    </div>

    <div class="search-wrapper">
<div class="col-md-6">
        <?php
        $export = array_merge($this->request->query,array('export' => 'xls'));
        $exportpdf = array_merge($this->request->query,array('export' => 'pdf'));
        ?>
        <div class="btn-link">
        <?= $this->Html->link(__('Excel Export'),['controller' => 'Fds', 'action' => 'brkreconciliationexceldata','?'=>$export],['class'=>'green-btn']); ?>
        <?= $this->Html->link(__('Pdf Export'),['controller' => 'Fds', 'action' => 'brkreconciliation','?'=>$exportpdf],['class'=>'green-btn']); ?>
        </div> </div>
        <div class="search-filter"><?= $this->Search->filterForm($searchFilters) ?></div>         
   
</div>
    <table cellpadding="0" cellspacing="0">
        <thead>
        	<tr>
		<th scope="col" colspan="4"><b>
			  
			  <div style="clear: both;">Report: Date Range Wise Brokerage Reconciliation Data</div>
</th>			  
<th scope="col" colspan="2"><b>
			  	  
			  <?php 
			  if($customer_name != '')
			  {
				
				echo 'Investor Name :'.$customer_name;
			  }
			  else{
			  echo 'Investor Name : all' ;
			  }
			  
			  ?></b>
			  </th>
			  <th scope="col" colspan="2"><b>
			  
			 
			  
			  <?php 
			 
                 if($companyname != ''){
                           echo 'Company Name :'.$companyname;
						   }
						   else{
                    echo 'Company Name : all';
                 }
                  ?></b></th>
              <th scope="col" colspan="6"><b>
			  <?php 
			 
                 if($datedform != '' && $datedto != '' ){
                             echo 'Date :  '.$dated2;
						   echo ' - '.$dated1; 
                          // echo 'Date :  '. $datedform;
						   //echo ' - '.$datedto;     
						   }
						   else{
                     echo 'Date : all' ;
                 }
                  ?></b></th>
				  				 
				  </tr>
            <tr>
                <th style="width:40px;" scope="col"><?= $this->Paginator->sort('Sr No') ?></th>
                <th scope="col"><?= $this->Paginator->sort('Investor Name') ?></th>
                <!--<th scope="col"><?= $this->Paginator->sort('Pan No') ?></th>-->
				<th scope="col"><?= $this->Paginator->sort('Company Name') ?></th>
				<!--<th scope="col"><?= $this->Paginator->sort('Instrument Type') ?></th>-->
				<th scope="col"><?= $this->Paginator->sort('Institution Name') ?></th>
                <th scope="col"><?= $this->Paginator->sort('Investment Date') ?></th>
			    <!--<th scope="col"><?= $this->Paginator->sort('Payment Mode') ?></th>-->
				<!--<th scope="col"><?= $this->Paginator->sort('Cheque No') ?></th>-->
				<!--<th scope="col"><?= $this->Paginator->sort('UTR/FDR No') ?></th>-->
				<th scope="col"><?= $this->Paginator->sort('Investment Amount') ?></th>
				<th scope="col"><?= $this->Paginator->sort('Tenure') ?></th>
				<!--<th scope="col"><?= $this->Paginator->sort('Maturity Date') ?></th>-->
				<th scope="col"><?= $this->Paginator->sort('Despatch Date') ?></th>
				<!--<th scope="col"><?= $this->Paginator->sort('Address') ?></th>-->
				<!--<th scope="col"><?= $this->Paginator->sort('Product name') ?></th>-->
				<!--<th scope="col"><?= $this->Paginator->sort('Investment Branch') ?></th>-->
				<th scope="col"><?= $this->Paginator->sort('Branch User') ?></th>
				<!--<th scope="col"><?= $this->Paginator->sort('Sub Broker Name') ?></th>-->
				<th scope="col"><?= $this->Paginator->sort('Brokerage') ?></th>
				<th scope="col"><?= $this->Paginator->sort('Actions') ?></th>
            </tr>
        </thead>
        <tbody>
            <?php   $srlno = ($this->request->params['paging']['Mtables']['page']-1) * $this->request->params['paging']['Mtables']['perPage'];
            $j=1;
            foreach ($mdatas as $mdata): $srlno++; if(!$mdata->branch_id > 0){ $trstyl = "style='background:#dbefec;'";$tdstyl = "style='color:#000;'"; }else{$trstyl = "style='background:none;'";$tdstyl = "style='color:#000;'";} ?>
            <tr <?= $trstyl ?>>
                <td <?= $tdstyl ?>><?= $srlno ?></td>
                <td <?= $tdstyl ?>><?= h($mdata->customer_name) ?></td>
               <!-- <td <?= $tdstyl ?>>
                    <!--<?= h($mdata->pan_no) ?>
                    <?php
                    $rowid = $mdata->id;
                    $pannofieldidedit = $rowid.'___pan_no___edittext';
                    $pannofieldid = $rowid.'___pan_no';
                    $pannovalue = '';
                    $panvaluetext = $rowid.'___pan_no___valuetext';
                    $pannofieldideditsubbutton = $rowid.'___pan_no___textfieldeditsubbutton';
                    if(!empty($mdata->pan_no)){
                        $pannovalue = $mdata->pan_no;
                    }
                    echo "<span id='$panvaluetext'>".$pannovalue."</span>"."<input class='edittextfield' type='text'  value='".$pannovalue."' id='".$pannofieldidedit."'  maxlength='10' style='display:none'/><a class='edit editbutton' id='".$pannofieldid."' title='Edit'></a><a class='green-btn submitedittextfieldbutton' id = '".$pannofieldideditsubbutton."' href='javascript:void(0)' style='display:none;'>Update</a>"; ?>
                    
                </td>-->
				<td <?= $tdstyl ?>><?= $filenames[h($mdata->csvid)] ?></td>
               <!-- <td <?= $tdstyl ?>><?= h($mdata->instrument_type) ?></td>-->
                <td <?= $tdstyl ?>>
                    <?php
                    /*$defaultInstitutionCompany = array(3,17,19);
                    if(in_array(h($mdata->csvid),$defaultInstitutionCompany)){
                        echo $filenames[h($mdata->csvid)];
                    }else {
                        echo h($mdata->institution_name);
                    }*/
                    echo h($mdata->institution_name);
                    ?>
                </td>
                <td <?= $tdstyl ?>><?= h($mdata->application_date) ?></td>
				<!--<td <?= $tdstyl ?>><?= h($mdata->payment_mode) ?></td>-->
				<!--<td <?= $tdstyl ?>><?= h($mdata->cheque_no) ?></td>-->
				<!--<td <?= $tdstyl ?>><?= h($mdata->utr_fdr_no) ?></td>-->
				<td <?= $tdstyl ?>><?= h($mdata->investment_amount) ?></td>
				<td <?= $tdstyl ?>><?= h($mdata->period) ?></td>
				<!--<td <?= $tdstyl ?>><?= h($mdata->maturity_date) ?></td>-->
				<td <?= $tdstyl ?>><?= h($mdata->despatchdate) ?></td>
				<!--<td <?= $tdstyl ?>><?= h($mdata->address) ?></td>-->
				<!--<td <?= $tdstyl ?>><?= h($mdata->product_name) ?></td>-->
				<!--<td><?//= h($mdata->branch_id) ?></td>-->
	    <td>
		<?php
			/*if($mdata->branch_id > 0){
				
				$bproductids = explode(",",  $mdata["branch_id"]);
				foreach($bproductids as $bproductid){
				$bproductdata = $bproducts->find()->where(['id' => $bproductid]);
				$bdata2 = $bproductdata->toArray();
				echo $bproductname = $bdata2[0]->branchname;
				}
			}*/
			
			$columname = 'branch_id';
            $fieldid = $mdata->id.'___'.$columname;
            echo $this->Form->input('branch_id',['class' => __('add-column cbranch'),'empty'=>'Choose branch','label' => false,'options' => $branches,'id'=>$fieldid,'value'=>$mdata->branch_id]);
		?>
	            </td>
				<!--<td>
				
				<?php
			if($mdata->modifiedby > 0){
				
				$uproductids = explode(",",  $mdata["modifiedby"]);
				foreach($uproductids as $uproductid){
				$uproductdata = $uproducts->find()->where(['id' => $uproductid]);
				$udata2 = $uproductdata->toArray();
				//echo $uproductname = $udata2[0]->firstname;
				}
			     }
		        ?>
				</td>-->
				
				<!--<td>
				<?php
			if($mdata->sub_broker > 0){
				
				$brproductids = explode(",",  $mdata["sub_broker"]);
				foreach($brproductids as $brproductid){
				$brproductdata = $brproducts->find()->where(['id' => $brproductid]);
				$brdata2 = $brproductdata->toArray();
				echo $brproductname = $brdata2[0]->name;
				}
			     }
		        ?>
				</td>-->
				  <td>
				    <?= $this->Form->create() ?>
                    <?=$this->Form->input('Reconciliation', ['class'=>'rcncilatn','id'=>$mdata->id, 'label' => false ,'empty' => 'Select Brokerage', 'options' => ['Brokerage Received'=>'Brokerage Received','Brokerage Not Received'=>'Brokerage Not Received','Brokerage Mismatch'=>'Brokerage Mismatch','Partial Brokerage'=>'Partial Brokerage','next month'=>'next month'],'value'=>$mdata->reconciliation]);?>
                    <?= $this->Form->end() ?>
                </td>
				
				<td class="actions">
                    <?= $this->Html->link(__('Edit'), ['action' => 'brfdedit', $mdata->id], ['class' => 'edit','title'=>__('Edit')]) ?>
                    <?= $this->Html->link(__('View'), ['action' => 'brfdview', $mdata->id], ['class' => 'view','title'=>__('View')]) ?>
                </td>
               </tr>
            <?php $j++;
            endforeach; ?>
        </tbody>
    </table>
<div class="btn-link"><input type="button" value="Back" onclick="window.history.back()" class="green-btn" /> </div>
    <div class="paginator">
        <ul class="pagination">
           <?= $this->Paginator->first(__('First', true), array('class' => 'disabled')); ?>
            <?= $this->Paginator->prev('< ' . __('previous',true), array('class' => 'disabled')) ?>
            <?= $this->Paginator->numbers() ?>
            <?= $this->Paginator->next(__('next' . ' >',true), array('class' => 'disabled')) ?>
		 <?=  $this->Paginator->last(__('Last', true), array('class' => 'disabled')); ?>
        </ul>
        <p><?= $this->Paginator->counter() ?></p>
    </div>
</div>

<script>
$(document).ready(function() { 
    
    /*---------Quick Edit---------*/
    $('.editbutton').click(function() {
        //alert('test');
        var idname = $(this).attr('id');
        var idspec = '#' + idname + '___edittext';
        $(idspec).fadeToggle();

        var idbuttonspec = '#' + idname + '___textfieldeditsubbutton';
        $(idbuttonspec).fadeToggle();
    });

    $(".submitedittextfieldbutton").click(function() {
        var inputfieldid = $(this).attr('id');

        var res = inputfieldid.split("___");
        var rowid = res[0];
        var fieldname =  res[1];
        var idinputspec = '#'+rowid+'___'+fieldname+'___edittext';
        var valueofinput = $(idinputspec).val();
        var idspanspec = '#'+rowid+'___'+fieldname+'___valuetext';
        var siteUrl = '<?php echo $this->Url->build('/', true) ?>';
        if(valueofinput==''){
            alert('Please enter value first!');
            return false;
        }
        if(fieldname == 'pan_no' && valueofinput.length!=10){
            alert('Please enter correct Pan No');
            return false;
        }
        jQuery.ajax({
            type: 'POST',
            url: siteUrl+'fds/updatefielddata',
            data: {
                rowid: rowid,
                fieldname: fieldname,
                valueofinput: valueofinput
            },
            success: function(data) { //console.log(data);
                //alert('Data Updated');
                //window.location.reload()
                $(idinputspec).fadeToggle();
                $('#'+inputfieldid).fadeToggle();
                $(idspanspec).html(valueofinput);
            },
            error: function(jqxhr, status, exception) {
                alert('Exception:', status);
            },
            statusCode: {
                404: function() {
                    alert(message.noPage);
                }
            }
        });
    });

    /*---------Quick Edit End---------*/
    
 $('.rcncilatn').change(function() { 
    
        var rid = this.id;
        var reconciliation = $(this).val();
        var userid = <?=$userid?>;
       
        //var siteUrl = window.location.host;
		var siteUrl = '<?php echo $this->Url->build('/', true) ?>';
        jQuery.ajax({
            type: 'POST',
			url: siteUrl+'fds/updatereconciliation',
            data: {
                reconciliation: reconciliation,
                rid: rid,
                userid: userid
            },
            dataType: 'json',
            success: function(data) {
                alert('reconciliation Updated');
            },
            error: function(jqxhr, status, exception) {
                alert('Exception:', status);
            },
            statusCode: {
                404: function() {
                    alert(message.noPage);
                }
            }
        });
    });
    
    $(".cbranch").change(function() {
        var inputfieldid = $(this).attr('id');
        var idinputspec = '#'+inputfieldid;
        var valueofinput = $(idinputspec).val();
        var res = inputfieldid.split("___");
        var rowid = res[0];
        var fieldname =  res[1];

        var bid=valueofinput;
        var rid=rowid;
        var userid = <?=$userid?>;

        var siteUrl = '<?php echo $this->Url->build('/', true) ?>';
        jQuery.ajax({
            type: 'POST',
            url:siteUrl+'/fds/updatebranch',
            data: {
                bid: bid,
                rid: rid,
                userid: userid
            },
            dataType: 'json',
            success: function(data) {
                //console.log(data['result']['result']);
                if(fieldname=='branch_id'){
                    
                    if(data['result']['result'] == 'error'){
                        alert('Branch Not Updated Some Error Occurs or Pan No not Exist');
                    }else{
                        alert('Branch Updated');
                    }
                    
                    
                }else{
                    alert('Data Updated');
                }
            },
            error: function(jqxhr, status, exception) {
                alert('Exception:', status);
            },
            statusCode: {
                404: function() {
                    alert(message.noPage);
                }
            }
        });
    });
    
      $("form").submit(function() {
        // e.preventDefault();

        if (($('#datedform').val() && $('#datedto').val()) && ($('#inv-datedform').val() && $(
                '#inv-datedto').val())) {
            alert("Please Select Maturity or Investment  Date");
            return false;
        }

        if ($('#datedform').val()) {
            if ($('#datedto').val() == '') {
                alert("Please choose End date for report");
                return false;
            }
        }

        if ($('#inv-datedform').val()) {
            if ($('#inv-datedto').val() == '') {
                alert("Please choose End date for report");
                return false;
            }
        }
		
    });
    
});

var availableTags = <?=json_encode($custname)?>;
//console.log(availableTags);
    $( "#autocomplete1" ).autocomplete({
      //source: availableTags,
      source: function(request, response) {
        var results = $.ui.autocomplete.filter(availableTags, request.term);

        response(results.slice(0, 10));
    }
    });
</script>
