<?php
session_start();

require './kalenderhijriah.php';
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8" />
<title>Laporan Rekap Saldo Tabungan</title>
<!-- Sertakan CSS dan JS sesuai kebutuhan -->
<link rel="stylesheet" href="calendar.css"/>
</head>
<body>

<!-- Content Header -->
<div class="content-header">
  <div class="container-fluid">
    <div class="row mb-1">
      <div class="col-sm-12">
        <!-- <h1 class="m-0 text-dark">Laporan Neraca []</h1> -->
      </div>
    </div>
  </div>
</div>

<!-- Main Content -->
<section class="content">
  <div class="container-fluid">
    <div class="row">
      <div class="col-12">
        <!-- Card -->
        <div class="card">
          <div class="card-header bg-info">
            <h3 class="card-title">Laporan Rekap Saldo Tabungan</h3>
            <div class="card-tools">
              <button type="button" class="btn btn-tool" data-card-widget="collapse" title="Collapse">
                <i class="fas fa-minus"></i>
              </button>
              <button type="button" class="btn btn-tool" data-card-widget="remove" title="Remove">
                <i class="fas fa-times"></i>
              </button>
            </div>
          </div>
          <div class="card-body">
            <?php
            include 'koneksi.php';

            // Mendapatkan session
            $username = $_SESSION['username'] ?? '';
            $kode = $_SESSION['kode'] ?? '';

            // Membuat filter WHERE berdasarkan input
            if (isset($_POST['p_rekening'])) {
                $id = trim($_POST['p_rekening']);
                $par1 = $_POST['par1'];
                $par2 = $_POST['par2'];
                $par1_sql = date('Y-m-d', strtotime($par1));
                $par2_sql = date('Y-m-d', strtotime($par2));
                if ($id !== '') {
                    // Lindungi dari SQL injection
                    $id_filter = mysqli_real_escape_string($koneksi, $id);
                    $where = "WHERE (a.rekening LIKE '%$id_filter%' OR b.nama LIKE '%$id_filter%') GROUP BY a.rekening";
                } else {
                    $where = "WHERE a.tgl <= '" . mysqli_real_escape_string($koneksi, $par2_sql) . "' GROUP BY a.rekening";
                }
            } else {
                $where = "WHERE 1=1";
            }
            ?>

            <!-- Form Pencarian -->
            <form role="form" id="quickForm" action="" method="post">
              <div class="row">
                <div class="col-sm-10">
                  <div class="form-group row align-items-center">
                    <label for="p_rekening" class="col-2 m-3">Cari Data</label>
                    <input type="text" name="p_rekening" id="p_rekening" class="form-control col-sm-2" placeholder="ketik Register/Nama/Alamat/No Register/Ayah" value="<?php echo isset($_POST['p_rekening']) ? htmlspecialchars($_POST['p_rekening']) : ''; ?>" />

                    <!-- Input tanggal pertama -->
                    <div id="datepicker1" class="ml-2">
                      <input id="par1" name="par1" type="hidden" class="form-control" style="width: 100px;" value="<?php echo isset($_POST['par1']) ? $_POST['par1'] : ''; ?>">
                      <!-- <img id="pick-button1" src="kalender.png" alt="Pick Date" style="cursor:pointer; width:24px; height:24px;" onclick="pickADate1();"/> -->
                      <div id="calendar-popup1" class="datepicker" style="display:none;"></div>
                    </div>

                    <!-- Input tanggal kedua -->
                    <div id="datepicker2" class="ml-2">
                      <input id="par2" name="par2" type="text" class="form-control" style="width: 100px;" value="<?php echo isset($_POST['par2']) ? $_POST['par2'] : ''; ?>">
                      <img id="pick-button2" src="kalender.png" alt="Pick Date" style="cursor:pointer; width:24px; height:24px;" onclick="pickADate2();"/>
                      <div id="calendar-popup2" class="datepicker"                      style="display:none;"></div>
                    </div>

                    <!-- Tombol submit -->
                    <div class="col">
                      <button type="submit" class="btn btn-info mt-3">
                        <i class="fas fa-search"></i> Cari
                      </button>
                    </div>

                    <!-- Tombol cetak PDF -->
                    <?php if (isset($_POST['par1'])): ?>
                      <div class="col-2 text-right mt-3">
                        <?php
                          $_SESSION['tabungan']['periode'] = $_POST['par2'];
                          $_SESSION['tabungan']['kantor'] = $_SESSION['kantor'] ?? '';
                        ?>
                        <a href="pdf/lap_rekap_saldotabunganpdf.php" target="_blank" class="btn btn-success">
                          <i class="fa fa-print"></i> PDF
                        </a>
                      </div>
                    <?php endif; ?>
                  </div>
                </div>
              </div>
            </form>

            <hr>

            <!-- Tabel hasil laporan -->
            <table class="table table-bordered table-hover w-100" style="width: 100%;">
              <thead>
                <tr class="text-center">
                  <th>No</th>
                  <th>Tgl</th>
                  <th>Rekening</th>
                  <th>Nama</th>
                  <th>Kls</th>
                  <th>Saldo</th>
                  <th>UserName</th>
                </tr>
              </thead>
              <tbody>
                <?php
                $queryp = "SELECT b.klsNow as kls, a.no_bukti, a.rekening, a.tgl, b.nama, SUM(kredit - debet) AS saldotab, a.username
                          FROM mutasitabungan a
                          LEFT JOIN registrasi b ON a.id = b.id
                          $where";

                $result = mysqli_query($koneksi, $queryp);
                $no = 0;
                $totalSaldo = 0;

                if ($result && mysqli_num_rows($result) > 0) {
                  while ($data = mysqli_fetch_assoc($result)) {
                    $tgl = $data['tgl'];
                    $kls = $data['kls'];
                    $rekening = $data['rekening'];
                    $nama = $data['nama'];
                    $saldotab = $data['saldotab'];
                    $user = $data['username'];

                    $totalSaldo += $saldotab;
                    $no++;
                ?>
                  <tr>
                    <td class="text-center"><?php echo $no; ?></td>
                    <td><?php echo date('d-m-Y', strtotime($tgl)); ?></td>
                    <td><?php echo htmlspecialchars($rekening); ?></td>
                    <td><?php echo htmlspecialchars($nama); ?></td>
                    <td><?php echo htmlspecialchars($kls); ?></td>
                    <td class="text-right"><?php echo number_format($saldotab, 0); ?></td>
                    <td><?php echo htmlspecialchars($user); ?></td>
                  </tr>
                <?php
                  }
                }
                ?>
              </tbody>
              <tfoot>
                <tr>
                  <td colspan="5" class="text-center"><b>Jumlah</b></td>
                  <td class="text-right"><b><?php echo number_format($totalSaldo, 0); ?></b></td>
                  <td></td>
                </tr>
              </tfoot>
            </table>
          </div> <!-- /.card-body -->
        </div> <!-- /.card -->
      </div> <!-- /.col -->
    </div> <!-- /.row -->
  </div> <!-- /.container-fluid -->
