<?php
// Uncomment for error reporting if needed
error_reporting(E_ALL^(E_NOTICE|E_WARNING));
error_reporting(0);
//ini_set('display_errors', 1); 
require './kalenderhijriah.php';

?>

<!-- Content Header (Page header) -->
<div class="content-header">
  <div class="container-fluid">
    <div class="row mb-2">
      <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">
        <div class="card">
          <div class="card-header bg-info">
            <h3 class="card-title">Laporan Posisi Keuangan</h3>
          </div>
          <div class="card-body">
            <?php
          
            $kode = $_SESSION['kode'];
            $par1 = isset($_POST['par1']) ? date('Y-m-d',strtotime($_POST['par1'])) : "";
            $par2 = isset($_POST['par2']) ? date('Y-m-d',strtotime($_POST['par2'])) : "";
            ?>
            <form action="home.php?home=<?php echo md5("neraca"); ?>" method="post">
              <div class="form-group row">
                 <!-- 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>

                  <input type="submit" name="proses" class="btn btn-info" style="float: right;" value="Preview">
                
              </div>
            </form>

            <hr>

            <?php if (!empty($par1)) { ?>    

            <h5 style="font-weight: bold;">AKTIVA</h5>
            <table class="table table-sm">
              <tr>
                <th>Kode</th>
                <th>Akun</th>
                <th style="text-align: center;"><?php echo date('d-m-Y', strtotime('-1 days', strtotime($par1))); ?></th>
                <th style="text-align: center;">Mutasi</th>
                <th style="text-align: center;"><?php echo date('d-m-Y', strtotime($par2)); ?></th>
              </tr>

              <?php
              $accountGroups = [
                  ['range' => "1.10", 'label' => "Aktiva Lancar"],
                  ['range' => "1.11", 'label' => "Penyertaan"],
                  ['range' => "1.12", 'label' => "Piutang Gadai"],
                  // Menggabungkan tiga akun menjadi satu kelompok dengan range yang sama
                  ['range' => "1.14,1.15,1.16,1.17,1.180,1.190", 'label' => "Aktiva Tetap"], // Combine into one group
              ];

              $totalSaldoAwal = 0;
              $totalMutasi = 0;
              $totalSaldoAkhir = 0;

              foreach ($accountGroups as $group) {
                  $ranges = explode(',', $group['range']);
                  $likeConditions = [];

                  foreach ($ranges as $range) {
                      $likeConditions[] = "kode_akun LIKE '{$range}%'";
                  }
                  $likeSQL = implode(' OR ', $likeConditions);

$query = "SELECT 
      bukubesar.kode_akun, 
      kode_akun.n_akun AS nama_akun, 
      saldo.saldoAwal, 
      SUM(bukubesar.debet - bukubesar.kredit) AS saldoAkhir,
      SUM(bukubesar.debet - bukubesar.kredit) - saldo.saldoAwal AS mutasi 
    FROM 
      bukubesar 
    LEFT JOIN (
      SELECT 
        kode_akun AS kode2, 
        SUM(debet - kredit) AS saldoAwal 
      FROM 
        bukubesar 
      WHERE kode ='$kode' AND
        tanggal < '$par1' AND ($likeSQL) 
      GROUP BY 
        kode_akun
    ) AS saldo ON bukubesar.kode_akun = saldo.kode2 
    LEFT JOIN kode_akun ON bukubesar.kode_akun = kode_akun.k_akun
    WHERE bukubesar.kode ='$kode' AND
      bukubesar.tanggal <= '$par2' AND ($likeSQL) 
    GROUP BY 
      bukubesar.kode_akun 
    HAVING 
      saldoAkhir <> 0";
                  $_SESSION['neracagab']['sql1'] = $query;

                  $result = $mysqli->query($query);
                  $tsaldoAwal = $tmutasi = $tsaldoAkhir = 0;

                  if ($result && $result->num_rows > 0) {
                      echo "<tr><th colspan='4'>{$group['label']}</th></tr>";

                      while ($data = $result->fetch_assoc()) {
                          $tsaldoAwal += $data['saldoAwal'];
                          $tmutasi += $data['mutasi'];
                          $tsaldoAkhir += $data['saldoAkhir'];
                          ?>
                          <tr>
                              <td width="10%"><?php echo $data['kode_akun']; ?></td>
                              <td><?php echo $data['nama_akun']; ?></td>
                              <td width="15%" align="right"><?php echo number_format($data['saldoAwal'], 0); ?></td>
                              <td width="15%" align="right"><?php echo number_format($data['mutasi'], 0); ?></td>
                              <td width="15%" align="right"><?php echo number_format($data['saldoAkhir'], 0); ?></td>
                          </tr>
                          <?php
                      }
                      $totalSaldoAwal += $tsaldoAwal;
                      $totalMutasi += $tmutasi;
                      $totalSaldoAkhir += $tsaldoAkhir;
                      ?>
                      <tr>
                          <th colspan="2">Jumlah</th>
                          <th style="text-align: right;"><?= number_format($tsaldoAwal, 0) ?></th>
                          <th style="text-align: right;"><?= number_format($tmutasi, 0) ?></th>
                          <th style="text-align: right;"><?= number_format($tsaldoAkhir, 0) ?></th>
                      </tr>
                      <?php
                  }
              }
              if ($totalSaldoAwal > 0) { // Only show this if there are results
              ?>
              <tr>
                  <th colspan="2">Total Aktiva</th>
                  <th style="text-align: right;"><?= number_format($totalSaldoAwal, 0) ?></th>
                  <th style="text-align: right;"><?= number_format($totalMutasi, 0) ?></th>
                  <th style="text-align: right;"><?= number_format($totalSaldoAkhir, 0) ?></th>
              </tr>
              <?php } ?>
            </table>
            <br>
            <!-- End of Aktiva Section -->

            <!-- Laba Rugi -->
            <?php
              $tsaldoAwals = 0;
              $tmutasis = 0;
              $tsaldoAkhirs = 0;
$queryzs = "SELECT tanggal AS tanggal, 
    '3.320.60' AS kode_akun, 
    'LABA BERJALAN' AS nama_akun,
    saldo.saldoAwal AS saldoAwal,
    SUM(kredit - debet) - saldo.saldoAwal AS mutasi,
    SUM(kredit - debet) AS saldoAkhir 
FROM bukubesar 
LEFT JOIN (
SELECT kode_akun AS kode2, 
       SUM(kredit - debet) AS saldoAwal 
FROM bukubesar 
WHERE kode='$kode' AND tanggal < '$par1' AND kode_akun >= '4.400' 
GROUP BY kode_akun
) AS saldo ON bukubesar.kode_akun = saldo.kode2 
LEFT JOIN (SELECT n_akun, k_akun FROM kode_akun) AS kode_akun 
ON bukubesar.kode_akun = kode_akun.k_akun 
WHERE bukubesar.kode='$kode' AND bukubesar.tanggal <= '$par2' AND bukubesar.kode_akun >= '4.400'";
                           
              $_SESSION['neraca']['sqls'] = $queryzs;
              $resultz = $mysqli->query($queryzs);
              $num_resultz = $resultz->num_rows;

              if ($num_resultz > 0) {
                while ($datazs = mysqli_fetch_assoc($resultz)) {
                  $tsaldoAwals += $datazs['saldoAwal'];
                  $tmutasis += $datazs['mutasi'];
                  $tsaldoAkhirs += $datazs['saldoAkhir'];
                }
              }
              ?>
              <!-- Laba RUgi -->

            <h5 style="font-weight: bold;">PASIVA</h5>
            <table class="table table-sm">
              <tr>
                <th>Kode</th>
                <th>Akun</th>
                <th style="text-align: center;"><?php echo date('d-m-Y', strtotime('-1 days', strtotime($par1))); ?></th>
                <th style="text-align: center;">Mutasi</th>
                <th style="text-align: center;"><?php echo date('d-m-Y', strtotime($par2)); ?></th>
              </tr>

              <?php
              $accountGroups = [
                  ['range' => "2.2", 'label' => "Pasiva Lancar"],
                  ['range' => "2.310", 'label' => "Modal"],
                   ['range' => "2.320", 'label' => "Kenaikan Aset"],
              ];

              $totalsaldoAwal22 = 0;
              $totalmutasi2 = 0;
              $totalsaldoAkhir22 = 0;

              foreach ($accountGroups as $group) {
                  $query2 = "SELECT 
                              bukubesar.kode_akun, 
                              kode_akun.n_akun AS nama_akun, 
                              saldo.saldoAwal2, 
                              SUM(bukubesar.kredit - bukubesar.debet) AS saldoAkhir2,
                              SUM(bukubesar.kredit - bukubesar.debet) - saldo.saldoAwal2 AS mutasi2 
                            FROM 
                              bukubesar 
                            LEFT JOIN (
                              SELECT 
                                kode_akun AS kode2, 
                                SUM(kredit - debet) AS saldoAwal2 
                              FROM 
                                bukubesar 
                              WHERE kode = '$kode' AND
                                tanggal < '$par1' AND kode_akun LIKE '{$group['range']}%' 
                              GROUP BY kode_akun
                            ) AS saldo ON bukubesar.kode_akun = saldo.kode2 
                            LEFT JOIN kode_akun ON bukubesar.kode_akun = kode_akun.k_akun
                            WHERE bukubesar.kode = '$kode' AND
                              bukubesar.tanggal <= '$par2' AND bukubesar.kode_akun LIKE '{$group['range']}%' 
                            GROUP BY 
                              bukubesar.kode_akun 
                            HAVING 
                              saldoAkhir2 <> 0";
                  $_SESSION['neracagab']['sql2'] = $query2;

                  $result = $mysqli->query($query2);
                  $tsaldoAwal2 = $tmutasi2 = $tsaldoAkhir2 = 0;

                  if ($result && $result->num_rows > 0) {
                      echo "<tr><th colspan='4'>{$group['label']}</th></tr>";

                      while ($data = $result->fetch_assoc()) {
                          $tsaldoAwal2 += $data['saldoAwal2'];
                          $tmutasi2 += $data['mutasi2'];
                          $tsaldoAkhir2 += $data['saldoAkhir2'];
                          ?>
                          <tr>
                              <td width="10%"><?php echo $data['kode_akun']; ?></td>
                              <td><?php echo $data['nama_akun']; ?></td>
                              <td width="15%" align="right"><?php echo number_format($data['saldoAwal2'], 0); ?></td>
                              <td width="15%" align="right"><?php echo number_format($data['mutasi2'], 0); ?></td>
                              <td width="15%" align="right"><?php echo number_format($data['saldoAkhir2'], 0); ?></td>
                          </tr>
                          <?php
                      }
                      $totalsaldoAwal22 += $tsaldoAwal2;
                      $totalmutasi2 += $tmutasi2;
                      $totalsaldoAkhir22 += $tsaldoAkhir2;
                      ?>
                      <tr>
                          <th colspan="2">Jumlah</th>
                          <th style="text-align: right;"><?= number_format($tsaldoAwal2, 0) ?></th>
                          <th style="text-align: right;"><?= number_format($tmutasi2, 0) ?></th>
                          <th style="text-align: right;"><?= number_format($tsaldoAkhir2, 0) ?></th>
                      </tr>
                      <?php
                  }
              }
              ?>
              <tr>
                  <td >2.320.60</th>
                  <td >KENAIKAN  ASET BERSIH</td>
                  <td style="text-align: right;"><?= number_format($tsaldoAwals, 0) ?></td>
                  <td style="text-align: right;"><?= number_format($tmutasis, 0) ?></td>
                  <td style="text-align: right;"><?= number_format($tsaldoAkhirs, 0) ?></td>
              </tr>
              <?php
              if ($totalsaldoAwal22 > 0) { // Only show this if there are results
              ?>
              <tr>
                  <th colspan="2">Total Pasiva</th>
                  <th style="text-align: right;"><?= number_format($totalsaldoAwal22 + $tsaldoAwals, 0) ?></th>
                  <th style="text-align: right;"><?= number_format($totalmutasi2 + $tmutasis, 0) ?></th>
                  <th style="text-align: right;"><?= number_format($totalsaldoAkhir22 + $tsaldoAkhirs, 0) ?></th>
              </tr>
              <?php } ?>
            </table>
            <br>
            <?php } ?>

            <?php if(isset($_POST['par1'])){
                $_SESSION['neracagab']['periode1'] = date('Y-m-d',strtotime($_POST['par1']));
                $_SESSION['neracagab']['periode2'] = date('Y-m-d',strtotime($_POST['par2']));
            ?>
            <a href="pdf/lap_neraca_pdf.php" target="_blank" style="float: right; margin-top: 10px;" class="btn btn-success">
                <i class="fa fa-print"></i> PDF
            </a>
            <?php } ?>

          <div class="card-footer bg-info">
            SAK-EP
          </div>
          <!-- /.card -->
        </div>
      </div>
    </div>
  </div>
</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>


