<div class="container-fluid" id="container-wrapper">
	<div class="d-sm-flex align-items-center justify-content-between mb-4">
		<h1 class="h3 mb-0 text-gray-800">Kas Tunai &amp; Bank</h1>
	</div>

	<?php
	$role  = strtolower(trim((string)($this->session->userdata('role')  ?? '')));
	$level = strtolower(trim((string)($this->session->userdata('level') ?? '')));
	$akses = strtolower(trim((string)($this->session->userdata('akses') ?? '')));

	$canTambahModal = in_array($role,  ['admin','owner'], true)
	               || in_array($level, ['admin','owner'], true)
	               || in_array($akses, ['admin','owner'], true);
	?>

	<?php if ($canTambahModal): ?>
	  <div class="d-sm-flex align-items-center justify-content-between mb-4">
	    <a href="#" class="btn btn-sm btn-primary shadow-sm mr-3 tambah_kas">
	      <i class="fa fa-plus mr-1"></i> Tambah Modal
	    </a>
	  </div>
	<?php endif; ?>

	<?php
	// Wrapper tampilan Rupiah: pakai rp() bawaan project,
	// tapi pastikan ada prefix "Rp " (tanpa dobel).
	$_rp = function($angka){
	  $out = trim((string) rp($angka));
	  if ($out === '') $out = '0';

	  // cek text tanpa tag HTML
	  $plain = trim(strip_tags($out));
	  if (preg_match('/^rp\b/i', $plain)) return $out; // sudah ada Rp

	  return 'Rp ' . $out;
	};
	?>



	<div class="row mb-3">
		<?php
		// Ambil role/level/akses dari session (jaga-jaga kalau salah satu yang dipakai di projectmu)
		$role  = strtolower(trim((string)($this->session->userdata('role')  ?? '')));
		$level = strtolower(trim((string)($this->session->userdata('level') ?? '')));
		$akses = strtolower(trim((string)($this->session->userdata('akses') ?? '')));

		// Hanya Admin & Owner yang boleh lihat
		$canSeeKasTunai = in_array($level, ['admin','owner'], true)
		  || in_array($role,  ['admin','owner'], true)
		  || in_array($akses, ['admin','owner'], true);
		?>

		<?php if ($canSeeKasTunai): ?>
		  <!-- Kas Tunai di Simpan (KHUSUS ADMIN & OWNER) -->
		  <div class="col-xl-4 col-md-6 mb-4" id="load-kas">
		    <div class="card h-100">
		      <div class="card-body">
		        <div class="row align-items-center">
		          <div class="col mr-2">
		            <div class="text-xs font-weight-bold text-uppercase mb-1">
		              <?= isset($kas_kecil['nama']) ? html_escape($kas_kecil['nama']) : 'Kas Tunai'; ?>
		            </div>

		            <div class="h5 mb-0 font-weight-bold text-gray-800 load-kecil">
					  <?= isset($kas_kecil['nilai']) ? $_rp($kas_kecil['nilai']) : $_rp(0); ?>
					</div>


		            <!-- Info keterangan (hanya tampil untuk Admin & Owner karena card-nya memang disembunyikan untuk user lain) -->
		            <div class="mt-2 small text-muted">
		              <i class="fa fa-info-circle mr-2"></i>
					  <b>Info:</b> kas tunai ini hanya ditampilkan untuk <b>Admin</b> dan <b>Owner</b>.
		            </div>
		          </div>

		          <div class="col-auto">
		            <a href="#" onclick="return false;" title="Kas Tunai di Simpan (Admin/Owner)">
		              <i class="fa fa-fw fa-money fa-2x"></i>
		            </a>
		          </div>
		        </div>
		      </div>
		    </div>
		  </div>
		<?php endif; ?>



		<!-- Kas DP -->
		<!--
        <div class="col-xl-4 col-md-6 mb-4">
            <div class="card h-100">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-uppercase mb-1"><?=$dp['nama'];?></div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?=rp($dp['nilai']);?></div>
						</div>
                        <div class="col-auto" >
							<a href="#"><i class="fa fa-fw fa-money fa-2x mdlFire"></i></a>
						</div>
					</div>
				</div>
			</div>
		</div>
		-->

		<!-- Kas Tunai (Laci) -->
		<div class="col-xl-4 col-md-6 mb-4">
			<div class="card h-100">
				<div class="card-body">
					<div class="row align-items-center">
						<div class="col mr-2">
							<div class="text-xs font-weight-bold text-uppercase mb-1"><?=$kas['nama'];?></div>
							<div class="h5 mb-0 font-weight-bold text-gray-800"><?= $_rp($kas['nilai']); ?></div>
						</div>
						<div class="col-auto">
							<a href="#" class="" title="">
								<i class="fa fa-money fa-2x text-primary"></i>
							</a>
						</div>
					</div>
				</div>
			</div>
		</div>

		<?php foreach($rekening as $key=>$val){ ?>
			<!-- Rekening Bank -->
			<div class="col-xl-4 col-md-6 mb-4">
				<div class="card h-100">
					<div class="card-body">
						<div class="row no-gutters align-items-center">
							<div class="col mr-2">
								<div class="text-xs font-weight-bold text-uppercase mb-1"><?=$val['nama'];?></div>
								<div class="h5 mb-0 font-weight-bold text-gray-800"><?= $_rp($val['nilai']); ?></div>
							</div>
							<div class="col-auto">
								<a href="#" class="" title="">
									<i class="fa fa-credit-card fa-2x text-primary"></i>
								</a>
							</div>
						</div>
					</div>
				</div>
			</div>
		<?php } ?>
	</div>
