<?php foreach($kontak as $kontak) :   endforeach; ?>
<?php foreach($admin_login as $user) :   endforeach; ?> 
  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <div class="content-header">
      <div class="container-fluid">
        <div class="row mb-2">
          <div class="col-sm-6">
            <h1 class="m-0 text-dark"> 
                 <?php echo $title1; ?>
            </h1>
          </div><!-- /.col -->
          <div class="col-sm-6">
            <ol class="breadcrumb float-sm-right">
              <li class="breadcrumb-item"><a href="#">Home</a></li>
              <li class="breadcrumb-item active"><?php echo $title1; ?></li>
            </ol>
          </div><!-- /.col -->
        </div><!-- /.row -->
      </div><!-- /.container-fluid -->
    </div>
    <!-- /.content-header -->
      
          
    <!-- Main content -->
    <section class="content">
      <div class="container-fluid">
          <div class="card">
              <div class="card-header">
                

                <button class="btn btn-success" data-toggle="modal" data-target="#modalTambah">Tambah Data</button>
                <hr>
                <div class="row">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>Tanggal Awal</label>
                            <input type="date" id="tgl_awal" class="form-control " value="<?= date('Y-m-01') ?>">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>Tanggal Akhir</label>
                            <input type="date" id="tgl_akhir" class="form-control " value="<?= date('Y-m-t') ?>">
                        </div>
                    </div>
                    <div class="col-md-3 align-self-end">
                        <div class="form-group">
                        <button id="btn-filter" class="btn btn-primary">Filter</button>
                        </div>
                    </div>
                </div>
                

              </div>
              <!-- /.card-header -->
              <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        <div class="alert alert-success">
                            <h4>Total Pemasukan</h4>
                            <h3 id="total-pemasukan">Rp <?= number_format($totals['pemasukan'], 0, ',', '.') ?></h3>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="alert alert-danger">
                            <h4>Total Pengeluaran</h4>
                            <h3 id="total-pengeluaran">Rp <?= number_format($totals['pengeluaran'], 0, ',', '.') ?></h3>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="alert alert-info">
                            <h4>Saldo Akhir</h4>
                            <h3 id="saldo-akhir">Rp <?= number_format($totals['pemasukan'] - $totals['pengeluaran'], 0, ',', '.') ?></h3>
                        </div>
                    </div>
                </div>
                <hr>
                <table   class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Tanggal</th>
                            <th>Keterangan</th>
                            <th>Jenis</th>
                            <th>Nominal</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody id="table-body">
                        <?php foreach($transaksi as $t): ?>
                        <tr id="row-<?= $t->id_bukukas ?>">
                            <td><?= htmlspecialchars($t->id_bukukas) ?></td>
                            <td><?= htmlspecialchars($t->date) ?></td>
                            <td><?= htmlspecialchars($t->keterangan) ?></td>
                            <td class="<?= $t->jenis ?>"><?= ucfirst($t->jenis) ?></td>
                            <td>Rp <?= number_format($t->nominal, 0, ',', '.') ?></td>
                            <td>
                                <button class="btn btn-sm btn-warning btn-edit" 
                                        data-id="<?= $t->id_bukukas ?>"
                                        data-keterangan="<?= htmlspecialchars($t->keterangan) ?>"
                                        data-jenis="<?= $t->jenis ?>"
                                        data-nominal="<?= $t->nominal ?>"
                                        data-tanggal="<?= $t->date ?>">Edit</button>
                                <button class="btn btn-sm btn-danger btn-hapus" data-id="<?= $t->id_bukukas ?>">Hapus</button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>

              </div>
              <!-- /.card-body -->
            </div>
      </div><!-- /.container-fluid -->
    </section>
    <!-- /.content -->
  </div>
  <!-- /.content-wrapper -->


<!-- Modal Tambah -->
<div class="modal fade" id="modalTambah">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Tambah Transaksi</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form id="formTambah">
                <div class="modal-body">
                    <div class="form-group">
                        <label>Keterangan</label>
                        <input type="text" name="keterangan" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Jenis</label>
                        <select name="jenis" class="form-control" required>
                            <option value="">Pilih Jenis</option>
                            <option value="pemasukan">Pemasukan</option>
                            <option value="pengeluaran">Pengeluaran</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Nominal</label>
                        <input type="number" name="nominal" class="form-control" required min="1">
                    </div>
                    <div class="form-group">
                        <label>Tanggal</label>
                        <input type="text" name="tanggal" class="form-control datepicker" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary">Simpan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal Edit -->
