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

<script type="text/javascript">
$(function(){
	var customIdx = 0;
	function recalc(){
		var totalSistema = 0;
		var totalContado = 0;
		var tasa = parseFloat($('#cambio_tasa').val()) || 1;
		$('.row-detalle').each(function(){
			var sistema = parseFloat($(this).data('sistema')) || 0;
			var moneda = $(this).data('moneda') || 'USD';
			var monedaSel = $(this).find('.moneda');
			if (monedaSel.length) { moneda = monedaSel.val(); }
			var contado = parseFloat($(this).find('.contado').val()) || 0;
			var contadoUsd = (moneda === 'BS') ? (tasa > 0 ? contado / tasa : 0) : contado;
			$(this).find('.contado_usd').text(contadoUsd.toFixed(2));
			totalSistema += sistema;
			totalContado += contadoUsd;
		});
			if ($('#total_sistema').length)
			{
				$('#total_sistema').text(totalSistema.toFixed(2));
			}
		$('#total_contado').text(totalContado.toFixed(2));
		// difference is evaluated in Step 3 (permission-based)
	}

	$(document).on('keyup change', '.contado, .moneda', recalc);

	// ------------------------------
	// Desglose modal
	// ------------------------------
	var currentDetalleId = 0;
	function renderBreakdown(lines, moneda)
	{
		var tbody = $('#breakdown_lines');
		tbody.empty();
		var total = 0;
		for (var i=0; i<lines.length; i++)
		{
			var l = lines[i];
			var amt = parseFloat(l.amount) || 0;
			total += amt;
			var checked = (parseInt(l.verified) ? 'checked' : '');
			tbody.append(
				'<tr>'+
					'<td style="width:140px;" class="text-right">'+amt.toFixed(2)+' '+moneda+'</td>'+
					'<td class="text-center" style="width:140px;"><input type="checkbox" class="breakdown-verified" data-id="'+l.id+'" '+checked+' /></td>'+
					'<td style="width:80px;" class="text-center"><a href="#" class="text-danger breakdown-delete" data-id="'+l.id+'"><span class="ion-close"></span></a></td>'+
				'</tr>'
			);
		}
		$('#breakdown_total').text(total.toFixed(2)+' '+moneda);
		// Sync into main input (readonly)
		var input = $('tr.row-detalle[data-detalle-id="'+currentDetalleId+'"] .contado');
		input.val(total.toFixed(2));
		input.trigger('change');
	}

	function loadBreakdown(detalleId)
	{
		return $.getJSON(<?php echo json_encode(site_url('cierre/ajax_get_breakdown')); ?>+'/'+detalleId, function(resp){
			renderBreakdown(resp.lines || [], resp.moneda || 'USD');
		});
	}

	$(document).on('click', '.btn-breakdown', function(e){
		e.preventDefault();
		currentDetalleId = parseInt($(this).data('detalle-id')) || 0;
		var tipo = $(this).data('tipo') || '';
		$('#breakdown_title').text(<?php echo json_encode(lang('cierre_breakdown')); ?>+' - '+tipo);
		$('#breakdown_amount').val('');
		$('#breakdown_modal').modal('show');
		loadBreakdown(currentDetalleId);
	});

	$('#breakdown_amount').on('keypress', function(e){
		if (e.which === 13)
		{
			e.preventDefault();
			var amt = parseFloat($('#breakdown_amount').val()) || 0;
			if (amt <= 0 || currentDetalleId <= 0) return;
			$.post(<?php echo json_encode(site_url('cierre/ajax_add_breakdown')); ?>, {cierre_detalle_id: currentDetalleId, amount: amt}, function(resp){
				if (resp && resp.lines)
				{
					renderBreakdown(resp.lines, $('tr.row-detalle[data-detalle-id="'+currentDetalleId+'"]').data('moneda') || 'USD');
					$('#breakdown_amount').val('').focus();
				}
			}, 'json');
		}
	});

	$(document).on('click', '.breakdown-delete', function(e){
		e.preventDefault();
		var id = parseInt($(this).data('id')) || 0;
		if (!id || !currentDetalleId) return;
		$.post(<?php echo json_encode(site_url('cierre/ajax_delete_breakdown')); ?>, {breakdown_id: id, cierre_detalle_id: currentDetalleId}, function(resp){
			if (resp && resp.lines)
			{
				renderBreakdown(resp.lines, $('tr.row-detalle[data-detalle-id="'+currentDetalleId+'"]').data('moneda') || 'USD');
			}
		}, 'json');
	});

	$(document).on('change', '.breakdown-verified', function(){
		var id = parseInt($(this).data('id')) || 0;
		if (!id) return;
		var v = $(this).is(':checked') ? 1 : 0;
		$.post(<?php echo json_encode(site_url('cierre/ajax_set_breakdown_verified')); ?>, {breakdown_id: id, verified: v});
	});

	$('#add_custom').on('click', function(e){
		e.preventDefault();
		customIdx++;
		var row = ''+
		'<tr class="row-detalle row-custom" data-sistema="0" data-moneda="USD">'+
			'<td style="width:260px;"><input type="text" class="form-control" name="custom['+customIdx+'][tipo_pago]" placeholder="'+<?php echo json_encode(lang('cierre_other_payment_placeholder')); ?>+'"></td>'+
			<?php if (empty($is_cashier_mode)) { ?>
			'<td class="text-center">0.00</td>'+
			<?php } ?>
			'<td style="width:90px;">'+
				'<select class="form-control moneda" name="custom['+customIdx+'][moneda]">'+
					'<option value="USD">USD</option>'+
					'<option value="BS">BS</option>'+
				'</select>'+
			'</td>'+
			'<td style="width:160px;"><input class="form-control contado text-center" type="number" step="0.01" min="0" name="custom['+customIdx+'][monto_contado]" value=""></td>'+
			'<td class="text-center contado_usd">0.00</td>'+
		'</tr>';
		$('#detalle_body').append(row);
		recalc();
	});
	recalc();
});
</script>