</div>

<!-- =========================
	MODAL: TAMBAH MODAL
========================= -->
<div class="modal fade" id="ModalKas" tabindex="-1" role="dialog" aria-labelledby="ModalKasLabel" aria-hidden="true">
	<div class="modal-dialog modal-dialog-centered" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title" id="ModalKasLabel">Tambah Modal</h5>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>
			<div class="modal-body">
				<div class="form-group">
					<label>Simpan ke Kas</label>
					<select id="sumber_kas" class="form-control sumber_kas"></select>
					<small class="text-muted">Pilih kas tunai atau kas bank.</small>
				</div>

				<div class="form-group" id="wrap_rekening" style="display:none;">
					<label>Rekening Bank</label>
					<select id="rekening_modal" class="form-control"></select>
					<small class="text-muted">Muncul jika memilih Kas Bank.</small>
				</div>

				<div class="form-group">
				  <label class="mb-1">Jumlah Modal</label>

				  <div class="input-group">
				    <div class="input-group-prepend">
				      <span class="input-group-text font-weight-bold">Rp</span>
				    </div>

				    <input
				      type="text"
				      class="form-control uang text-right"
				      id="jumlah_modal"
				      placeholder="0"
				      inputmode="numeric"
				      autocomplete="off"
				    >
				  </div>

				  <small class="text-muted d-block mt-1">
				    Masukkan nominal tanpa koma. Contoh: <b>1.000.000</b>
				  </small>
				</div>


				<div class="form-group mb-0">
					<label>Keterangan</label>
					<textarea id="keterangan" class="form-control" rows="3" placeholder="Contoh: Setor modal awal / tambah saldo kas"></textarea>
				</div>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-light" data-dismiss="modal">Batal</button>
				<button type="button" class="btn btn-primary simpan_modal"><i class="fa fa-save mr-1"></i> Simpan</button>
			</div>
		</div>
	</div>
</div>