</section> <!-- /.content -->


<link rel="stylesheet" href="calendar.css"/>
<script type="text/javascript" src="hijri-date.js"></script>
<script type="text/javascript" src="calendar.js"></script>
<!-- https://zulns.github.io/libs/calendar-api-doc.html -->



<script type="text/javascript">
    var pickedTxt1 = document.getElementById('par1'),
        datepicker1 = new Calendar(true, 0, false, true);
    document.getElementById('datepicker1').appendChild(datepicker1.getElement());
    datepicker1.getElement().style.marginTop = '10px';
    
    datepicker1.callback = function() {
        var selectedDate = datepicker1.getDate();
        var day = selectedDate.getDate().toString().padStart(2, '0');
        var month = (selectedDate.getMonth() + 1).toString().padStart(2, '0');
        var year = selectedDate.getFullYear();
        pickedTxt1.value = day + '-' + month + '-' + year;
        pickedTxt1.selectionStart = 0;
        pickedTxt1.selectionEnd = pickedTxt1.value.length;
        pickedTxt1.focus();
        datepicker1.hide();
    };

    function pickADate1() {
        datepicker1.show();
        datepicker1.getElement().style.position = 'absolute'; // Pastikan posisi kalender tidak mengganggu layout
    }

    var pickedTxt2 = document.getElementById('par2'),
        datepicker2 = new Calendar(true, 0, false, true);
    document.getElementById('datepicker2').appendChild(datepicker2.getElement());
    datepicker2.getElement().style.marginTop = '10px';
    
    datepicker2.callback = function() {
        var selectedDate = datepicker2.getDate();
        var day = selectedDate.getDate().toString().padStart(2, '0');
        var month = (selectedDate.getMonth() + 1).toString().padStart(2, '0');
        var year = selectedDate.getFullYear();
        pickedTxt2.value = day + '-' + month + '-' + year;
        pickedTxt2.selectionStart = 0;
        pickedTxt2.selectionEnd = pickedTxt2.value.length;
        pickedTxt2.focus();
        datepicker2.hide();
    };

    function pickADate2() {
        datepicker2.show();
        datepicker2.getElement().style.position = 'absolute'; // Pastikan posisi kalender tidak mengganggu layout
    }
</script>
<style>
    /* Mengatur posisi datepicker agar tidak mempengaruhi layout lain */
    .datepicker {
        position: absolute; /* Mencegah pergeseran elemen lain */
        z-index: 1000; /* Agar kalender muncul di atas elemen lain */
    }
</style>
<script type="text/javascript">
function addClickOutsideListener(datepicker, popupId) {
        function onClick(event) {
            var popup = document.getElementById(popupId);
            if (popup && !popup.contains(event.target) && !datepicker.getElement().contains(event.target)) {
               
                datepicker.hide(); // Menyembunyikan kalender
                document.removeEventListener('click', onClick); // Menghapus event listener setelah digunakan
            }
        }
        
        // Menambahkan event listener untuk mendeteksi klik di luar kalender
        document.addEventListener('click', onClick);
    }
</script>