<?php 
include 'header.php';
include '../koneksi.php';

// Buat tabel jika belum ada (untuk kemudahan instalasi)
$cek = mysqli_query($koneksi, "SHOW TABLES LIKE 'laporan_kasir'");
if (mysqli_num_rows($cek) == 0) {
  mysqli_query($koneksi, "CREATE TABLE IF NOT EXISTS `laporan_kasir` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `tanggal` date NOT NULL,
    `shift` enum('Pagi','Siang','Malam') NOT NULL,
    `nominal` bigint(20) NOT NULL DEFAULT 0,
    `keterangan` text DEFAULT NULL,
    PRIMARY KEY (`id`),
    KEY `tanggal` (`tanggal`),
    KEY `shift` (`shift`)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
}

// Filter
$tanggal_dari = isset($_GET['tanggal_dari']) ? mysqli_real_escape_string($koneksi, $_GET['tanggal_dari']) : '';
$tanggal_sampai = isset($_GET['tanggal_sampai']) ? mysqli_real_escape_string($koneksi, $_GET['tanggal_sampai']) : '';
$filter_shift = isset($_GET['shift']) ? mysqli_real_escape_string($koneksi, $_GET['shift']) : '';
?>

<div class="content-wrapper">

  <section class="content-header">
    <h1>Pembayaran Tunai (Laporan Kasir)</h1>
    <ol class="breadcrumb">
      <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
      <li class="active">Pembayaran Tunai</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 Pembayaran Tunai dari Laporan Kasir</h3>
            <?php if (empty($is_input_pengeluaran)) { ?>
            <div class="btn-group pull-right">
              <button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#modalTambah">
                <i class="fa fa-plus"></i> &nbsp Tambah Laporan
              </button>
            </div>
            <?php } ?>
          </div>

          <!-- Filter -->
          <div class="box-body" style="border-bottom:1px solid #f4f4f4;">
            <form id="filterFormTunai" class="form-inline">
              <div class="form-group">
                <label>Dari Tanggal</label>
                <input type="text" id="tanggal_dari_tunai" name="tanggal_dari" class="form-control datepicker2" placeholder="Dari" value="<?php echo htmlspecialchars($tanggal_dari); ?>" autocomplete="off" style="width:120px">
              </div>
              <div class="form-group">
                <label>Sampai Tanggal</label>
                <input type="text" id="tanggal_sampai_tunai" name="tanggal_sampai" class="form-control datepicker2" placeholder="Sampai" value="<?php echo htmlspecialchars($tanggal_sampai); ?>" autocomplete="off" style="width:120px">
              </div>
              <div class="form-group">
                <label>Shift</label>
                <select name="shift" id="filter_shift_tunai" class="form-control" style="width:130px">
                  <option value="">Semua Shift</option>
                  <option value="Pagi" <?php echo $filter_shift==='Pagi'?'selected':''; ?>>Pagi</option>
                  <option value="Siang" <?php echo $filter_shift==='Siang'?'selected':''; ?>>Siang</option>
                  <option value="Malam" <?php echo $filter_shift==='Malam'?'selected':''; ?>>Malam</option>
                </select>
              </div>
              <button type="button" id="btnFilterTunai" class="btn btn-primary"><i class="fa fa-filter"></i> Filter</button>
              <a href="pembayaran_tunai.php" class="btn btn-default">Reset</a>
            </form>
          </div>

          <div class="box-body">
            <!-- Total dari data yang difilter (di-update via AJAX) -->
            <div class="row" style="margin-bottom:16px">
              <div class="col-md-12">
                <div class="alert alert-info">
                  <strong>Jumlah Total (data yang difilter):</strong> 
                  <span id="total-filter" style="font-weight: bold; font-size: 1.81em;"><b>Rp. 0 ,-</b></span>
                </div>
              </div>
            </div>

            <div class="table-responsive">
              <table class="table table-bordered table-striped table-hover" id="table-pembayaran">
                <thead>
                  <tr>
                    <th width="1%" class="text-center">NO</th>
                    <th width="12%" class="text-center">TANGGAL LAPORAN</th>
                    <th width="10%" class="text-center">SHIFT</th>
                    <th width="18%" class="text-right">JUMLAH (Rp)</th>
                    <th>KETERANGAN</th>
                    <th width="10%" class="text-center">OPSI</th>
                  </tr>
                </thead>
                <tbody>
                  <!-- Data di-load via AJAX (server-side) -->
                </tbody>
              </table>
            </div>

            <!-- Grafik naik turun pembayaran -->
            <div class="row" style="margin-top:24px">
              <div class="col-md-12">
                <div class="box box-solid">
                  <div class="box-header with-border">
                    <h3 class="box-title">Grafik Pembayaran Tunai (per tanggal)</h3>
                  </div>
                  <div class="box-body">
                    <canvas id="chartPembayaran" height="80"></canvas>
                  </div>
                </div>
              </div>
            </div>
          </div>

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

</div>

<!-- Modal Tambah -->
<div class="modal fade" id="modalTambah" tabindex="-1" role="dialog" data-backdrop="static" data-keyboard="false">
  <div class="modal-dialog" role="document">
    <form action="pembayaran_tunai_act.php" method="post">
      <div class="modal-content">
        <div class="modal-header">
          <h4 class="modal-title">Tambah Pembayaran Tunai</h4>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>Tanggal Laporan</label>
            <input type="text" name="tanggal" class="form-control datepicker2" required placeholder="dd/mm/yyyy" autocomplete="off">
          </div>
          <div class="form-group">
            <label>Shift</label>
            <select name="shift" class="form-control" required>
              <option value="">- Pilih Shift -</option>
              <option value="Pagi">Pagi</option>
              <option value="Siang">Siang</option>
              <option value="Malam">Malam</option>
            </select>
          </div>
          <div class="form-group">
            <label>Jumlah Uang (Rp)</label>
            <input type="text" name="nominal" class="form-control input-rupiah" required placeholder="0" autocomplete="off">
          </div>
          <div class="form-group">
            <label>Keterangan <small class="text-muted">(opsional)</small></label>
            <textarea name="keterangan" class="form-control" rows="2" placeholder="Kosongkan jika tidak ada"></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Batal</button>
          <button type="submit" class="btn btn-success">Simpan</button>
        </div>
      </div>
    </form>
  </div>
</div>

<!-- Modal Edit (content di-load via AJAX) -->
<div class="modal fade" id="modalEdit" tabindex="-1" role="dialog" data-backdrop="static" data-keyboard="false">
  <div class="modal-dialog" role="document">
    <div class="modal-content" id="modalEditContent">
      <div class="modal-header">
        <h4 class="modal-title">Edit Pembayaran Tunai</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body text-center">
        <p>Memuat...</p>
      </div>
    </div>
  </div>
</div>

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

<script>
$(document).ready(function() {
  var chartPembayaranInstance = null;

  // DataTables server-side
  if ($('#table-pembayaran').length) {
    var tableTunai = $('#table-pembayaran').DataTable({
      processing: true,
      serverSide: true,
      ajax: {
        url: 'pembayaran_tunai_ajax.php',
        type: 'POST',
        data: function(d) {
          d.tanggal_dari = $('#tanggal_dari_tunai').val();
          d.tanggal_sampai = $('#tanggal_sampai_tunai').val();
          d.shift = $('#filter_shift_tunai').val();
        },
        dataSrc: function(json) {
          $('#total-filter').text('Rp. ' + Math.round(json.total_nominal || 0).toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.') + ' ,-');
          if (json.chart_labels && json.chart_data) {
            if (chartPembayaranInstance) {
              chartPembayaranInstance.destroy();
              chartPembayaranInstance = null;
            }
            if (json.chart_labels.length > 0 && $('#chartPembayaran').length && typeof Chart !== 'undefined') {
              var ctx = document.getElementById('chartPembayaran').getContext('2d');
              chartPembayaranInstance = new Chart(ctx).Line({
                labels: json.chart_labels,
                datasets: [{
                  label: 'Total Pembayaran (Rp)',
                  fillColor: 'rgba(0, 166, 90, 0.2)',
                  strokeColor: 'rgba(0, 166, 90, 1)',
                  pointColor: 'rgba(0, 166, 90, 1)',
                  data: json.chart_data
                }]
              }, { responsive: true });
            } else if (chartPembayaranInstance) {
              chartPembayaranInstance.destroy();
              chartPembayaranInstance = null;
            }
          }
          return json.data;
        }
      },
      order: [[1, 'desc'], [2, 'asc']],
      pageLength: 25,
      lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "Semua"]],
      language: {
        processing: 'Memproses data...',
        search: 'Cari:',
        lengthMenu: 'Tampilkan _MENU_ data per halaman',
        info: 'Menampilkan _START_ sampai _END_ dari _TOTAL_ data',
        infoEmpty: 'Tidak ada data',
        infoFiltered: '(difilter dari _MAX_ total data)',
        zeroRecords: 'Tidak ada data yang cocok',
        paginate: { first: 'Pertama', last: 'Terakhir', next: 'Selanjutnya', previous: 'Sebelumnya' }
      },
      columnDefs: [
        { orderable: false, targets: [0, 5] },
        { className: 'text-center', targets: [0, 1, 2, 5] },
        { className: 'text-right', targets: [3] }
      ]
    });

    $('#btnFilterTunai').on('click', function() {
      tableTunai.draw();
    });
  }

  // Datepicker di modal Tambah
  $('#modalTambah').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 });
    }
    $(this).find('.input-rupiah').val('');
  });

  // Load modal Edit
  $(document).on('click', '.btn-edit-tunai', function() {
    var id = $(this).data('id');
    $('#modalEditContent').load('pembayaran_tunai_edit.php?id=' + id, function() {
      $('#modalEditContent .datepicker2').datepicker({ autoclose: true, format: 'dd/mm/yyyy', todayHighlight: true });
      $('#modalEditContent .input-rupiah').each(function() {
        var v = $(this).val().replace(/\D/g,'');
        if (v) $(this).val('Rp. ' + v.replace(/\B(?=(\d{3})+(?!\d))/g, '.'));
      });
    });
  });

  // Hapus dengan SweetAlert
  $(document).on('click', '.btn-hapus-tunai', function(e) {
    e.preventDefault();
    var id = $(this).data('id');
    Swal.fire({
      title: 'Yakin ingin menghapus?',
      text: 'Data pembayaran tunai ini akan dihapus.',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#d33',
      cancelButtonColor: '#3085d6',
      confirmButtonText: 'Ya, Hapus'
    }).then(function(result) {
      if (result.isConfirmed) window.location.href = 'pembayaran_tunai_hapus.php?id=' + id;
    });
  });

  // Grafik di-update dari response AJAX (dataSrc) - tidak perlu init di sini

  <?php if (isset($_SESSION['alert']) && isset($_SESSION['message'])) { 
    $msg = $_SESSION['message']; 
    $alert = $_SESSION['alert'];
    unset($_SESSION['alert'], $_SESSION['message']);
  ?>
  Swal.fire({
    icon: '<?php echo $alert === 'error' ? 'error' : ($alert === 'warning' ? 'warning' : 'success'); ?>',
    title: '<?php echo $alert === 'error' ? 'Gagal' : ($alert === 'warning' ? 'Peringatan' : 'Berhasil'); ?>',
    text: <?php echo json_encode($msg); ?>,
    confirmButtonColor: '#3085d6',
    timer: 2500,
    timerProgressBar: true
  });
  <?php } ?>
});
</script>
