<?= $this->extend('admin/template/template') ?>


<?= $this->section('css') ?>
<link rel="stylesheet" type="text/css" href="<?=base_url('public/assets/css')?>/jquery.datetimepicker.min.css" >
<?= $this->endSection() ?>


<?= $this->section('content') ?>
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-md-2">
	<h3 class="mt-5">Balanço</h3>
    <?php
        $dataAtual['navegacao'] = new DateTime('now');
    ?>
	<ul>
		<li><?=anchor('faturamento?case='.$dataAtual['navegacao']->format('mY'),'Lançamentos do Mês'); ?></li>
		<li><?=anchor('faturamento?case='.$dataAtual['navegacao']->format('Y'),'Lançamento Anual'); ?></li>
	</ul>
	<hr>
	<h5>Categorias de Lançamento</h5>
	<ul class="small">
		<?php
		foreach($listagemCategoria as $c):
			echo '<li>';
			echo $c['fatcat_nome'];
			echo '</li>';
		endforeach;
		?>
		<li style="list-style:none;"><small><?=anchor('faturamentoCategoria/cadastra','Nova Categoria');?></small></li>
	</ul>
	<hr>
	<h5>Formas de Pagamento</h5>
	<ul class="small">
		<?php
		foreach($listagemFormaPgto as $l):
			echo '<li>';
			echo $l['fatfor_nome'];
			echo '</li>';
		endforeach;
		?>
		<li style="list-style:none;"><small><?=anchor('faturaFormapgto/cadastra','Nova Forma de Pagamento');?></small></li>
	</ul>
