<?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';

// Proses penyimpanan data ke tabel message
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['proses_data'])) {
    $selected_ids = $_POST['selected_data'] ?? [];
    $success_count = 0;
    $error_count = 0;
    
    foreach ($selected_ids as $data_string) {
        // Parse data yang dikirim dari checkbox
        $data_parts = explode('|', $data_string);
        if (count($data_parts) >= 7) {
            $nim = mysqli_real_escape_string($koneksi, $data_parts[0]);
            $nama = mysqli_real_escape_string($koneksi, $data_parts[1]);
            $kewajiban = mysqli_real_escape_string($koneksi, $data_parts[2]);
            $bayar = mysqli_real_escape_string($koneksi, $data_parts[3]);
            $bulan = mysqli_real_escape_string($koneksi, $data_parts[4]);
            $kls = mysqli_real_escape_string($koneksi, $data_parts[5]);
            $nohp = mysqli_real_escape_string($koneksi, $data_parts[6]);
            
            $sisaKewajiban = $kewajiban - $bayar;
            $tglmasehi2 = $tglmasehi2 = $hijri[2]. '-' . $calendar->monthName($hijri[0]). '-' . sprintf('%02d', $hijri[1]);
            $penErima = $nama;
            $kantor = $_SESSION['username'] ?? 'System';
            $keteranganpesan = "Tagihan Syahriah Bulan " . $bulan;
            $tagihan = "*TAGIHAN SYAHRIAH MMU A-39*";
            $metodebayar = "Tagihan";
            $bulanBayar = $bulan;            
            $waTagihan = mysqli_query($koneksi, "INSERT INTO message_tes SET 
                number='$nohp',
                tgl='$tglmasehi2',
                judul='$tagihan', 
                penErima='$penErima', 
                PenGirim='$kls', 
                rekening='$bulan',
                kewajiban='$kewajiban',
                sisaKewajiban='$bayar', 
                nominal='$sisaKewajiban', 
                keterangan='$keteranganpesan', 
                metodeBayar='$metodebayar',
                kodeFilTer='Syahriah'
            ");
            
            if ($waTagihan) {
                $success_count++;
            } else {
                $error_count++;
            }
        }
    }
    
    if ($success_count > 0) {
        echo "<script>alert('Data berhasil diproses: $success_count record');</script>";
    }
    if ($error_count > 0) {
        echo "<script>alert('Gagal memproses: $error_count record');</script>";
    }
}
?>

<!-- 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'];

            $dataTable = $_POST['dataTable'] ?? ''; 

            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'])));
              $bulaN = mysqli_real_escape_string($koneksi, date('m',strtotime($_POST['par2'])));
              $tahuN = mysqli_real_escape_string($koneksi, date('Y',strtotime($_POST['par2'])));
              $tglHitung = [
                "10" => 1,
                "11" => 2,
                "12" => 3,
                "01" => 4,
                "02" => 5,
                "03" => 6,
                "04" => 7,
                "05" => 8,
                "06" => 9,
                "07" => 10,
                "08" => 11,
                "09" => 12 // Menambahkan bulan September yang hilang
            ];

            $where = " WHERE 1=1 "; // Jadi bisa tambahkan kondisi dengan AND
            // Kalau Anda ingin kondisi berdasarkan statusBayar
                if ($statusBayar == "lunas") {
                    $where .= "AND DATE_FORMAT(a.tglmasehi, '%Y-%m') <= CONCAT('$tahuN', '-', '$bulaN') ";
                    $groupBy = " GROUP BY a.rekGabung, a.tahun ";
                    $having = " HAVING SUM(a.bayar) >= SUM(a.kewajiban) ";
                } elseif ($statusBayar == "bayar") {
                    $where .= " AND DATE_FORMAT(a.tglmasehi, '%Y-%m') <= CONCAT('$tahuN', '-', '$bulaN') ";
                    $groupBy = " GROUP BY a.rekGabung, a.tahun ";
                    $having = " HAVING SUM(a.bayar) > 0 AND SUM(a.bayar) < SUM(a.kewajiban) ";
                } else {
                    // Tidak bayar
                    $where .= " AND DATE_FORMAT(a.tglmasehi, '%Y-%m') <= CONCAT('$tahuN', '-', '$bulaN') ";
                    $groupBy = " GROUP BY a.rekGabung, a.tahun ";
                    $having = " HAVING SUM(a.bayar) = 0 ";
                }
            } else {
            $where .= " AND 1=0 "; // No results if no criteria are set
            }
            $sBayaR = [
              "lunas" => "Lunas",
              "bayar" => "Bayar",
              "tidak" => "Tidak Bayar"
            ];
            $BulanH = [
              "10" => "Syawal",
              "11" => "Dz. Qodah",
              "12" => "Dz Hijjah",
              "01" =>  "Muharram",
              "02"=>  "Shafar",
              "03" => "R. Awal",
              "04" => "R. Tsani",
              "05" => "J. Ula",
              "06" => "J. Tsani",
              "07" => "Rajab",
              "08" => "Sy`aban",
              "09" => "Ramadhan", // Menambahkan bulan September yang hilang
            ];
            ?>
            
            <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"> -->
                
                                         
                <input type="hidden" name="dataTable" id="dataTable" value="bulanan" >              
                <select class="form-control col-md-2 col-sm-2 col-xs-2" name="statusBayar" id="statusBayar">                          
                <option><?php if(isset($_POST['statusBayar'])){ echo $sBayaR[$_POST['statusBayar']]; }else{echo "PILIH---- ";}?></option>
                <option value="lunas">Lunas</option>
                <option value="bayar">Bayar</option>
                <option value="tidak">Tidak Bayar</option>                  
                </select>
                 <!-- 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['par2'])){?>
                    <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="exportexcell/bayar_syahriah_murid.php" target="_blank" style="float: right;margin-top: 10px;" class="btn btn-success"><i class="fas fa-arrow-alt-circle-down"></i></a> -->
                  <div style="position: absolute; right: 0; top: 0; display: flex; gap: 10px; align-items: center;">
                        <!-- Icon Excel -->
                        <a href="exportexcell/bayar_syahriah_murid.php" target="_blank" title="Download Excel">
                            <img src="img/excell.png" alt="Excel" style="width: 32px; height: 32px;">
                        </a>

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

            <!-- Form untuk proses data -->
            <form method="POST" id="prosesForm">
                <div class="row mb-3">
                    <div class="col-12">
                        <button type="button" id="selectAll" class="btn btn-sm btn-secondary">Pilih Semua</button>
                        <button type="button" id="deselectAll" class="btn btn-sm btn-secondary">Batal Pilih</button>
                        <button type="submit" name="proses_data" class="btn btn-sm btn-success" id="prosesBtn" disabled>
                            <i class="fas fa-paper-plane"></i> Proses Data
                        </button>
                        <span id="selectedCount" class="badge badge-info ml-2">0 dipilih</span>
                    </div>
                </div>

                <!-- <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 style="width: 30px;">
                        <input type="checkbox" id="masterCheck">
                    </th>
                    <th >No</th>
                    <th >ID</th>
                    <th style="width: 10px;">NIM</th>
                    <th style="width: 10px;">Tahun</th>
                    <th style="width: 10px;">Bln</th>
                   <th >Nama</th>           
                    <th >Kewajiban</th>
                    <th >Bayar</th>
                    <th >Sisa</th>
                    <th >Kls</th>
                    <th >Keterangan</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, a.tahun,a.bulan,
                    sum(a.kewajiban) AS kewajiban, SUM(a.bayar) AS bayar, sum(a.kewajiban-a.bayar) AS sisa, a.keterangan AS keterangan, a.username AS username,
                    b.nohp AS nohp
                    FROM $dataTable a 
                    LEFT JOIN registrasi b ON a.id = b.id 
                     $where $groupBy $having";
                $querya = mysqli_query($koneksi, $queryba);
                $_SESSION['bayar_syahriah']['kode']['sqlbyr']=$queryba;

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

                    if (mysqli_num_rows($querya) > 0) {
                        while ($barisD = mysqli_fetch_assoc($querya)) {
                            $kewajiban = $barisD['kewajiban'];
                            $bayar = $barisD['bayar'];
                            $sisa = $bayar-$kewajiban;
                            $t_kewajiban += $barisD['kewajiban'];
                            $t_bayar += $barisD['bayar'];
                            $t_sisa = $t_bayar-$t_kewajiban;
                            $no++;
                            
                            // Data untuk checkbox - format: nim|nama|kewajiban|bayar|bulan|kls|nohp
                            $checkbox_data = $barisD['nim'] . '|' . $barisD['nama'] . '|' . $barisD['kewajiban'] . '|' . $barisD['bayar'] . '|' . $BulanH[$barisD['bulan']] . '|' . $barisD['no_kls'] . '|' . ($barisD['nohp'] ?? '');
                            ?>
                            <tr>
                                <td align="center">
                                    <input type="checkbox" name="selected_data[]" value="<?php echo htmlspecialchars($checkbox_data); ?>" class="row-checkbox">
                                </td>
                                <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 $barisD['tahun']; ?></td>
                                <td style="width: 10px;"><?php echo $BulanH[$barisD['bulan']]; ?></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($sisa, 0); ?></td>
                                <td><?php echo $barisD['no_kls']; ?></td>
                                <td><?php echo $barisD['keterangan']; ?></td>
                               
                            </tr>
                            <?php
                        }
                    } else {
                        echo "<tr><td colspan='12' align='center'>No records found.</td></tr>";
                    }
                } else {
                    echo "<tr><td colspan='12' align='center'>Error executing query: " . mysqli_error($koneksi) . "</td></tr>";
                }
            } else {
                echo "<tr><td colspan='12' align='center'>Error: No table selected.</td></tr>";
            }
            ?>
          </tbody>
                      
                  <tr>
                      <td colspan="6" ><b>Total</b></td>
                      <td><b><?php echo number_format($t_kewajiban,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><td></td>
                    </tr> 
                  </table>
            </form>

                   
                 <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 -->

        <link rel="stylesheet" href="calendar.css" />
    <script type="text/javascript" src="hijri-date.js"></script>
    <script type="text/javascript" src="calendar.js"></script>

    <script type="text/javascript">
        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';
        }
    </script>

    <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();
                    document.removeEventListener('click', onClick);
                }
            }
            document.addEventListener('click', onClick);
        }

    // JavaScript untuk mengelola checkbox dan tombol proses
    $(document).ready(function() {
        // Master checkbox
        $('#masterCheck').on('change', function() {
            $('.row-checkbox').prop('checked', this.checked);
            updateSelectedCount();
        });

        // Individual checkbox
        $('.row-checkbox').on('change', function() {
            updateSelectedCount();
            
            // Update master checkbox
            var totalCheckboxes = $('.row-checkbox').length;
            var checkedCheckboxes = $('.row-checkbox:checked').length;
            
            if (checkedCheckboxes === 0) {
                $('#masterCheck').prop('indeterminate', false);
                $('#masterCheck').prop('checked', false);
            } else if (checkedCheckboxes === totalCheckboxes) {
                $('#masterCheck').prop('indeterminate', false);
                $('#masterCheck').prop('checked', true);
            } else {
                $('#masterCheck').prop('indeterminate', true);
            }
        });

        // Tombol pilih semua
        $('#selectAll').on('click', function() {
            $('.row-checkbox').prop('checked', true);
            $('#masterCheck').prop('checked', true);
            updateSelectedCount();
        });

        // Tombol batal pilih
        $('#deselectAll').on('click', function() {
            $('.row-checkbox').prop('checked', false);
            $('#masterCheck').prop('checked', false);
            updateSelectedCount();
        });

        // Update jumlah item yang dipilih
        function updateSelectedCount() {
            var count = $('.row-checkbox:checked').length;
            $('#selectedCount').text(count + ' dipilih');
            
            // Enable/disable tombol proses
            if (count > 0) {
                $('#prosesBtn').prop('disabled', false);
            } else {
                $('#prosesBtn').prop('disabled', true);
            }
        }

        // Konfirmasi sebelum memproses
        $('#prosesForm').on('submit', function(e) {
            var count = $('.row-checkbox:checked').length;
            if (count === 0) {
                e.preventDefault();
                alert('Pilih minimal satu data untuk diproses!');
                return false;
            }
            
            if (!confirm('Apakah Anda yakin ingin memproses ' + count + ' data yang dipilih?')) {
                e.preventDefault();
                return false;
            }
        });

        // Initial count update
        updateSelectedCount();
    });
    </script>

    <style>
        .datepicker {
            position: absolute;
            z-index: 1000;
        }
        
        .row-checkbox {
            cursor: pointer;
        }
        
        #selectedCount {
            font-size: 12px;
        }
        
        #prosesBtn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
    </style>