<?php  use Cake\ORM\TableRegistry;
$user1 = $this->request->session()->read('Auth.User');
$user  = TableRegistry::get('Users');
$banks = TableRegistry::get('Banks');
//$filename  = TableRegistry::get('Filenames');
$companies = TableRegistry::get('Companies');
$branches = TableRegistry::get('Branches');
$scheme = TableRegistry::get('Mffunds');
$mtables = TableRegistry::get('Mtables');
$fds = TableRegistry::get('Fds');
?>
<?= $this->Html->script('schemeload.js'); ?>
<script>
    $(document).ready(function() {
		
		/* $("#autocomplete1").change(function(){ 
			$("#pan_no").val('');
			$('#pan_no').empty();
			if($('#autocomplete1').val().length > 0){				
				$('#minor').val(null).trigger('change');
			}			  
		}); */
		
		/* $("#minor").change(function(){ 
			$("#pan_no").val('');
			$('#pan_no').empty();
			if($('#minor').val().length > 0){				
				$('#autocomplete1').val(null).trigger('change');
			}		  
			
		}); */
		
		
        $('.printButton').on('click', function() {
            var visible =  $('#actions-sidebar,.search-wrapper').toggle().is(":visible");
            if(visible){
                $('.daily').css('width','83%');
            }else{
                $('.daily').css('width','100%');
            }
        });


        $("form").submit(function(){
            // e.preventDefault();
            //if($('#applicants').val() ==''){
                if($('#autocomplete1').val() =='' && $('#minor').val() ==''){
					alert("Please choose the applicant for report");
					return false;
				}else if($('#autocomplete1').val().length > 0 && $('#minor').val().length){
					alert("Please choose either applicant name or minor name. Not both!");
					return false;
				}
            
            /*
            if($('#datedform').val()){
                if($('#datedto').val() == ''){
                    alert("Please choose End date for report");
                    return false;
                }}*/
                
            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;
            }}    

        });
    });
</script>
<style>
    h3.heading{
        font-size:17px !important;
        padding:0 !important;
        margin-bottom: 0px;
        border-left: 1px !important;
    }

</style>
<nav class="large-3 medium-4 columns" id="actions-sidebar">
    <?= $this->element('admin_sidebar') ?>
</nav>
<div class="fds index large-9 medium-8 columns content">
    <div class="col-md-6">
        <h3><?= __('Client Portfolio') ?></h3>
    </div>
    <div class="col-md-6"><!--
	<div class="btn-link">
	<button onclick="print_function()" class="green-btn print-btn">Print</button>
