<?php
//session_start();
/*error_reporting(E_ALL);
ini_set('display_errors', 1);*/
error_reporting(E_ALL^(E_NOTICE|E_WARNING));
  ini_set('display_errors',1);
  error_reporting(0);
include 'koneksi.php';
require './kalenderhijriah.php';
?>

<!-- Content Header (Page 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><!-- /.col -->
    </div><!-- /.row -->
  </div><!-- /.container-fluid -->
</div>
<!-- /.content-header -->

<!-- Main content -->
    <section class="content">
      <div class="container-fluid">
        <div class="row">
          <div class="col-12">
            <!-- Default box -->
            <div class="card">
              <div class="card-header bg-info">
                <h3 class="card-title ">Laporan Pembayaran <?php if(isset($_POST['dataTable'])){echo ucfirst($_POST['dataTable']); }?></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>

              <!-- /.card-header -->
        <div class="card-body">
          <?php

// Initialize the variables
$username = isset($_SESSION['username']) ? $_SESSION['username'] : '';
$kode = isset($_SESSION['kode']) ? $_SESSION['kode'] : '';
$dataTable = ''; // Initialize to avoid undefined variable
$statusBayar = '';
$par1 = '';
$par2 = '';
$where = " WHERE 1=1 ";          
          
$username = $_SESSION['username'];
$kode = $_SESSION['kode'];



if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['dataTable'])) {
  $dataTable = $_POST['dataTable'];
  $statusBayar = $_POST['statusBayar'];
  $par1 = mysqli_real_escape_string($koneksi, date('Y-m-d',strtotime($_POST['par1'])));
  $par2 = mysqli_real_escape_string($koneksi, date('Y-m-d',strtotime($_POST['par2'])));

  if ($statusBayar == "lunas") {
  $where .= " AND year(a.tglmasehi) >= '$par1' AND year(a.tglmasehi)<='$par2'      GROUP BY a.id,month(a.tglmasehi),year(a.tglmasehi),
               HAVING SUM(a.bayar) >= SUM(a.kewajiban)  "; // Use SUM to ensure total payments equal obligations
} else if ($statusBayar == "bayar") {
   $where .= " AND year(a.tglmasehi) >= '$par1' AND year(a.tglmasehi)<='$par2'    GROUP BY a.id,month(a.tglmasehi),year(a.tglmasehi)
               HAVING SUM(a.bayar) > 0 AND SUM(a.bayar) < SUM(a.kewajiban)"; // Payments are less than obligations
} else {
  $where .= " AND year(a.tglmasehi) >= '$par1' AND year(a.tglmasehi)<='$par2'  GROUP BY a.id ,month(a.tglmasehi),year(a.tglmasehi) 
               HAVING SUM(a.bayar) = 0"; // No payments made
}
  
} else {
  $where .= " AND 1=0 "; // No results if no criteria are set
}
?>
          <form role="form" id="quickForm" action="home.php?home=<?php echo md5("lapbayar_syahriah");?>" method="POST">
             <div class="row">
              <div class="col-sm-10">
            <div class="form-group row">
              <!-- <label for="nama" class="col-2 m-3">Cari Data</label>
              <input type="text" name="ba_rekening" id="ba_rekening"  class="form-control col-sm-2" placeholder="No Rekening"> -->
              
               <select class="form-control col-md-1 col-sm-1 col-xs-1" name="dataTable" id="dataTable">                          
              <option value="bulanan">Syahriah</option>
              <option value="iktibar">Ikhtibar</option>
              <option value="kitab">Kitab</option>
              <option value="imda1">Imda-I</option> 
              <option value="imda2">Imda-II</option> 
              <option value="imda3">Imda-III</option>                    
              </select>
              <select class="form-control col-md-1 col-sm-1 col-xs-1" name="statusBayar" id="statusBayar">                          
              <option value="lunas">Lunas</option>
              <option value="bayar">Bayar</option>
              <option value="tidak">Tidak Bayar</option>                  
              </select>
                              <!-- Input tanggal pertama -->
                <div id="datepicker1" class="ml-2 " >
                    <input id="par1" name="par1" type="text" class="form-control d-inline-block" style="width: 100px; display: inline;" value="<?php if(isset($_POST['par1'])){ echo $_POST['par1']; }else{ echo sprintf('%02d', $hijri[1]) . '-' . $calendar->monthName($hijri[0]) . '-' . $hijri[2];} ?>"  />
                    <img id="pick-button1" src="kalender.png" alt="Pick Date" style="cursor: pointer; width: 24px; height: 24px;" onclick="pickADate1();" class="d-inline-block"/>
                    <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 d-inline-block" style="width: 100px; display: inline;"  value="<?php if(isset($_POST['par2'])){ echo $_POST['par2']; }else{ echo sprintf('%02d', $hijri[1]) . '-' . $calendar->monthName($hijri[0]) . '-' . $hijri[2];} ?>" />
                    <img id="pick-button2" src="kalender.png" alt="Pick Date" style="cursor: pointer; width: 24px; height: 24px;" onclick="pickADate2();" class="d-inline-block"/>
                    <div id="calendar-popup2" class="datepicker" style="display:none;"></div>
                </div>
            
                <div class="col">
                    <button type="submit" class="btn btn-info">
                        <i class="fas fa-search"></i>
                    </button>
                </div>
                          <?php if(isset($_POST['par1'])){?>
                  <div class="form-group col-2">
                <?php
               $_SESSION['bayar_kewajiban']['periode'] =date('d-m-Y',strtotime($_POST['par1'])). " S/d ". date('d-m-Y',strtotime($_POST['par2']));
                $_SESSION['bayar_kewajiban']['namaKewajiban'] = $dataTable; 
                
                ?>
                <a href="pdf/lap_bayar_kewajiban_muridpdf.php" target="_blank" style="float: right;margin-top: 10px;" class="btn btn-success"><i class="fa fa-print"></i>PDF</a>

              <?php } ?>
               </div>
            </div>    
          </form>                   
          <hr>

          <!-- <table class="table table-bordered table-hover" width="148%"> -->
            <table id="sortTable" width="100%" class="table table-bordered table-hover">
            <thead>
              <tr align="center">
                <th >No</th>
                <th >ID</th>
                <th style="width: 10px;">NIM</th>
                <th style="width: 10px;">Tgl</th>
               <th >Nama</th>           
                <th >Kewajiban</th>
                <th >Bayar</th>
                <th >Sisa</th>
                <th >Kls</th>
                <th >Keterangan</th>
                <th >UserName</th>
              </tr>
            </thead>
            <tbody>
              <?php
              include 'koneksi.php';
               if (!empty($dataTable)) { // Check if $dataTable is not empty
                $queryba = "SELECT a.id AS id, a.nim AS nim, b.nama AS nama, a.tglmasehi AS tglmasehi, 
                MONTH(a.tglmasehi) AS month1, YEAR(a.tglmasehi) AS year1, a.no_kls AS no_kls, 
                SUM(a.kewajiban) AS kewajiban, SUM(a.bayar) AS bayar, 
                SUM(a.bayar - a.kewajiban) AS sisa, a.keterangan AS keterangan, a.username AS username
                FROM $dataTable a 
                LEFT JOIN registrasi b ON a.id = b.id 
                $where";
            $querya = mysqli_query($koneksi, $queryba);
            $_SESSION['bayar_kewajiban']['kode']['sqlbyr']=$queryba;

            if ($querya) {
                $t_kwajiban = 0;
                $t_bayar = 0;
                $t_sisa = 0;
                $no = 0;

                if (mysqli_num_rows($querya) > 0) {
                    while ($barisD = mysqli_fetch_assoc($querya)) {
                        $t_kwajiban += $barisD['kewajiban'];
                        $t_bayar += $barisD['bayar'];
                        $t_sisa += $barisD['sisa'];
                        $no++;
                        ?>
                        <tr>
                            <td align="center"><?php echo $no; ?></td>
                            <!-- <td><A?php echo date('d-m-Y', strtotime($barisD['tglmasehi'])); ?></td> -->
                            <td><?php echo $barisD['id']; ?></td>
                            <td style="width: 10px;"><?php echo $barisD['nim']; ?></td>
                            <td style="width: 10px;"><?php echo date('d-m-Y',strtotime($barisD['tglmasehi'])); ?></td>
                            <td style="width: 10px;"><?php echo $barisD['nama']; ?></td>
                            <td align="right"><?php echo number_format($barisD['kewajiban'], 0); ?></td>
                            <td align="right"><?php echo number_format($barisD['bayar'], 0); ?></td>
                            <td align="right"><?php echo number_format($barisD['sisa'], 0); ?></td>
                            <td><?php echo $barisD['no_kls']; ?></td>
                            <td><?php echo $barisD['keterangan']; ?></td>
                            <td><?php echo $barisD['username']; ?></td>
                        </tr>
                        <?php
                    }
                } else {
                    echo "<tr><td colspan='9' align='center'>No records found.</td></tr>";
                }
            } else {
                echo "<tr><td colspan='9' align='center'>Error executing query: " . mysqli_error($koneksi) . "</td></tr>";
            }
        } else {
            echo "<tr><td colspan='9' align='center'>Error: No table selected.</td></tr>";
        }
        ?>
      </tbody>
                  
              <tr>
                  <td colspan="5" ><b>Total</b></td>
                  <td><b><?php echo number_format($t_kwajiban,0); ?></b></td>
                  <td><b><?php echo number_format($t_bayar,0); ?></b></td>
                  <td><b><?php echo number_format($t_sisa,0); ?></b></td>
                  <td></td><td></td>
                </tr> 
              </table>
<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>

               
             <script type="text/javascript" charset="utf8" src="./assets/jquery.dataTables.js"></script>
              
              <link rel="stylesheet" type="text/css" href="./assets/jquery.dataTables.css">
                  <script>
              $('#sortTable').DataTable(); //https://www.sahretech.com/2020/04/cara-membuat-pencarian-sorting-dan.html?m=1/ cara buat sorter table
              </script>
            </div>
            <!-- /.card-body -->
          </div>
          <!-- /.card -->
        </div>
        <!-- /.col -->
      </div>

      <!-- /.row -->
    </section>
    <!-- /.content -->