</div>
<div class="col-md-8 shadow rounded-bottom p-5">
	<!-- > Breadcrumb -->
	<nav style="--bs-breadcrumb-divider: url(&#34;data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='8' height='8'%3E%3Cpath d='M2.5 0L1 1.5 3.5 4 1 6.5 2.5 8l4-4-4-4z' fill='%236c757d'/%3E%3C/svg%3E&#34;);" aria-label="breadcrumb">
		<ol class="breadcrumb">
			<li class="breadcrumb-item"><?=anchor('/','Painel')?></li>
			<li class="breadcrumb-item active" aria-current="page">Faturamento</li>
		</ol>
	</nav>
	<!-- # end breadcrumb -->
	<!-- > Conteudo -->
    <?php
    //definindo datas
    $titulopagina = 'Lançamentos de '.$dataAtual['mesextenso'].' de '.$dataAtual['ano'];
    $mesanterior = new datetime($dataAtual['diahora']->format('Y-m-d'));
    $mesanterior->modify('-1month');
    $mesanterior = $mesanterior->format('mY'); //forma que a programacao gera o periodo
    $mesproximo = new datetime($dataAtual['diahora']->format('Y-m-d'));
    $mesproximo->modify('+1month');
    $mesproximo = $mesproximo->format('mY'); //forma que a programacao gera o periodo
    ?>
	<h3><?php echo $titulopagina; ?></h3>
    <?=anchor('faturamento?case='.$mesanterior,'&laquo; mês Anterior'); ?> . <?=anchor('faturamento?case='.$mesproximo,'Próximo mês &raquo;'); ?>
	<hr />
	<div class="table-responsive">
	<?php
		$validation = \Config\Services::validation();
		echo form_open('faturamento/cadastra');
	?>
	<table class="table table-striped table-bordered table-hover">
		<thead>
		<tr>
			<th width="15%">Data</th>
			<th>Novo Lançamento <small style="font-weight:normal;">[ se Cliente]</small></th>
			<th width="15%" nowrap="nowrap">Forma Pgto</th>
			<th width="15%" nowrap="nowrap">Categoria</th>
			<th width="15%">Valor</th>
			<th width="5%">Lançar</th>
		</tr>
		</thead>
		<tbody>
		<tr>
			<td><?php echo form_input('fat_data', set_value('fat_data'),'class="form-control" id="datetimepicker1"');
			// <!-- valor Error -->
			if($validation->getError('fat_data')) { ?>
				<div class='alert alert-danger mt-2'>
				<?= $validation->getError('fat_data'); ?>
				</div><?php 
			}
			?></td>
			<td><?php
			echo form_input('fat_descricao', set_value('fat_descricao'),'id="fat_descricao" class="form-control"');
			// <!-- valor Error -->
			if($validation->getError('fat_descricao')) { ?>
				<div class='alert alert-danger mt-2'>
				<?= $validation->getError('fat_descricao'); ?>
				</div><?php 
			}
			?></td>
			<td><?php
			echo form_dropdown('fatfor_nome', $faturaformaspgto, set_value('fatfor_nome'), 'class="form-select"');
			?></td>
			<td><?php
			echo form_dropdown('fatcat_nome', $faturacategoria, set_value('fatcat_nome'), 'class="form-select"');
			?></td>
			<td><?php
			echo form_input('fat_valor', set_value('fat_valor'),'id="fat_valor" class="form-control"');
			// <!-- valor Error -->
			if($validation->getError('fat_valor')) { ?>
				<div class='alert alert-danger mt-2'>
				<?= $validation->getError('fat_valor'); ?>
				</div><?php 
			}
			?></td>
			<td style="text-align:center;"><?php
			echo form_submit('ok','OK','class="btn btn-success"');
			echo form_close();
			?></td>
		</tr>
		</tbody>
	</table>
	<?=form_close(); ?>
	<hr />
	<table class="table">
		<thead class="table-light">
		<tr>
			<th width="15%">Data</th>
			<th>Lançamento</th>
			<th width="15%" nowrap="nowrap">Forma Pgto</th>
			<th width="15%">Categoria</th>
			<th width="15%" colspan="2">Valor</th>
			<th>Ação</th>
		</tr>
		</thead>
		<tbody>
			<?php
			$dadosChart = [];
			foreach($listagem as $l):
				echo '<tr>';
				echo '<td>'.$l['fat_data'].'</td>';
                echo '<td><small><a href="';
				echo base_url('faturamento/edita/' . $l['id_faturamento'] ) . '"><span class="glyphicon glyphicon-pencil"></span></a></small> '.$l['fat_descricao'].'  <small><a href="' . base_url('faturamento/exclui/'.$l['id_faturamento'].'/' . $dataAtual['mes'] . $dataAtual['ano']) .'" class="btn-confirma-excluir"><span class="glyphicon glyphicon-trash"></span></a></small></td>';
				echo '<td nowrap="nowrap">'.$l['fatfor_nome'].'</td>';
				echo '<td>'.$l['fatcat_nome'].'</td>';
				echo '<td colspan="2">'.$l['fat_valor'].'</td>';
				echo '<td nowrap>';
				echo anchor('faturamento/edita/'.$l['id_faturamento'],'<span class="material-symbols-outlined">edit_note</span>');
				echo ' | ';
				echo anchor('faturamento/exclui/'.$l['id_faturamento'],'<span class="material-symbols-outlined">delete</span>','class="btn-confirma-excluir"');
				echo '</td>';
				echo '</tr>';
				// Gráfico
				$l['fat_valor'] = str_replace('.','',$l['fat_valor']);
				$l['fat_valor'] = str_replace(',','.',$l['fat_valor']);
				$rows = array_column( $dadosChart,'categoria');
				$found_key = array_search($l['fatcat_nome'], $rows);
				if($found_key !== false):
					$dadosChart[$found_key]['soma'] = $dadosChart[$found_key]['soma'] + $l['fat_valor'];
				else:
					$dadosChart[] = [
						'categoria'			=> $l['fatcat_nome'],
						'soma'				=> $l['fat_valor'],
					];
				endif;
			endforeach;
			?>

		</tbody>
		<tfoot>

            <?php
                //somando total
                $saida = 0;
                $entrada = 0;
                foreach($listagem as $v):
                    if($v['fat_valor']<=0):
                        $numero = str_replace('.','',$v['fat_valor']);
                        $numero = str_replace(',','.',$numero);
                        $saida = $saida+$numero;
                    endif;
                    if($v['fat_valor']>0):
                        $numero = str_replace('.','',$v['fat_valor']);
                        $numero = str_replace(',','.',$numero);
                        $entrada = $entrada+$numero;
                    endif;
                endforeach;
                $total = $entrada + $saida;
            ?>
			<tr class="table-dark">
				<td colspan="4" style="text-align:right;"><small>SubTotal:</small> </td>
				<td><?php echo 'R$ '.number_format($entrada,2,",","."); ?></td>
				<td><?php echo 'R$ '.number_format($saida,2,",","."); ?></td>
				<td></td>
			</tr>
			<tr>
				<td colspan="4" style="text-align:right;">Total: </td>
				<td colspan="2"><?php echo 'R$ '.number_format($total,2,",","."); ?></td>
				<td></td>
			</tr>
		</tfoot>
	</table>
	</div>
	<?php
	// grafico ajustes
	$chart['categorias'] = 'Soma mensal';
	foreach($dadosChart as $d):
		$chart[$d['categoria']] = $d['soma'];
	endforeach;
	$chart = '[['.json_encode($chart).']]';
	$chart = str_replace("{",'',$chart);
	$chart = str_replace("}",'',$chart);
	$chart = str_replace(",",'];[',$chart);
	$chart = str_replace(":",',',$chart);
	$chart = str_replace("];[",'],[',$chart);
	// grafico apresenta
	?>
	<div id="donutchart" style="width: 100%; height: 500px;"></div>
</div><!-- end 12 -->
</div><!-- end row -->
</div>
<?= $this->endSection() ?>



<?= $this->section('js') ?>
<script>
// confirma excluir item clicado
$('.btn-confirma-excluir').on('click',function(e){
	let text = "Confirme para continuar\nou cancele.";
	if (confirm(text) == true) {
		text = "You pressed OK!";
	} else {
        e.stopImmediatePropagation();
        e.preventDefault();
	}
});
</script>

<script src="<?=base_url('public/assets/js')?>/jquery.datetimepicker.full.min.js"></script>

<script>
jQuery('#datetimepicker1').datetimepicker({
	format:'d/m/Y',
	lang:'pt-BR',
	mask:true,
});
</script>

<!-- Gráfico -->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
	google.charts.load("current", {packages:["corechart"]});
	google.charts.setOnLoadCallback(drawChart);
	function drawChart() {

	var passedArray = <?php echo $chart ?>;
	var data = google.visualization.arrayToDataTable( passedArray );

	var options = {
		title: 'Gastos no mês',
		pieHole: 0.4,
	};

	var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
	chart.draw(data, options);
	}
</script>
<?= $this->endSection() ?>