<div class="modal fade" id="modalEdit">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Transaksi</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form id="formEdit">
                <input type="hidden" name="id" id="edit_id">
                <div class="modal-body">
                    <div class="form-group">
                        <label>Keterangan</label>
                        <input type="text" name="keterangan" id="edit_keterangan" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Jenis</label>
                        <select name="jenis" id="edit_jenis" class="form-control" required>
                            <option value="pemasukan">Pemasukan</option>
                            <option value="pengeluaran">Pengeluaran</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Nominal</label>
                        <input type="number" name="nominal" id="edit_nominal" class="form-control" required min="1">
                    </div>
                    <div class="form-group">
                        <label>Tanggal</label>
                        <input type="text" name="tanggal" id="edit_tanggal" class="form-control datepicker" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary">Update</button>
                </div>
            </form>
        </div>
    </div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script>
    $(document).ready(function() {
        // Fungsi format nominal
        function formatRupiah(nominal) {
            return 'Rp ' + parseInt(nominal).toLocaleString('id-ID');
        }

        // Fungsi show toast
        function showToast(message, type = 'success') {
            const $toast = $('#toast');
            $toast.find('.toast-body').text(message);
            $toast.removeClass('bg-success bg-danger')
                   .addClass(type === 'success' ? 'bg-success' : 'bg-danger');
            $toast.toast({ delay: 3000 }).toast('show');
        }

        // Inisialisasi datepicker
        $('.datepicker').datepicker({
            format: 'yyyy-mm-dd',
            autoclose: true,
            language: 'id'
        });

        // Filter data
        $('#btn-filter').click(function() {
            const tgl_awal = $('#tgl_awal').val();
            const tgl_akhir = $('#tgl_akhir').val();
            
            // Validasi tanggal
            if (new Date(tgl_awal) > new Date(tgl_akhir)) {
                showToast('Tanggal akhir tidak boleh lebih awal dari tanggal awal', 'danger');
                return;
            }
            
            $.post('<?= site_url('bukukas/filter') ?>', { tgl_awal, tgl_akhir })
            .done(function(data) {
                try {
                    const result = JSON.parse(data);
                    const transaksi = result.transaksi;
                    const totals = result.totals;
                    
                    let html = '';
                    
                    transaksi.forEach(t => {
                        html += `
                        <tr id="row-${t.id_bukukas}">
                            <td>${t.id_bukukas}</td>
                            <td>${t.date}</td>
                            <td>${escapeHtml(t.keterangan)}</td>
                            <td class="${t.jenis}">${t.jenis.charAt(0).toUpperCase() + t.jenis.slice(1)}</td>
                            <td>${formatRupiah(t.nominal)}</td>
                            <td>
                                <button class="btn btn-sm btn-warning btn-edit" 
                                        data-id="${t.id_bukukas}"
                                        data-keterangan="${escapeHtml(t.keterangan)}"
                                        data-jenis="${t.jenis}"
                                        data-nominal="${t.nominal}"
                                        data-tanggal="${t.date}">Edit</button>
                                <button class="btn btn-sm btn-danger btn-hapus" data-id="${t.id_bukukas}">Hapus</button>
                            </td>
                        </tr>
                        `;
                    });
                    
                    $('#table-body').html(html);
                    
                    // Update total
                    $('#total-pemasukan').text(formatRupiah(totals.pemasukan));
                    $('#total-pengeluaran').text(formatRupiah(totals.pengeluaran));
                    
                    const saldo = totals.pemasukan - totals.pengeluaran;
                    $('#saldo-akhir').text(formatRupiah(saldo));
                    
                    showToast('Data berhasil difilter', 'success');
                } catch (e) {
                    showToast('Error parsing data: ' + e.message, 'danger');
                }
            })
            .fail(function() {
                showToast('Terjadi kesalahan saat memfilter data', 'danger');
            });
        });

        // Tambah data
        $('#formTambah').submit(function(e) {
            e.preventDefault();
            
            $.post('<?= site_url('bukukas/tambah') ?>', $(this).serialize())
            .done(function(data) {
                try {
                    const t = JSON.parse(data);
                    const newRow = `
                    <tr id="row-${t.id_bukukas}">
                        <td>${t.id_bukukas}</td>
                        <td>${t.date}</td>
                        <td>${escapeHtml(t.keterangan)}</td>
                        <td class="${t.jenis}">${t.jenis.charAt(0).toUpperCase() + t.jenis.slice(1)}</td>
                        <td>${formatRupiah(t.nominal)}</td>
                        <td>
                            <button class="btn btn-sm btn-warning btn-edit" 
                                    data-id="${t.id_bukukas}"
                                    data-keterangan="${escapeHtml(t.keterangan)}"
                                    data-jenis="${t.jenis}"
                                    data-nominal="${t.nominal}"
                                    data-tanggal="${t.date}">Edit</button>
                            <button class="btn btn-sm btn-danger btn-hapus" data-id="${t.id_bukukas}">Hapus</button>
                        </td>
                    </tr>
                    `;
                    
                    $('#table-body').prepend(newRow);
                    $('#modalTambah').modal('hide');
                    $('#formTambah')[0].reset();
                    $('#btn-filter').click(); // Refresh totals
                    showToast('Data berhasil ditambahkan', 'success');
                } catch (e) {
                    showToast('Error parsing data: ' + e.message, 'danger');
                }
            })
            .fail(function() {
                showToast('Gagal menambahkan data', 'danger');
            });
        });

        // Edit data - tampilkan modal
        $(document).on('click', '.btn-edit', function() {
            const id = $(this).data('id');
            const keterangan = $(this).data('keterangan');
            const jenis = $(this).data('jenis');
            const nominal = $(this).data('nominal');
            const tanggal = $(this).data('tanggal');
            
            $('#edit_id').val(id);
            $('#edit_keterangan').val(keterangan);
            $('#edit_jenis').val(jenis);
            $('#edit_nominal').val(nominal);
            $('#edit_tanggal').val(tanggal);
            
            $('#modalEdit').modal('show');
        });

        // Edit data - proses update
        $('#formEdit').submit(function(e) {
            e.preventDefault();
            const id = $('#edit_id').val();
            
            $.post('<?= site_url('bukukas/edit/') ?>' + id, $(this).serialize())
            .done(function(data) {
                try {
                    const t = JSON.parse(data);
                    const row = $(`#row-${t.id_bukukas}`);
                    
                    row.find('td:eq(1)').text(t.date);
                    row.find('td:eq(2)').text(t.keterangan);
                    row.find('td:eq(3)')
                        .attr('class', t.jenis)
                        .text(t.jenis.charAt(0).toUpperCase() + t.jenis.slice(1));
                    row.find('td:eq(4)').text(formatRupiah(t.nominal));
                    
                    // Update data di tombol edit
                    row.find('.btn-edit')
                        .data('keterangan', t.keterangan)
                        .data('jenis', t.jenis)
                        .data('nominal', t.nominal)
                        .data('tanggal', t.date);
                    
                    $('#modalEdit').modal('hide');
                    $('#btn-filter').click(); // Refresh totals
                    showToast('Data berhasil diperbarui', 'success');
                } catch (e) {
                    showToast('Error parsing data: ' + e.message, 'danger');
                }
            })
            .fail(function() {
                showToast('Gagal memperbarui data', 'danger');
            });
        });

        // Hapus data
        $(document).on('click', '.btn-hapus', function() {
            if(confirm('Apakah Anda yakin ingin menghapus data ini?')) {
                const id = $(this).data('id');
                
                $.post('<?= site_url('bukukas/hapus/') ?>' + id)
                .done(function() {
                    $(`#row-${id}`).remove();
                    $('#btn-filter').click(); // Refresh totals
                    showToast('Data berhasil dihapus', 'success');
                })
                .fail(function() {
                    showToast('Gagal menghapus data', 'danger');
                });
            }
        });

        // Fungsi escape HTML
        function escapeHtml(text) {
            return text
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }
    });
</script>