<div class="row">
	<div class="col-md-12">
		<?php $active_step = 2; $this->load->view('cierre/_wizard_steps', array('active_step'=>$active_step)); ?>
		<div class="panel panel-piluku">
			<div class="panel-heading">
				<h3 class="panel-title" style="display:inline-block;">
					<?php echo lang('cierre_step2_title'); ?>
				</h3>
				<?php if (!empty($can_payment_verification) && empty($is_cashier_mode)) { ?>
					<div class="pull-right">
						<?php echo anchor('cierre/payment_verification', '<span class="ion-checkmark"></span> '.lang('cierre_payment_verification'), array('class'=>'btn btn-default btn-sm')); ?>
					</div>
				<?php } ?>
				<div class="clearfix"></div>
			</div>
			<div class="panel-body">

				<div class="row" style="margin-bottom:15px;">
					<div class="col-md-12">
						<strong><?php echo lang('cierre_fecha'); ?>:</strong> <?php echo H($cierre->fecha); ?> &nbsp;
						<strong><?php echo lang('cierre_caja'); ?>:</strong> <?php echo H($cierre->caja_nombre); ?> &nbsp;
						<strong><?php echo lang('cierre_bolsa'); ?>:</strong> <?php echo H($cierre->bolsa_manual); ?> &nbsp;
						<strong><?php echo lang('cierre_tasa'); ?>:</strong> <?php echo H($cierre->cambio_tasa); ?>
					</div>
				</div>

				<?php if (empty($detalle)) { ?>
					<div class="alert alert-warning"><?php echo lang('cierre_no_payment_types'); ?> <?php echo anchor('cierre/config', lang('cierre_config')); ?></div>
				<?php } ?>

				<?php echo form_open('cierre/create_step2/'.$cierre->id); ?>
				<input type="hidden" id="cambio_tasa" value="<?php echo H($cierre->cambio_tasa); ?>">

				<div class="clearfix" style="margin-bottom:10px;">
					<a href="#" id="add_custom" class="btn btn-default btn-sm"><span class="ion-plus"></span> <?php echo lang('cierre_other_payment'); ?></a>
				</div>

				<div class="table-responsive">
					<table class="table table-bordered">
						<thead>
							<tr>
								<th><?php echo lang('cierre_tipo_pago'); ?></th>
								<?php if (empty($is_cashier_mode)) { ?>
									<th class="text-center"><?php echo lang('cierre_sistema_usd'); ?></th>
								<?php } ?>
								<th><?php echo lang('cierre_moneda'); ?></th>
								<th class="text-center"><?php echo lang('cierre_contado'); ?></th>
								<th class="text-center"><?php echo lang('cierre_contado_usd'); ?></th>
							<!-- Difference is shown in Step 3 for users with permission -->
							</tr>
						</thead>
						<tbody id="detalle_body">
							<?php foreach($detalle as $d) { ?>
								<tr class="row-detalle" data-sistema="<?php echo (float)$d->monto_sistema_usd; ?>" data-moneda="<?php echo H($d->moneda); ?>" data-detalle-id="<?php echo (int)$d->id; ?>" data-breakdown="<?php echo !empty($d->enable_breakdown) ? 1 : 0; ?>">
									<td>
										<?php echo H($d->tipo_pago); ?>
										<?php if (!empty($d->enable_breakdown) && empty($d->es_adicional)) { ?>
											<a href="#" class="btn btn-default btn-xs pull-right btn-breakdown" data-detalle-id="<?php echo (int)$d->id; ?>" data-tipo="<?php echo H($d->tipo_pago); ?>">
												<span class="ion-navicon"></span> <?php echo lang('cierre_desglose'); ?>
											</a>
										<?php } ?>
									</td>
								<?php if (empty($is_cashier_mode)) { ?>
									<td class="text-center"><?php echo number_format((float)$d->monto_sistema_usd, 2); ?></td>
								<?php } ?>
									<td style="width:90px;">
										<?php // Currency locked for existing rows ?>
										<span class="label label-default" style="display:inline-block;min-width:55px;">
											<?php echo H($d->moneda); ?>
										</span>
										<input type="hidden" name="detalle[<?php echo (int)$d->id; ?>][moneda]" value="<?php echo H($d->moneda); ?>">
									</td>
									<td style="width:160px;">
										<input class="form-control contado text-center" type="number" step="0.01" min="0" name="detalle[<?php echo (int)$d->id; ?>][monto_contado]" value="<?php echo H($d->monto_contado); ?>" <?php echo (!empty($d->enable_breakdown) && empty($d->es_adicional)) ? 'readonly' : ''; ?> />
									</td>
								<td class="text-center contado_usd"><?php echo number_format((float)$d->monto_contado_usd, 2); ?></td>
								</tr>
							<?php } ?>
						</tbody>
						<tfoot>
							<tr>
								<th class="text-right"><?php echo lang('cierre_totales'); ?></th>
								<?php if (empty($is_cashier_mode)) { ?>
									<th class="text-center" id="total_sistema"></th>
								<?php } ?>
								<th></th>
								<th></th>
								<th class="text-center" id="total_contado"></th>
							</tr>
						</tfoot>
					</table>
				</div>

				<div class="form-group">
					<label><?php echo lang('cierre_notas'); ?></label>
					<textarea name="notas" class="form-control" rows="3"><?php echo H($cierre->notas); ?></textarea>
				</div>

				<div class="form-group">
					<?php echo anchor('cierre/create_step1', lang('cierre_back_step'), array('class'=>'btn btn-default')); ?>
					<button type="submit" class="btn btn-primary"><?php echo lang('cierre_next'); ?></button>
				</div>

				<?php echo form_close(); ?>
			</div>
		</div>
	</div>
