  <!-- /.content-wrapper -->
  <footer class="main-footer">
    <div class="pull-right hidden-xs">
      <b>Version</b> 1.0
    </div>
    <strong>Copyright &copy; <?php echo date("Y"); ?></strong> - <?php 
    include '../get_profil.php';
    echo htmlspecialchars($profil['profil_nama']);
    if(!empty($profil['profil_alamat'])){
      echo ' | '.htmlspecialchars($profil['profil_alamat']);
    }
    ?>
  </footer>

  
</div>


<script src="../assets/bower_components/jquery/dist/jquery.min.js"></script>

<script src="../assets/bower_components/jquery-ui/jquery-ui.min.js"></script>

<script>
  $.widget.bridge('uibutton', $.ui.button);
</script>

<script src="../assets/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>

<script src="../assets/bower_components/raphael/raphael.min.js"></script>
<script src="../assets/bower_components/morris.js/morris.min.js"></script>

<script src="../assets/bower_components/jquery-sparkline/dist/jquery.sparkline.min.js"></script>


<script src="../assets/bower_components/datatables.net/js/jquery.dataTables.min.js"></script>
<script src="../assets/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>

<script src="../assets/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
<script src="../assets/plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script>

<script src="../assets/bower_components/jquery-knob/dist/jquery.knob.min.js"></script>

<script src="../assets/bower_components/moment/min/moment.min.js"></script>
<script src="../assets/bower_components/bootstrap-daterangepicker/daterangepicker.js"></script>

<script src="../assets/bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js"></script>

<script src="../assets/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>

<script src="../assets/bower_components/jquery-slimscroll/jquery.slimscroll.min.js"></script>

<script src="../assets/bower_components/fastclick/lib/fastclick.js"></script>

<script src="../assets/dist/js/adminlte.min.js"></script>

<script src="../assets/dist/js/pages/dashboard.js"></script>

