<?php $this->load->view("partial/header"); ?>

<div class="row">
	<div class="col-md-12">
		<div class="panel panel-piluku">
			<div class="panel-heading">
				<h3 class="panel-title"><?php echo lang('cierre_statistics_title'); ?></h3>
			</div>
			<div class="panel-body">

				<?php echo form_open('cierre/statistics', array('method'=>'get', 'class'=>'form-inline', 'style'=>'margin-bottom:15px;')); ?>
					<div class="form-group" style="margin-right:10px;">
						<label style="margin-right:6px;"><?php echo lang('cierre_statistics_filter_cashier'); ?></label>
						<select name="cashier_id" class="form-control" style="width:240px;">
							<?php $csel = isset($cashier_id) ? (int)$cashier_id : 0; ?>
							<option value="0" <?php echo $csel===0?'selected':''; ?>><?php echo lang('cierre_filter_cashier_all'); ?></option>
							<?php if (!empty($cashiers)) { foreach($cashiers as $ca) { ?>
								<?php $name = trim($ca->first_name.' '.$ca->last_name); ?>
								<option value="<?php echo (int)$ca->person_id; ?>" <?php echo $csel===(int)$ca->person_id?'selected':''; ?>><?php echo H($name); ?></option>
							<?php }} ?>
						</select>
					</div>

					<div class="form-group" style="margin-right:10px;">
						<label style="margin-right:6px;"><?php echo lang('cierre_statistics_filter_range'); ?></label>
						<select name="range" id="stats_range" class="form-control" style="width:240px;">
							<?php $r = isset($range) ? $range : 'last_30'; ?>
							<option value="today" <?php echo $r==='today'?'selected':''; ?>><?php echo lang('cierre_range_today'); ?></option>
							<option value="yesterday" <?php echo $r==='yesterday'?'selected':''; ?>><?php echo lang('cierre_range_yesterday'); ?></option>
							<option value="last_7" <?php echo $r==='last_7'?'selected':''; ?>><?php echo lang('cierre_range_last_7'); ?></option>
							<option value="last_15" <?php echo $r==='last_15'?'selected':''; ?>><?php echo lang('cierre_range_last_15'); ?></option>
							<option value="last_30" <?php echo $r==='last_30'?'selected':''; ?>><?php echo lang('cierre_range_last_30'); ?></option>
							<option value="this_week" <?php echo $r==='this_week'?'selected':''; ?>><?php echo lang('cierre_range_this_week'); ?></option>
							<option value="last_week" <?php echo $r==='last_week'?'selected':''; ?>><?php echo lang('cierre_range_last_week'); ?></option>
							<option value="this_month" <?php echo $r==='this_month'?'selected':''; ?>><?php echo lang('cierre_range_this_month'); ?></option>
							<option value="last_month" <?php echo $r==='last_month'?'selected':''; ?>><?php echo lang('cierre_range_last_month'); ?></option>
							<option value="this_quarter" <?php echo $r==='this_quarter'?'selected':''; ?>><?php echo lang('cierre_range_this_quarter'); ?></option>
							<option value="last_quarter" <?php echo $r==='last_quarter'?'selected':''; ?>><?php echo lang('cierre_range_last_quarter'); ?></option>
							<option value="this_year" <?php echo $r==='this_year'?'selected':''; ?>><?php echo lang('cierre_range_this_year'); ?></option>
							<option value="last_year" <?php echo $r==='last_year'?'selected':''; ?>><?php echo lang('cierre_range_last_year'); ?></option>
							<option value="all" <?php echo $r==='all'?'selected':''; ?>><?php echo lang('cierre_range_all'); ?></option>
							<option value="custom" <?php echo $r==='custom'?'selected':''; ?>><?php echo lang('cierre_range_custom'); ?></option>
						</select>
					</div>

					<span id="stats_custom_dates" style="display:none;">
						<div class="form-group" style="margin-right:10px;">
							<label style="margin-right:6px;"><?php echo lang('cierre_range_from'); ?></label>
							<input type="date" name="from" class="form-control" value="<?php echo isset($from)?H($from):''; ?>">
						</div>
						<div class="form-group" style="margin-right:10px;">
							<label style="margin-right:6px;"><?php echo lang('cierre_range_to'); ?></label>
							<input type="date" name="to" class="form-control" value="<?php echo isset($to)?H($to):''; ?>">
						</div>
					</span>

					<button type="submit" class="btn btn-primary"><span class="ion-search"></span> <?php echo lang('cierre_statistics_apply'); ?></button>
					<?php echo anchor('cierre/statistics_export_csv?cashier_id='.(int)$csel.'&range='.urlencode($r).'&from='.urlencode(isset($from)?$from:'').'&to='.urlencode(isset($to)?$to:''), '<span class="ion-archive"></span> '.lang('cierre_statistics_export_csv'), array('class'=>'btn btn-default', 'style'=>'margin-left:6px;')); ?>
					<?php echo anchor('cierre', lang('common_back'), array('class'=>'btn btn-default', 'style'=>'margin-left:6px;')); ?>
				<?php echo form_close(); ?>

				<?php
					$k = isset($kpis) ? $kpis : array('total_cierres'=>0,'total_diff'=>0,'avg_diff'=>0,'fuera_margen'=>0);
					$total_cierres = (int)$k['total_cierres'];
					$fuera_margen = (int)$k['fuera_margen'];
					$pct_fuera = $total_cierres > 0 ? round(($fuera_margen / $total_cierres) * 100, 1) : 0;
				?>

				<div class="row" style="margin-bottom:15px;">
					<div class="col-sm-3">
						<div class="panel panel-default">
							<div class="panel-body">
								<div style="font-size:12px;color:#777;"><?php echo lang('cierre_stats_kpi_closures'); ?></div>
								<div style="font-size:24px;font-weight:bold;"><?php echo (int)$total_cierres; ?></div>
							</div>
						</div>
					</div>
					<div class="col-sm-3">
						<div class="panel panel-default">
							<div class="panel-body">
								<div style="font-size:12px;color:#777;"><?php echo lang('cierre_stats_kpi_out_of_margin'); ?></div>
								<div style="font-size:24px;font-weight:bold;"><?php echo (int)$fuera_margen; ?> <span style="font-size:14px;color:#777;">(<?php echo $pct_fuera; ?>%)</span></div>
								<div style="font-size:12px;color:#999;"><?php echo lang('cierre_margen_error'); ?>: <?php echo to_currency($margen_error); ?></div>
							</div>
						</div>
					</div>
					<div class="col-sm-3">
						<div class="panel panel-default">
							<div class="panel-body">
								<div style="font-size:12px;color:#777;"><?php echo lang('cierre_stats_kpi_total_diff'); ?></div>
								<div style="font-size:24px;font-weight:bold;"><?php echo to_currency((float)$k['total_diff']); ?></div>
							</div>
						</div>
					</div>
					<div class="col-sm-3">
						<div class="panel panel-default">
							<div class="panel-body">
								<div style="font-size:12px;color:#777;"><?php echo lang('cierre_stats_kpi_avg_diff'); ?></div>
								<div style="font-size:24px;font-weight:bold;"><?php echo to_currency((float)$k['avg_diff']); ?></div>
							</div>
						</div>
					</div>
				</div>

				<div class="row">
					<div class="col-md-6">
						<div class="panel panel-default">
							<div class="panel-heading"><strong><?php echo lang('cierre_stats_summary_by_status'); ?></strong></div>
							<div class="panel-body">
								<canvas id="chart_status" height="180"></canvas>
							</div>
						</div>
					</div>
					<div class="col-md-6">
						<div class="panel panel-default">
							<div class="panel-heading"><strong><?php echo lang('cierre_stats_error_by_payment'); ?></strong></div>
							<div class="panel-body">
								<canvas id="chart_payments" height="180"></canvas>
							</div>
						</div>
					</div>
				</div>

				<div class="row">
					<div class="col-md-7">
						<div class="panel panel-default">
							<div class="panel-heading"><strong><?php echo lang('cierre_stats_summary_by_cashier'); ?></strong></div>
							<div class="panel-body">
								<div class="table-responsive">
									<table class="table table-bordered table-striped">
										<thead>
											<tr>
												<th><?php echo lang('cierre_caja'); ?></th>
												<th style="text-align:right;"><?php echo lang('cierre_stats_kpi_closures'); ?></th>
												<th style="text-align:right;"><?php echo lang('cierre_total_sistema'); ?></th>
												<th style="text-align:right;"><?php echo lang('cierre_total_contado'); ?></th>
												<th style="text-align:right;"><?php echo lang('cierre_diferencia'); ?></th>
												<th style="text-align:right;"><?php echo lang('cierre_stats_kpi_out_of_margin'); ?></th>
											</tr>
										</thead>
										<tbody>
											<?php if (!empty($summary_by_cashier)) { foreach($summary_by_cashier as $row) { ?>
												<?php $pct = $row->cierres > 0 ? round(($row->fuera_margen / $row->cierres) * 100, 1) : 0; ?>
												<tr>
													<td><?php echo H($row->caja_nombre); ?></td>
													<td style="text-align:right;"><?php echo (int)$row->cierres; ?></td>
													<td style="text-align:right;"><?php echo to_currency((float)$row->total_sistema_usd); ?></td>
													<td style="text-align:right;"><?php echo to_currency((float)$row->total_contado_usd); ?></td>
													<td style="text-align:right;"><?php echo to_currency((float)$row->diferencia_total_usd); ?></td>
													<td style="text-align:right;"><?php echo (int)$row->fuera_margen; ?> <span style="color:#777;">(<?php echo $pct; ?>%)</span></td>
												</tr>
											<?php }} else { ?>
												<tr><td colspan="6" class="text-center"><?php echo lang('cierre_stats_no_data'); ?></td></tr>
											<?php } ?>
										</tbody>
									</table>
								</div>
							</div>
						</div>
					</div>

					<div class="col-md-5">
						<div class="panel panel-default">
							<div class="panel-heading"><strong><?php echo lang('cierre_stats_ranking_out_of_margin'); ?></strong></div>
							<div class="panel-body">
								<div class="table-responsive">
									<table class="table table-bordered table-striped">
										<thead>
											<tr>
												<th><?php echo lang('cierre_fecha'); ?></th>
												<th><?php echo lang('cierre_caja'); ?></th>
												<th style="text-align:right;"><?php echo lang('cierre_diferencia'); ?></th>
											</tr>
										</thead>
										<tbody>
											<?php if (!empty($ranking_out_of_margin)) { foreach($ranking_out_of_margin as $rnk) { ?>
												<tr>
													<td><?php echo H($rnk->fecha); ?></td>
													<td><?php echo H($rnk->caja_nombre); ?></td>
													<td style="text-align:right;"><?php echo to_currency((float)$rnk->diferencia_total_usd); ?></td>
												</tr>
											<?php }} else { ?>
												<tr><td colspan="3" class="text-center"><?php echo lang('cierre_stats_no_data'); ?></td></tr>
											<?php } ?>
										</tbody>
									</table>
								</div>
								<p class="help-block" style="margin:0;"><?php echo lang('cierre_margen_error'); ?>: <?php echo to_currency($margen_error); ?></p>
							</div>
						</div>
					</div>
				</div>

				<?php
					// Prepare chart datasets
					$status_map = array(
						'Pendiente' => lang('cierre_filter_pending'),
						'Completado' => lang('cierre_filter_completed'),
						'Revision' => lang('cierre_status_revision'),
						'CompletadoRevisado' => lang('cierre_filter_reviewed_completed'),
					);

					$status_labels = array();
					$status_values = array();
					if (!empty($summary_by_status))
					{
						foreach($summary_by_status as $s)
						{
							$raw = isset($s->estado) ? trim($s->estado) : '';
							$label = $raw !== '' && isset($status_map[$raw]) ? $status_map[$raw] : ($raw !== '' ? $raw : lang('cierre_status_unknown'));
							$status_labels[] = $label;
							$status_values[] = (int)$s->qty;
						}
					}

					$pay_labels = array();
					$pay_values = array();
					if (!empty($error_by_payment))
					{
						foreach($error_by_payment as $p)
						{
							$pay_labels[] = $p->tipo_pago;
							$pay_values[] = round((float)$p->percent, 2);
						}
					}
				?>

				<script type="text/javascript">
					(function() {
						function toggleCustomDates() {
							var r = document.getElementById('stats_range').value;
							document.getElementById('stats_custom_dates').style.display = (r === 'custom') ? 'inline-block' : 'none';
						}
						document.getElementById('stats_range').addEventListener('change', toggleCustomDates);
						toggleCustomDates();

						if (typeof Chart === 'undefined') {
							return;
						}

						var statusCtx = document.getElementById('chart_status').getContext('2d');
						var statusChart = new Chart(statusCtx, {
							type: 'doughnut',
							data: {
								labels: <?php echo json_encode($status_labels); ?>,
								datasets: [{
									data: <?php echo json_encode($status_values); ?>
								}]
							},
							options: {
								legend: { position: 'bottom' },
								responsive: true,
								maintainAspectRatio: false
							}
						});

						var payCtx = document.getElementById('chart_payments').getContext('2d');
						var payChart = new Chart(payCtx, {
							type: 'bar',
							data: {
								labels: <?php echo json_encode($pay_labels); ?>,
								datasets: [{
									label: '%',
									data: <?php echo json_encode($pay_values); ?>
								}]
							},
							options: {
								legend: { display: false },
								scales: {
									yAxes: [{ ticks: { beginAtZero: true, callback: function(v){ return v + '%'; } } }]
								},
								responsive: true,
								maintainAspectRatio: false
							}
						});
					})();
				</script>

			</div>
		</div>
	</div>
</div>

<?php $this->load->view("partial/footer"); ?>
