<?php include 'header.php'; ?>

<div class="content-wrapper">

  <section class="content-header">
    <h1>
      Bank
      <small>Data bank</small>
    </h1>
    <ol class="breadcrumb">
      <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
      <li class="active">Dashboard</li>
    </ol>
  </section>

  <section class="content">
    <div class="row">
      <section class="col-lg-12">
        <div class="box box-info">

          <div class="box-header">
            <h3 class="box-title">Data Akun Bank</h3>
            <div class="btn-group pull-right">            

              <button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#exampleModal">
                <i class="fa fa-plus"></i> &nbsp Tambah Bank
              </button>
            </div>
          </div>
          <div class="box-body">

            <!-- Modal -->
            <form action="bank_act.php" method="post">
              <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
                <div class="modal-dialog" role="document">
                  <div class="modal-content">
                    <div class="modal-header">
                      <h5 class="modal-title" id="exampleModalLabel">Tambah bank</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>Nama bank</label>
                        <input type="text" name="nama" required="required" class="form-control" placeholder="Nama bank ..">
                      </div>

                      <div class="form-group">
                        <label>Nama Pemilik Rekening</label>
                        <input type="text" name="pemilik" class="form-control" placeholder="Nama pemiliki rekening bank ..">
                      </div>

                      <div class="form-group">
                        <label>Nomor Rekening</label>
                        <input type="text" name="nomor" class="form-control" placeholder="Nomor rekening bank ..">
                      </div>

                      <div class="form-group">
                        <label>Saldo Awal</label>
                        <input type="text" name="saldo" required="required" class="form-control input-rupiah" placeholder="0" autocomplete="off">
                      </div>

                    </div>
                    <div class="modal-footer">
                      <button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>
                      <button type="submit" class="btn btn-primary">Simpan</button>
                    </div>
                  </div>
                </div>
              </div>
            </form>


            <div class="table-responsive">
              <table class="table table-bordered table-striped" id="table-datatable">
                <thead>
                  <tr>
                    <th width="1%">NO</th>
                    <th>NAMA BANK</th>
                    <th>PEMILIK REKENING</th>
                    <th>NOMOR REKENING</th>
                    <th>SALDO</th>
                    <th width="10%">OPSI</th>
                  </tr>
                </thead>
                <tbody>
                  <?php 
                  include '../koneksi.php';
                  $no=1;
                  $data = mysqli_query($koneksi,"SELECT bank_id, bank_nama, bank_pemilik, bank_nomor, bank_saldo FROM bank ORDER BY bank_id ASC");
                  while($d = mysqli_fetch_assoc($data)){
                    // Cek apakah bank terpakai: punya saldo != 0 atau ada transaksi yang pakai bank ini
                    $bid = (int)$d['bank_id'];
                    $saldo = (float)($d['bank_saldo'] ?? 0);
                    $cek_trans = mysqli_query($koneksi, "SELECT COUNT(*) as jml FROM transaksi WHERE transaksi_bank='$bid'");
                    $jml_trans = (int)mysqli_fetch_assoc($cek_trans)['jml'];
                    $terpakai = ($saldo != 0 || $jml_trans > 0);
                    $title_lock = 'Bank memiliki saldo atau terpakai di transaksi. Edit/Hapus dinonaktifkan untuk keamanan data.';
                    ?>
                    <tr>
                      <td class="text-center"><?php echo $no++; ?></td>
                      <td><?php echo !empty($d['bank_nama']) ? htmlspecialchars($d['bank_nama']) : '-'; ?></td>
                      <td><?php echo !empty($d['bank_pemilik']) ? htmlspecialchars($d['bank_pemilik']) : '-'; ?></td>
                      <td><?php echo !empty($d['bank_nomor']) ? htmlspecialchars($d['bank_nomor']) : '-'; ?></td>
                      <td class="text-right"><?php echo "Rp. ".number_format($d['bank_saldo'] ?? 0, 0, ',', '.')." ,-"; ?></td>
                      <td class="text-center">    
                        <?php if ($terpakai) { ?>
                        <button type="button" class="btn btn-warning btn-sm" disabled title="<?php echo htmlspecialchars($title_lock); ?>">
                          <i class="fa fa-lock"></i>
                        </button>
                        <button type="button" class="btn btn-danger btn-sm" disabled title="<?php echo htmlspecialchars($title_lock); ?>">
                          <i class="fa fa-lock"></i>
                        </button>
                        <?php } else { ?>
                        <button type="button" class="btn btn-warning btn-sm" data-toggle="modal" data-target="#edit_bank_<?php echo $d['bank_id'] ?>" title="Edit bank">
                          <i class="fa fa-cog"></i>
                        </button>
                        <?php 
                        if($d['bank_id'] != 1){
                          ?>
                          <button type="button" class="btn btn-danger btn-sm btn-hapus-bank" data-id="<?php echo $d['bank_id'] ?>" title="Hapus bank">
                            <i class="fa fa-trash"></i>
                          </button>
                          <?php
                        }
                        ?>
                        <?php } ?>

                        <form action="bank_update.php" method="post">
                          <div class="modal fade" id="edit_bank_<?php echo $d['bank_id'] ?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
                            <div class="modal-dialog" role="document">
                              <div class="modal-content">
                                <div class="modal-header">
                                  <h4 class="modal-title" id="exampleModalLabel">Edit bank</h4>
                                  <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" style="margin-bottom:15px;width: 100%">
                                    <label>Nama bank</label>
                                    <input type="hidden" name="id" required="required" class="form-control" placeholder="Nama bank .." value="<?php echo $d['bank_id']; ?>">
                                    <input type="text" name="nama" style="width:100%" required="required" class="form-control" placeholder="Nama bank .." value="<?php echo $d['bank_nama']; ?>">
                                  </div>

                                  <div class="form-group" style="margin-bottom:15px;width: 100%">
                                    <label>Nama Pemilik Rekening</label>
                                    <input type="text" name="pemilik" style="width:100%" class="form-control" placeholder="Nama pemiliki rekening bank .." value="<?php echo $d['bank_pemilik']; ?>">
                                  </div>

                                  <div class="form-group" style="margin-bottom:15px;width: 100%">
                                    <label>Nomor Rekening</label>
                                    <input type="text" name="nomor" style="width:100%" class="form-control" placeholder="Nomor rekening bank .." value="<?php echo $d['bank_nomor']; ?>">
                                  </div>

                                  <div class="form-group" style="margin-bottom:15px;width: 100%">
                                    <label>Saldo Awal</label>
                                    <input type="text" name="saldo" style="width:100%" required="required" class="form-control input-rupiah" placeholder="0" value="<?php $s = (float)($d['bank_saldo'] ?? 0); echo $s > 0 ? 'Rp. ' . number_format($s, 0, '', '.') : ''; ?>" autocomplete="off">
                                  </div>

                                </div>
                                <div class="modal-footer">
                                  <button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>
                                  <button type="submit" class="btn btn-primary">Simpan</button>
                                </div>
                              </div>
                            </div>
                          </div>
                        </form>


                      </td>
                    </tr>
                    <?php 
                  }
                  ?>
                </tbody>
              </table>
            </div>
          </div>

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