<script src="../assets/dist/js/demo.js"></script>
<script src="../assets/bower_components/ckeditor/ckeditor.js"></script>
<script src="../assets/bower_components/chart.js/Chart.min.js"></script>
<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!-- Select2 -->
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
  $(document).ready(function(){

   // Select2: filter kategori & jenis (halaman transaksi)
   if ($('.select2-filter').length) {
     $('.select2-filter').select2({ width: '100%', placeholder: 'Pilih...', allowClear: true });
   }

   // Select2: modal Tambah Transaksi (kategori & rekening bank)
   if ($('#exampleModal').length) {
     $('#exampleModal select.select2-form').select2({
       width: '100%',
       placeholder: function(){ return $(this).data('placeholder') || 'Cari atau pilih...'; },
       allowClear: false,
       dropdownParent: $('#exampleModal')
     });
   }

   // $(".edit").hide();

   // Hanya inisialisasi DataTables untuk transaksi (server-side)
   // Bank.php memiliki konfigurasi DataTables sendiri (client-side)
   if ($('#table-datatable').length && $('#tanggal_dari').length) {
     var table = $('#table-datatable').DataTable({
    'processing': true,
    'serverSide': true,
    'ajax': {
      'url': 'transaksi_ajax.php',
      'type': 'POST',
      'data': function(d) {
        // Tambahkan parameter filter ke request
        d.tanggal_dari = $('#tanggal_dari').val();
        d.tanggal_sampai = $('#tanggal_sampai').val();
        d.filter_kategori = $('#filter_kategori').val();
        d.filter_jenis = $('#filter_jenis').val();
      },
      'dataSrc': function(json) {
        // Update total pemasukan, pengeluaran, selisih (dinamis sesuai filter)
        if (typeof json.total_pemasukan !== 'undefined' && $('#total-pemasukan').length) {
          var fmt = function(n) { return Math.round(n).toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.'); };
          $('#total-pemasukan').text('Rp. ' + fmt(json.total_pemasukan) + ' ,-');
          $('#total-pengeluaran').text('Rp. ' + fmt(json.total_pengeluaran) + ' ,-');
          $('#total-selisih').text('Rp. ' + fmt(parseFloat(json.total_pemasukan) - parseFloat(json.total_pengeluaran)) + ' ,-');
        }
        return json.data;
      }
    },
    'paging'      : true,
    'lengthChange': true,
    'searching'   : true,
    'ordering'    : true,
    'info'        : true,
    'autoWidth'   : false,
    'pageLength': 50,
    'lengthMenu': [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
    'columns': [
      { 'data': 0, 'orderable': false },
      { 'data': 1, 'orderable': true },
      { 'data': 2, 'orderable': true },
      { 'data': 3, 'orderable': true },
      { 'data': 4, 'orderable': false },
      { 'data': 5, 'orderable': false },
      { 'data': 6, 'orderable': false }
    ],
    'language': {
      'processing': 'Memproses data...',
      'search': 'Cari:',
      'lengthMenu': 'Tampilkan _MENU_ data per halaman',
      'info': 'Menampilkan _START_ sampai _END_ dari _TOTAL_ data',
      'infoEmpty': 'Menampilkan 0 sampai 0 dari 0 data',
      'infoFiltered': '(difilter dari _MAX_ total data)',
      'zeroRecords': 'Tidak ada data yang ditemukan',
      'emptyTable': 'Tidak ada data tersedia',
      'paginate': {
        'first': 'Pertama',
        'last': 'Terakhir',
        'next': 'Selanjutnya',
        'previous': 'Sebelumnya'
      }
    }
    });
   }

  // Handle modal edit
  $(document).on('click', '.btn-edit', function() {
    var id = $(this).data('id');
    $('#modalEditContent').load('transaksi_modal_edit.php?id=' + id, function() {
      $('#modalEditContent .datepicker2').datepicker({
        autoclose: true,
        format: 'dd/mm/yyyy',
        todayHighlight: true
      });
      // Select2 di modal Edit (kategori & rekening bank)
      $('#modalEditContent select.select2-form').each(function() {
        if ($(this).data('select2')) $(this).select2('destroy');
      });
      $('#modalEditContent select.select2-form').select2({
        width: '100%',
        placeholder: function(){ return $(this).data('placeholder') || 'Cari atau pilih...'; },
        allowClear: false,
        dropdownParent: $('#modalEdit')
      });
    });
  });

  // Handle modal lihat
  $(document).on('click', '.btn-lihat', function() {
    var foto = $(this).data('foto') || '';
    if (!foto) {
      $('#modalLihatContent').html('<p class="text-muted">Tidak ada bukti upload untuk transaksi ini.</p>');
    } else {
      $('#modalLihatContent').html('<embed src="../gambar/bukti/' + foto + '" type="application/pdf" width="100%" height="400px" />');
    }
  });

  // Handle modal hapus dengan SweetAlert
  $(document).on('click', '.btn-hapus', function(e) {
    e.preventDefault();
    var id = $(this).data('id');
    var deleteUrl = 'transaksi_hapus.php?id=' + id;
    
    Swal.fire({
      title: 'Apakah Anda Yakin?',
      text: 'Data transaksi yang dihapus tidak dapat dikembalikan!',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#d33',
      cancelButtonColor: '#3085d6',
      confirmButtonText: 'Ya, Hapus!',
      cancelButtonText: 'Batal'
    }).then((result) => {
      if (result.isConfirmed) {
        window.location.href = deleteUrl;
      }
    });
  });

  // Handle filter button
  $('#btnFilter').on('click', function() {
    table.draw();
  });

  // Handle reset button
  $('#btnReset').on('click', function() {
    $('#tanggal_dari').val('');
    $('#tanggal_sampai').val('');
    $('#filter_kategori').val('');
    $('#filter_jenis').val('');
    table.draw();
  });

  // Modal Tambah Transaksi: datepicker format dd/mm/yyyy saat modal dibuka
  $('#exampleModal').on('shown.bs.modal', function() {
    var $dp = $(this).find('.datepicker2');
    if ($dp.length) {
      try { $dp.datepicker('destroy'); } catch (e) {}
      $dp.datepicker({ autoclose: true, format: 'dd/mm/yyyy', todayHighlight: true });
    }
  });

  // Format Rupiah untuk input nominal (transaksi & halaman lain yang pakai .input-rupiah)
  function stripRupiahInput(el) {
    var v = $(el).val().replace(/\D/g, '');
    $(el).val(v);
    return v;
  }
  $(document).on('input keyup', '.input-rupiah', function() {
    var n = $(this).val().replace(/\D/g, '');
    var pos = this.selectionStart;
    var prevLen = $(this).val().length;
    var formatted = n === '' ? '' : 'Rp. ' + n.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
    $(this).val(formatted);
    var newLen = formatted.length;
    this.setSelectionRange(Math.max(0, pos + newLen - prevLen), Math.max(0, pos + newLen - prevLen));
  });
  $(document).on('focus', '.input-rupiah', function() {
    var n = $(this).val().replace(/\D/g, '');
    if (n !== '') $(this).val('Rp. ' + n.replace(/\B(?=(\d{3})+(?!\d))/g, '.'));
  });
  $('form').on('submit', function() {
    $(this).find('.input-rupiah').each(function() { stripRupiahInput(this); });
  });

  // SweetAlert Notifications
  <?php 
  if(isset($_SESSION['alert']) && isset($_SESSION['message'])):
    $alertType = $_SESSION['alert'];
    $message = $_SESSION['message'];
    unset($_SESSION['alert']);
    unset($_SESSION['message']);
    
    if($alertType == 'success'):
    ?>
      Swal.fire({
        icon: 'success',
        title: 'Berhasil!',
        text: <?php echo json_encode($message); ?>,
        confirmButtonColor: '#3085d6',
        confirmButtonText: 'OK',
        timer: 3000,
        timerProgressBar: true
      }).then((result) => {
        if (result.isConfirmed || result.dismiss === Swal.DismissReason.timer) {
          // Reload DataTable setelah notifikasi
          if(typeof table !== 'undefined') {
            table.draw();
          }
        }
      });
    <?php elseif($alertType == 'error'): ?>
      Swal.fire({
        icon: 'error',
        title: 'Gagal!',
        text: <?php echo json_encode($message); ?>,
        confirmButtonColor: '#d33',
        confirmButtonText: 'OK'
      });
    <?php elseif($alertType == 'warning'): ?>
      Swal.fire({
        icon: 'warning',
        title: 'Peringatan!',
        text: <?php echo json_encode($message); ?>,
        confirmButtonColor: '#ffc107',
        confirmButtonText: 'OK'
      });
    <?php endif; ?>
  <?php endif; ?>

  // Handle form submit dengan loading indicator (opsional - bisa diaktifkan jika diperlukan)
  // $('#formEditTransaksi').on('submit', function(e) {
  //   Swal.fire({
  //     title: 'Menyimpan...',
  //     text: 'Mohon tunggu, data sedang diproses',
  //     allowOutsideClick: false,
  //     allowEscapeKey: false,
  //     showConfirmButton: false,
  //     didOpen: () => {
  //       Swal.showLoading();
  //     }
  //   });
  //   return true;
  // });



 });
  
  $('#datepicker').datepicker({
    autoclose: true,
    format: 'dd/mm/yyyy',
  }).datepicker("setDate", new Date());

  $('.datepicker2').datepicker({
    autoclose: true,
    format: 'yyyy/mm/dd',
  });


</script>


<script>
  var randomScalingFactor = function(){ return Math.round(Math.random()*100)};

  var barChartData = {
    labels : ["Jan","Feb","Mar","Apr","Mei","Jun","Jul","Agu","Sep","Okt","Nov","Des"],
    datasets : [
    {
      label: 'Pemasukan',
      fillColor : "rgba(51, 240, 113, 0.61)",
      strokeColor : "rgba(11, 246, 88, 0.61)",
      highlightFill: "rgba(220,220,220,0.75)",
      highlightStroke: "rgba(220,220,220,1)",
      data : [
      <?php
      for($bulan=1;$bulan<=12;$bulan++){
        $thn_ini = date('Y');
        $pemasukan = mysqli_query($koneksi,"select sum(transaksi_nominal) as total_pemasukan from transaksi where transaksi_jenis='Pemasukan' and month(transaksi_tanggal)='$bulan' and year(transaksi_tanggal)='$thn_ini'");
        $pem = mysqli_fetch_assoc($pemasukan);

        // $total = str_replace(",", "44", number_format($pem['total_pemasukan']));
        $total = $pem['total_pemasukan'];
        if($pem['total_pemasukan'] == ""){
          echo "0,";
        }else{
          echo $total.",";
        }

      }
      ?>
      ]
    },
    {
      label: 'Pengeluaran',
      fillColor : "rgba(255, 51, 51, 0.8)",
      strokeColor : "rgba(248, 5, 5, 0.8)",
      highlightFill : "rgba(151,187,205,0.75)",
      highlightStroke : "rgba(151,187,205,1)",
      data : [
      <?php
      for($bulan=1;$bulan<=12;$bulan++){
        $thn_ini = date('Y');
        $pengeluaran = mysqli_query($koneksi,"select sum(transaksi_nominal) as total_pengeluaran from transaksi where transaksi_jenis='pengeluaran' and month(transaksi_tanggal)='$bulan' and year(transaksi_tanggal)='$thn_ini'");
        $peng = mysqli_fetch_assoc($pengeluaran);

        // $total = str_replace(",", "44", number_format($peng['total_pengeluaran']));
        $total = $peng['total_pengeluaran'];
        if($peng['total_pengeluaran'] == ""){
          echo "0,";
        }else{

          echo $total.",";
        }
      }
      ?>
      ]
    }
    ]

  }


  var barChartData2 = {
    labels : [
    <?php 
    $tahun = mysqli_query($koneksi,"select distinct year(transaksi_tanggal) as tahun from transaksi order by year(transaksi_tanggal) asc");
    while($t = mysqli_fetch_array($tahun)){
      ?>
      "<?php echo $t['tahun']; ?>",
      <?php 
    }
    ?>
    ],
    datasets : [
    {
      label: 'Pemasukan',
      fillColor : "rgba(51, 240, 113, 0.61)",
      strokeColor : "rgba(11, 246, 88, 0.61)",
      highlightFill: "rgba(220,220,220,0.75)",
      highlightStroke: "rgba(220,220,220,1)",
      data : [
      <?php
      $tahun = mysqli_query($koneksi,"select distinct year(transaksi_tanggal) as tahun from transaksi order by year(transaksi_tanggal) asc");
      while($t = mysqli_fetch_array($tahun)){
        $thn = $t['tahun'];
        $pemasukan = mysqli_query($koneksi,"select sum(transaksi_nominal) as total_pemasukan from transaksi where transaksi_jenis='Pemasukan' and year(transaksi_tanggal)='$thn'");
        $pem = mysqli_fetch_assoc($pemasukan);
        $total = $pem['total_pemasukan'];
        if($pem['total_pemasukan'] == ""){
          echo "0,";
        }else{
          echo $total.",";
        }

      }
      ?>
      ]
    },
    {
      label: 'Pengeluaran',
      fillColor : "rgba(255, 51, 51, 0.8)",
      strokeColor : "rgba(248, 5, 5, 0.8)",
      highlightFill : "rgba(151,187,205,0.75)",
      highlightStroke : "rgba(254, 29, 29, 0)",
      data : [
      <?php
      $tahun = mysqli_query($koneksi,"select distinct year(transaksi_tanggal) as tahun from transaksi order by year(transaksi_tanggal) asc");
      while($t = mysqli_fetch_array($tahun)){
        $thn = $t['tahun'];
        $pemasukan = mysqli_query($koneksi,"select sum(transaksi_nominal) as total_pengeluaran from transaksi where transaksi_jenis='Pengeluaran' and year(transaksi_tanggal)='$thn'");
        $pem = mysqli_fetch_assoc($pemasukan);
        $total = $pem['total_pengeluaran'];
        if($pem['total_pengeluaran'] == ""){
          echo "0,";
        }else{
          echo $total.",";
        }

      }
      ?>
      ]
    }
    ]

  }



  window.onload = function(){
    var ctx = document.getElementById("grafik1").getContext("2d");
    window.myBar = new Chart(ctx).Bar(barChartData, {
     responsive : true,
     animation: true,
     barValueSpacing : 5,
     barDatasetSpacing : 1,
     tooltipFillColor: "rgba(0,0,0,0.8)",
     multiTooltipTemplate: "<%= datasetLabel %> - Rp.<%= value.toLocaleString() %>,-"
   });

   var ctx = document.getElementById("grafik2").getContext("2d");
    window.myBar = new Chart(ctx).Bar(barChartData2, {
     responsive : true,
     animation: true,
     barValueSpacing : 5,
     barDatasetSpacing : 1,
     tooltipFillColor: "rgba(0,0,0,0.8)",
     multiTooltipTemplate: "<%= datasetLabel %> - Rp.<%= value.toLocaleString() %>,-"
   });




    


  }












</script>

</body>
</html>