</div>

<!-- Breakdown Modal -->
<div class="modal fade" id="breakdown_modal" tabindex="-1" role="dialog" aria-hidden="true">
	<div class="modal-dialog modal-sm" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
				<h4 class="modal-title" id="breakdown_title"><?php echo lang('cierre_breakdown'); ?></h4>
			</div>
			<div class="modal-body">
				<div class="form-group">
					<label><?php echo lang('cierre_breakdown_add_amount'); ?></label>
					<input type="number" step="0.01" min="0" class="form-control" id="breakdown_amount" placeholder="0.00" />
					<p class="help-block">Enter para guardar y sumar.</p>
				</div>
				<div class="table-responsive">
					<table class="table table-bordered">
						<thead>
							<tr>
								<th class="text-right"><?php echo lang('cierre_contado'); ?></th>
								<th class="text-center"><?php echo lang('cierre_verified'); ?></th>
								<th></th>
							</tr>
						</thead>
						<tbody id="breakdown_lines"></tbody>
						<tfoot>
							<tr>
								<th colspan="3" class="text-right">
									<?php echo lang('cierre_breakdown_total'); ?>: <span id="breakdown_total"></span>
								</th>
							</tr>
						</tfoot>
					</table>
				</div>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default" data-dismiss="modal"><?php echo lang('common_close'); ?></button>
			</div>
		</div>
	</div>
</div>

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