</div>

<?php include 'footer.php'; ?>

<script>
$(document).ready(function() {
  // Konfigurasi DataTables khusus untuk bank (client-side karena data biasanya tidak banyak)
  if ($('#table-datatable').length && !$('#table-datatable').hasClass('server-side')) {
    $('#table-datatable').DataTable({
      'paging': true,
      'lengthChange': true,
      'searching': true,
      'ordering': true,
      'info': true,
      'autoWidth': false,
      'pageLength': 25,
      'lengthMenu': [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
      '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'
        }
      },
      'columnDefs': [
        { 'orderable': false, 'targets': [0, 5] }, // NO dan OPSI tidak bisa di-sort
        { 'className': 'text-center', 'targets': [0, 5] },
        { 'className': 'text-right', 'targets': [4] }
      ]
    });
  }

  // Format Rupiah untuk input Saldo Awal
  function formatRupiahDisplay(angka) {
    var n = String(angka).replace(/\D/g, '');
    return n === '' ? '' : 'Rp. ' + n.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
  }
  function stripRupiah(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, '.'));
  });
  // Saat buka modal Tambah, pastikan input rupiah kosong/format
  $('#exampleModal').on('show.bs.modal', function() {
    var $in = $(this).find('.input-rupiah');
    if ($in.val() === '' || $in.val().replace(/\D/g, '') === '') return;
    $in.val('');
  });
  // Sebelum submit form (Tambah atau Edit), kirim nilai angka saja
  $('form').on('submit', function() {
    $(this).find('.input-rupiah').each(function() {
      stripRupiah(this);
    });
  });

  // Handle hapus bank dengan SweetAlert
  $(document).on('click', '.btn-hapus-bank', function(e) {
    e.preventDefault();
    var id = $(this).data('id');
    var deleteUrl = 'bank_hapus.php?id=' + id;
    
    Swal.fire({
      title: 'Apakah Anda Yakin?',
      html: '<p style="font-size: 1.6rem;">Data bank yang dihapus tidak dapat dikembalikan!</p><p style="font-size: 1.4rem; color: #666;">Semua transaksi yang berhubungan dengan akun bank ini akan dipindahkan ke akun bank default.</p>',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#d33',
      cancelButtonColor: '#3085d6',
      confirmButtonText: 'Ya, Hapus!',
      cancelButtonText: 'Batal'
    }).then((result) => {
      if (result.isConfirmed) {
        window.location.href = deleteUrl;
      }
    });
  });

  // 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) {
          location.reload();
        }
      });
    <?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; ?>
});
</script>