</div> -->
        <?php
        $export = array_merge($this->request->query,array('export' => 'xls'));
        $exportpdf = array_merge($this->request->query,array('export' => 'pdf'));
        ?>
        <div class="btn-link">
            <!--<input type="button" value="Back" onclick="window.history.back()" class="green-btn" /> -->
            <?= $this->Html->link(__('Excel Export'),['controller' => 'Reports', 'action' => 'clientwisefd','?'=>$export],['class'=>'green-btn']); ?>
            <?= $this->Html->link(__('Pdf Export'),['controller' => 'Reports', 'action' => 'clientwisefd','?'=>$exportpdf],['class'=>'green-btn']); ?>
        </div>
    </div>
    <div class="search-wrapper">
        <div class="search-filter" style="width: 88%;"><?= $this->Search->filterForm($searchFilters) ?></div>
    </div>
    <?php if(!empty($result)): ?>
        <table class="tbl-wrapper" cellpadding="0" cellspacing="0">
            <thead>
            <tr>
                <th scope="col" colspan="2"><b><div style="clear: both;"><center><h3 class="heading">ABN INVESTMENT</h3></center></div></th>
            </tr>
            <tr>
                <th scope="col" style="width:10%;">CLIENT NAME </th><th ><span style="font-weight: normal;">
								<?php 
									if($customer_name != '' && $customer_name != 'all'){
										echo $customer_name; 
									}elseif($minor_name != '' && $minor_name != 'all'){
										echo !empty($result['fd'][0]['fapplicantname']) ? $minor_name.' U/G '.$result['fd'][0]['fapplicantname'] : $minor_name; 
									}else {
										echo '';
									} ?>
								</span></th>
            </tr>
            <tr>
                <th scope="col" style="width:10%;">PAN NO</th>
                <th scope="col" style="font-weight: normal;">
                    <?php if($applicant_pan != '' && $applicant_pan != 'all'){
                        echo $applicant_pan; }
                    else {
                        echo '';} ?>
                </th>
            </tr>
            <tr>
                <th scope="col" style="width:10%;">ADDRESS</th>
                <th scope="col" style="font-weight: normal;">
                    <?php if($applicant_pan != '' && $applicant_pan != 'all'){
                        $applicant_pan_no = $mtables->find()->where(['pan_no' => $applicant_pan]); 
                        $applicantbr = $applicant_pan_no->toArray(); //pr($applicantbr);
                        $address_combined = !empty($applicantbr[0]->address) ? $applicantbr[0]->address.', ': '';
                        if(!empty($applicantbr[0]->add1)){
                            $address_combined .= ' '. $applicantbr[0]->add1;
                        }
                        if(!empty($applicantbr[0]->add2)){
                            $address_combined .= ', '. $applicantbr[0]->add2;
                        }
                        if(!empty($applicantbr[0]->add3)){
                            $address_combined .= ', '. $applicantbr[0]->add3;
                        }

                        if(!empty($applicantbr[0]->city)){
                            $address_combined .= ', '. $applicantbr[0]->city;
                        }

                        if(!empty($applicantbr[0]->region)){
                            $address_combined .= ', '. $applicantbr[0]->region;
                        }

                        if(!empty($applicantbr[0]->pin)){
                            $address_combined .= ', '. $applicantbr[0]->pin;
                        }
                        echo  $address_combined; }else {
                        echo '';} ?>
                </th>
            </tr>
            <tr>
                <th scope="col" style="width:10%;">MOBILE NO</th>
                <th scope="col" style="font-weight: normal;">
                    <?php
                    echo $applicantbr[0]->mobileno;?>
                </th>
            </tr>
            </thead>
        </table>

        <div class="row">

            <div class="col-md-12">
                <h7><?= __('PORTFOLIO AS ON ').date('d/m/Y'); ?></h7>
            </div>
        </div><br>

        <table class="tbl-wrapper" cellpadding="0" cellspacing="0">
            <thead>
            <tr>
                <th scope="col" colspan="9"><b><?php echo 'FD';?></b></th>
            </tr>
            <tr>
                <th scope="col" style="width:3%;"><?= $this->Paginator->sort('Sr No') ?></th>
                <th scope="col"><?= $this->Paginator->sort('Institution Name') ?></th>
                <th scope="col" style="width:10%;"><?= $this->Paginator->sort('Instrument Type') ?></th>
                <th scope="col"><?= $this->Paginator->sort('Investment Date') ?></th>
                <th scope="col"><?= $this->Paginator->sort('Investment Amount') ?></th>
                <th scope="col" style="width:4%"><?= $this->Paginator->sort('Tenure') ?></th>
                <th scope="col"><?= $this->Paginator->sort('Maturity Date') ?></th>
                <th scope="col" style="width:20%"><?= $this->Paginator->sort('Investor Remark') ?></th>
            </tr>
            </thead>
            <tbody>
            <?php $j=1; $total=0; $tc=0;
			$minorData =array();
            foreach($result['fd'] as $key=>$res): ?>
			
				<?php
					//Get Minor Data
					$minor = false;
					if(empty($minor_name) && $res['fdtable_fdid'] > 0){
						$fddata = $fds->find()->where(['id' => $res['fdtable_fdid'], 'minor' => 1]);
						$data = $fddata->toArray();
						if($data){
							$res['minorname'] = $data[0]->minorname;
							$minorData[$j] = $res;
							$minor = true;
						}
					}
				?>
				<?php  if(empty($minor_name) && !$minor){?>
                <tr>
                    <td><?=$j++ ?></td>
                    <td>
                        <?php echo $res['institution_name'];?>
                    </td>
                    <td style="width:10%;"><?php echo $res['instrument_type']; ?></td>
                    <td><?php echo $res['application_date']; ?></td>
                    <td><?php echo $res['investment_amount'];?></td>
                    <td><?php echo $res['period'];?></td>
                    <td><?php echo $res['maturity_date'];?></td>
                    <td><?php echo $res['remark'];?></td>
                </tr>
				<?php }elseif(!empty($minor_name)){ ?>
					<?php $mtabledata = $mtables->findByFdtableFdid($res['id'])->first();?>
					<tr>
						<td><?=$j++ ?></td>
						<td>
							<?php echo $mtabledata['institution_name'];?>
						</td>
						<td style="width:10%;"><?php echo $mtabledata['instrument_type']; ?></td>
						<td><?php echo $mtabledata['application_date']; ?></td>
						<td><?php echo $mtabledata['investment_amount'];?></td>
						<td><?php echo $mtabledata['period'];?></td>
						<td><?php echo $mtabledata['maturity_date'];?></td>
						<td><?php echo $mtabledata['remark'];?></td>
					</tr>
				<?php }?>
                <?php endforeach;?>
            </tbody>

        </table>
		
		<?php if(!empty($minorData)){?>
        <h3> Minor Applicant </h3>
		
		<table class="tbl-wrapper" cellpadding="0" cellspacing="0">
            <thead>
            <tr>
                <th scope="col" colspan="9"><b><?php echo 'FD';?></b></th>
            </tr>
            <tr>
                <th scope="col" style="width:3%;"><?= $this->Paginator->sort('Sr No') ?></th>
				<th scope="col"><?= $this->Paginator->sort('Minor Name') ?></th>
                <th scope="col"><?= $this->Paginator->sort('Institution Name') ?></th>
                <th scope="col" style="width:10%;"><?= $this->Paginator->sort('Instrument Type') ?></th>
                <th scope="col"><?= $this->Paginator->sort('Investment Date') ?></th>
                <th scope="col"><?= $this->Paginator->sort('Investment Amount') ?></th>
                <th scope="col" style="width:4%"><?= $this->Paginator->sort('Tenure') ?></th>
                <th scope="col"><?= $this->Paginator->sort('Maturity Date') ?></th>
                <th scope="col" style="width:20%"><?= $this->Paginator->sort('Investor Remark') ?></th>
            </tr>
            </thead>
            <tbody>
            <?php $j=1; $total=0; $tc=0;
            foreach($minorData as $mdata):?>
				
                <tr>
                    <td><?=$j ?></td>
					<td><?php echo $mdata['minorname'].' U/G '.$mdata['customer_name'];?></td>
                    <td><?php echo $mdata['institution_name'];?>
                    </td>
                    <td style="width:10%;"><?php echo $mdata['instrument_type']; ?></td>
                    <td><?php echo $mdata['application_date']; ?></td>
                    <td><?php echo $mdata['investment_amount'];?></td>
                    <td><?php echo $mdata['period'];?></td>
                    <td><?php echo $mdata['maturity_date'];?></td>
                    <td><?php echo $mdata['remark'];?></td>
                </tr>
			
                <?php endforeach;?>
			</tbody>

        </table>
		<?php } ?>

    <?php endif; ?>