<script>

	function withRp(html){
	  html = (html || '').toString().trim();
	  if(!html) return 'Rp 0';

	  // cek teks tanpa tag HTML
	  var plain = html.replace(/<[^>]*>/g, '').trim();
	  if(/^rp\b/i.test(plain)) return html; // server sudah kirim Rp

	  return 'Rp ' + html;
	}

	$(document).ready(function() {
	  // Kas Tunai di Simpan
	  if ($('#load-kas').length) {
	    $('#load-kas').loading({theme: 'dark'});
	    kecil();
	  }

	  // yang lain biarkan aman (jalan hanya kalau elemennya ada)
	  if ($('#load-kasp').length) {
	    $('#load-kasp').loading({theme: 'dark'});
	    penjualan();
	  }
	  if ($('#load-kasb').length) {
	    $('#load-kasb').loading({theme: 'dark'});
	    bank();
	  }
	});

	var date2 = new Date();
	$('.date-kas').datepicker({
		language: 'id',
        format: 'MM yyyy',
		"endDate": date2,
        autoclose: true,
        startView: "months",
		minViewMode: "months",
	});
	function kecil(){
		$.ajaxQueue({
			url:  base_url+"kas/total_kas_kecil",
			cache: false,
			success: function (data) {
				$('#load-kas').loading('stop')
				$('.load-kecil').html(withRp(data));

			},
			error: function (xhr, ajaxOptions, thrownError) {
				console.log(thrownError);
				$('#load-kas').loading('stop');
			}
		});
	}

	function penjualan(){
		$.ajaxQueue({
			url:  base_url+"kas/total_kas_penjualan",
			cache: false,
			success: function (data) {
				$('#load-kasp').loading('stop');
				$('.load-penjualan').html(withRp(data));

			},
			error: function (xhr, ajaxOptions, thrownError) {
				console.log(thrownError);
				$('#load-kasp').loading('stop');
			}
		});
	}

	function bank(){
		$.ajaxQueue({
			url:  base_url+"kas/total_kas_bank",
			cache: false,
			success: function (data) {
				$('#load-kasb').loading('stop');
				$('.load-bank').html(withRp(data));

			},
			error: function (xhr, ajaxOptions, thrownError) {
				console.log(thrownError);
				$('#load-kasb').loading('stop');
			}
		});
	}

	$(document).on("click", "#detail_bank", function(event) {
		event.preventDefault();
		$("#DetailBank").modal({
			backdrop : "static",
			keyboard : false
		});
		$.ajax({
			method : "POST",
			url : base_url + "kas/detail_bayar",
			dataType:'html',
			success : function(data) {
				$("#detail-data").html(data)
			},
			error : function(res, status, httpMessage) {
				sweet("Peringatan!!!", httpMessage, "warning", "warning");
			}
		});
	});

	$(document).on("click", ".cetak_kas", function(event) {
		event.preventDefault();
		$("#CetakKas").modal({
			backdrop : "static",
			keyboard : false
		});
		$.ajax({
			method : "POST",
			url : base_url + "kas/detail_bayar",
			dataType:'html',
			success : function(data) {
				$("#detail-data").html(data)
			},
			error : function(res, status, httpMessage) {
				sweet("Peringatan!!!", httpMessage, "warning", "warning");
			}
		});
	});

	// =========================
	// TOMBOL + MODAL TAMBAH MODAL
	// =========================
	$(document).on("click", ".tambah_kas", function(event) {
		event.preventDefault();

		// reset form
		$("#sumber_kas").empty();
		$("#wrap_rekening").hide();
		$("#rekening_modal").empty();
		$("#jumlah_modal").val('');
		$("#keterangan").val('');

		$("#ModalKas").modal({
			backdrop : "static",
			keyboard : false
		});

		// load sumber kas (tunai/bank)
		$.ajax({
			url: base_url + "kas/load_jenis_kas",
			type: 'post',
			dataType: 'json',
			beforeSend : function() {
				$("#sumber_kas").empty();
			},
			success: function (response) {
				var len = (response || []).length;
				$(".sumber_kas").attr("disabled", false);
				$("#sumber_kas").append("<option value='0'>Pilih</option>");
				for (var i = 0; i < len; i++) {
					var id = response[i]['id'];
					var name = response[i]['name'];
					$("#sumber_kas").append("<option value='" + id + "'>" + name + "</option>");
				}
			},
			error: function(){
				sweet('Peringatan!!!','Gagal memuat sumber kas','warning','warning');
			}
		});
	});

	// jika pilih bank -> tampilkan dropdown rekening
	$(document).on('change', '#sumber_kas', function(){
		var akun = parseInt($(this).val() || 0);
		if(akun === 110){
			$('#wrap_rekening').show();
			$('#rekening_modal').empty().append("<option value='0'>Pilih rekening</option>");

			$.ajax({
				url: base_url + 'kas/rekening',
				type: 'post',
				data: {dari:'', id:''},
				dataType: 'json',
				success: function(res){
					var len = (res || []).length;
					for (var i=0; i<len; i++){
						$('#rekening_modal').append("<option value='"+res[i].id+"'>"+res[i].name+"</option>");
					}
				},
				error: function(){
					sweet('Peringatan!!!','Gagal memuat rekening bank','warning','warning');
				}
			});
		}else{
			$('#wrap_rekening').hide();
			$('#rekening_modal').empty();
		}
	});

	$(document).on("click", ".simpan_modal", function(event) {
		event.preventDefault();

		var akun = parseInt($("#sumber_kas").val() || 0);
		if(akun === 0){
			sweet("Peringatan!!!", 'Akun belum dipilih', "warning", "warning");
			return;
		}

		var rekening = 0;
		if(akun === 110){
			rekening = parseInt($("#rekening_modal").val() || 0);
			if(rekening === 0){
				sweet("Peringatan!!!", 'Rekening bank belum dipilih', "warning", "warning");
				return;
			}
		}

		var jumlah = angka($("#jumlah_modal").val());
		if(jumlah=='' || jumlah == 0){
			sweet("Peringatan!!!", 'Jumlah masih kosong', "warning", "warning");
			return;
		}

		var keterangan = $("#keterangan").val();
		if(keterangan==''){
			sweet("Peringatan!!!", 'Keterangan masih kosong', "warning", "warning");
			return;
		}

		$.ajax({
			url: base_url + "kas/simpan_modal",
			type: 'post',
			data: {akun:akun, rekening:rekening, jumlah:jumlah, keterangan:keterangan},
			dataType: 'json',
			success: function (response) {
				if(response && response.status == 200){
					$("#ModalKas").modal('hide');
					location.reload();
				}else{
					sweet('Peringatan!!!', (response && response.msg) ? response.msg : 'Gagal', 'warning', 'warning');
				}
			},
			error: function (xhr, ajaxOptions, thrownError) {
				sweet('Peringatan!!!',thrownError,'warning','warning');
			}
		});
	});

	function formatRibuanID(val){
	  val = (val || '').toString().replace(/[^\d]/g, ''); // sisakan digit saja
	  val = val.replace(/^0+(?=\d)/, ''); // hilangkan leading zero
	  if(!val) return '';
	  return val.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
	}

	// auto format saat input
	$(document).on('input', '#jumlah_modal', function(){
	  this.value = formatRibuanID(this.value);
	});

</script>