</div>

<script>
    var pan_nullnumbercnt = '<?=$pan_nullnumbercnt?>';
    function print_function(){
        window.print();
    }
    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));
        },
        change: function(event, ui) {
			var elmObj = $( "#autocomplete1" );
            if($('#autocomplete1').val().length > 0){				
				$('#minor').val(null).trigger('change');
				pannosoptions(elmObj);
			}		
        },
        select: function( event, ui ) {
			var elmObj = $( "#autocomplete1" );
			
			if($('#autocomplete1').val().length > 0){				
				$('#minor').val(null).trigger('change');
				pannosoptions(elmObj);
			}
			

        }
    });
	$('#minor').select2();
	
	//$('#minor').on("change", function (e) { 
	$('#minor').on('select2:select', function (e) {
		var elmObj = $(this);
		
		if($('#minor').val().length > 0){				
			$('#autocomplete1').val(null).trigger('change');
			pannosoptions(elmObj);
		}
		
		
	});
	
    /* var minorname = <?=json_encode($minorname)?>;
	$( "#minor" ).autocomplete({
        source: function(request, response) {
            var results = $.ui.autocomplete.filter(minorname, request.term);

            response(results.slice(0, 10));
        },
        change: function(event, ui) {
            pannosoptions();

        },
        select: function( event, ui ) {
            pannosoptions();

        }
    }); */
	
    $(function () {
        if(pan_nullnumbercnt==0){
            $('#pan_no option').filter(function(){
                return ($(this).val().trim()=="" && $(this).text().trim()=="");
            }).remove();

        }
        
        $( "#autocomplete1" ).on('paste', function(){
			var elmObj = $(this);
            pannosoptions(elmObj);
        });
        
        $( "#autocomplete1, #minor" ).on('keyup', function(){
            $('#pan_no').val('');
            $('#pan_no').empty();

        });
    });
    
    
    function pannosoptions(elmObj) { console.log(elmObj.attr('id'));
        $('#pan_no').val('');
        $('#pan_no').empty();
		
		var minor = false;
		if(elmObj.attr('id') == 'minor'){
			minor = true;
		}
		
		
        //var elmObj = $('#autocomplete1');
        var cname = elmObj.val();
        var siteUrl = '<?php echo $this->Url->build('/', true) ?>';
        jQuery.ajax({
            type: 'POST',
            url: siteUrl + 'reports/getpannosoptions',
            data: {
                cname: cname,
				minor: minor
            },
            dataType: 'json',
            beforeSend: function(){
                elmObj.after('<img src="'+siteUrl+'img/loading20.gif" class="loading" />');
            },
            complete: function(){
                jQuery('.loading').remove();
            },
            success: function (data) {//alert(JSON.stringify(data));//return false;
                $('#pan_no').val('');
                $('#pan_no').empty();
                data = JSON.parse(JSON.stringify(data));
                $.each(data, function (key, value) {
                    $('#pan_no')
                        .append($("<option></option>")
                            .attr("value", key)
                            .text(value));
                });
            },
            error: function (jqxhr, status, exception) {
                alert('Exception:', jqxhr);
            },
            statusCode: {
                404: function () {
                    alert(message.noPage);
                }
            }
        });
      }


</script>