<?php
error_reporting(0);

include "../config/koneksi.php";
include "../config/library.php";
include '../config/user_agent.php';
include '../config/variabel_default.php';
$idt = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM identitas LIMIT 1"));
$link_send = $idt['link_one_sender'];
$token_send = $idt['token'];
//url tagihan
$page_URL = (@$_SERVER['HTTPS'] == 'on') ? "https://" : "http://";
$uri_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri_segments = explode('/', $uri_path);
//tahun ajaran
$t = mysql_query("SELECT idTahunAjaran as ta FROM tahun_ajaran WHERE aktif = 'Y'");
$ta = mysql_fetch_array($t);
$thn_ajar = $ta['ta'];
$headers = array();
$headers[] = $token_send;
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
?>
<?php if ($_GET['act'] == 'data') : ?>

  <div class="table-responsive">
    <form method="POST" onsubmit="return add_bayar_bulanan('<?= $_GET[id] ?>')" id="frm-tambah<?= $_GET[id] ?>">
      <table class="table table-bordered" style="white-space: nowrap; font-size: 10pt">
        <tr class="info">
          <th>No</th>
          <th>Tanggal</th>
          <th>Jumlah Bayar</th>
          <th>Nama Dispensasi</th>
          <th>Jumlah Dispensasi</th>
          <th>Cara Bayar</th>
          <th>Keterangan</th>
          <th>Aksi</th>
        </tr>
        <?php
        $no = 1;
        $total_bayar = 0;
        $totalTagihanBulanan = mysqli_fetch_array(mysqli_query($conn, "SELECT statusBayar, jumlahBayar as totalTagihan FROM tagihan_bulanan WHERE idTagihanBulanan='$_GET[id]'"));
        $qDetailBulananBayar = mysqli_query($conn, "SELECT * FROM tagihan_bulanan_bayar WHERE idTagihanBulanan='$_GET[id]' ORDER BY tglBayar ASC");
        if (mysqli_num_rows($qDetailBulananBayar) == 0) {
          echo '<tr>
                      <td colspan="7" align="center">Data masih kosong</td>
                    </tr>';
          $total_bayar = 0;
        } else {
          while ($detBulananBayar = mysqli_fetch_array($qDetailBulananBayar)) {
            echo '<tr>
                        <td>' . $no++ . '</td>
                        <td>' . date('m/d/Y', strtotime($detBulananBayar['tglBayar'])) . '</td>
                        <td>' . buatRp($detBulananBayar['diBayar']) . '</td>
                        <td>' . $detBulananBayar['namaDispensasi'] . '</td>
                        <td>' . buatRp($detBulananBayar['dispensasiBayar']) . '</td>
                        <td>' . $detBulananBayar['caraBayar'] . '</td>
                        <td>' . $detBulananBayar['ketBayar'] . '</td>
                        <td>
                          <button class="btn btn-danger btn-xs" onclick="return del_bayar_bulanan(\'' . $detBulananBayar['idBayar'] . '\',\'' . $_GET['id'] . '\')"><span class="glyphicon glyphicon-trash"></span></button>
                          <!--<a class="btn btn-success btn-xs" target="_blank" title="Cetak Pembayaran" href=""><span class="fa fa-print"></span></a>
                        --></td>
                      </tr>';
            $total_bayar = $total_bayar + $detBulananBayar['diBayar'] + $detBulananBayar['dispensasiBayar'];
          }
        }

        $tunggakan = $totalTagihanBulanan['totalTagihan'] - $total_bayar;
        ?>
        <tr>
          <td colspan="3">Total Sudah Bayar</td>
          <td><?= buatRp($total_bayar) ?></td>
          <td></td>
          <td colspan="3">Tunggakan : <?= buatRp($tunggakan) ?></td>
        </tr>
        <tr class="warning">
          <td colspan="8"><b>Tambah Pembayaran</b></td>
        </tr>
        <tr>
          <td colspan="2">Tanggal Bayar</td>
          <td>Jumlah Bayar</td>
          <td>Nama Dispensasi</td>
          <td>Jumlah Dispensasi</td>
          <td>Cara Bayar</td>
          <td>Keterangan</td>
          <td></td>
        </tr>
        <tr>
          <input type="hidden" name="id" value="<?= $_GET[id] ?>">
          <td colspan="2">
            <div class="input-group date date-picker" data-date="" id="tanggal" data-date-format="yyyy-mm-dd">
              <span class="input-group-addon">
                <i class="glyphicon glyphicon-calendar"></i>
              </span>
              <input class="form-control" required="" data-target="#tanggal" type="text" name="tanggal_bayar" placeholder="Tanggal Bayar" value="<?= date('Y-m-d') ?>" readonly <?= $totalTagihanBulanan['statusBayar'] == '1' ? 'disabled' : '' ?>>
            </div>
          </td>
          <td>
            <input class="form-control" type="text" name="jumlah_bayar" required placeholder="Jumlah Bayar" value="<?= $tunggakan ?>" <?= $totalTagihanBulanan['statusBayar'] == '1' ? 'disabled' : '' ?>>
          </td>
          <td>
            <input type="text" name="namaDispensasi" class="form-control" placeholder="Nama Dispen" <?= $totalTagihanBulanan['statusBayar'] == '1' ? 'disabled' : '' ?>>
          </td>
          <td>
            <input type="text" name="dispensasiBayar" class="form-control" placeholder="Jumlah Dispen" value="0" <?= $totalTagihanBulanan['statusBayar'] == '1' ? 'disabled' : '' ?>>
          </td>
          <td>
            <select name="caraBayar" class="form-control" required <?= $totalTagihanBulanan['statusBayar'] == '1' ? 'disabled' : '' ?>>
              <option value="Tunai">Tunai</option>
              <option value="Transfer">Transfer</option>
            </select>
          </td>
          <td>
            <select class="form-control" name="ketBayar" required <?= $totalTagihanBulanan['statusBayar'] == '1' ? 'disabled' : '' ?>>
              <option value="Lunas">Lunas</option>
              <option value="Angsuran 1">Angsuran 1</option>
              <option value="Angsuran 2">Angsuran 2</option>
              <option value="Angsuran 3">Angsuran 3</option>
              <option value="Angsuran 4">Angsuran 4</option>
              <option value="Angsuran 5">Angsuran 5</option>
            </select>
          </td>
          <td>
            <input type="submit" class="btn btn-danger" value="Bayar" <?= $totalTagihanBulanan['statusBayar'] == '1' ? 'disabled' : '' ?>>
          </td>
        </tr>
      </table>
    </form>
  </div>

<?php elseif ($_GET['act'] == 'tambah') : ?>

  <?php
  $query = mysqli_query($conn, "INSERT INTO tagihan_bulanan_bayar(idTagihanBulanan,tglBayar,diBayar,namaDispensasi,dispensasiBayar,caraBayar,ketBayar)
                        VALUES ('$_POST[id]','$_POST[tanggal_bayar]','$_POST[jumlah_bayar]','$_POST[namaDispensasi]','$_POST[dispensasiBayar]','$_POST[caraBayar]','$_POST[ketBayar]')");

  $cek_totalBayar = mysqli_fetch_array(mysqli_query($conn, "SELECT SUM(diBayar) as totalBayar, SUM(dispensasiBayar) as totalDispensasiBayar FROM tagihan_bulanan_bayar WHERE idTagihanBulanan='$_POST[id]'"));
  $cek_totalTagihan = mysqli_fetch_array(mysqli_query($conn, "SELECT jumlahBayar as totalTagihan FROM tagihan_bulanan WHERE idTagihanBulanan='$_POST[id]'"));

  $totalBayar = $cek_totalBayar['totalBayar'] + $cek_totalBayar['totalDispensasiBayar'];

  if ($totalBayar == $cek_totalTagihan['totalTagihan']) {
    $sttsBayar = '1';
  } elseif ($totalBayar < $cek_totalTagihan['totalTagihan']) {
    $sttsBayar = '2';
  } else {
    $sttsBayar = '0';
  }

  $query1 = mysqli_query($conn, "UPDATE tagihan_bulanan SET statusBayar='$sttsBayar' WHERE idTagihanBulanan='$_POST[id]'");

  $a = mysql_query("SELECT nmBulan as Bulan,tagihan_bulanan.idSiswa as ids, nmSiswa as nama, noHpOrtu as hpo, jumlahBayar as tagihan FROM siswa 
    INNER JOIN tagihan_bulanan ON siswa.idSiswa = tagihan_bulanan.idSiswa 
    INNER JOIN bulan ON tagihan_bulanan.idBulan = bulan.idBulan         
    WHERE idTagihanBulanan='$_POST[id]'         
              ");
  $re = mysql_fetch_array($a);
  $sis = $re['ids'];
  $tagihan = $re['tagihan'];
  $siswa = $re['nama'];
  $hpo = $re['hpo'];
  $bulan = $re['Bulan'];
  $msg_par = 'Assalamualaikum, Terima Kasih pembayaran Tagihan bulanan untuk bulan ' . $bulan . ' sebesar *Rp.' . rupiah($tagihan) . '* anak anda yang bernama *' . $siswa . '*, *Lunas* Terima kasih%0A%0ADownload kwitansi : ' . $link_url_tagihan . '';

  $phone = $hpo;

  $apikey = $token_send;
  $tujuan = $hpo;
  $pesan = $msg_par;
  $curl = curl_init();
  curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://starsender.online/api/sendText?message=' . rawurlencode($pesan) . '&tujuan=' . rawurlencode($tujuan . '@s.whatsapp.net'),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_HTTPHEADER => array(
      'apikey: ' . $apikey
    ),
  ));
  $response = curl_exec($curl);
  curl_close($curl);
  ?>

<?php elseif ($_GET['act'] == 'hapus') : ?>

  <?php
  $query = mysqli_query($conn, "DELETE FROM tagihan_bulanan_bayar WHERE idBayar='$_POST[idBayar]'");

  $cek_totalBayar = mysqli_fetch_array(mysqli_query($conn, "SELECT SUM(diBayar) as totalBayar, SUM(dispensasiBayar) as totalDispensasiBayar FROM tagihan_bulanan_bayar WHERE idTagihanBulanan='$_POST[idTagihan]'"));
  $cek_totalTagihan = mysqli_fetch_array(mysqli_query($conn, "SELECT jumlahBayar as totalTagihan FROM tagihan_bulanan WHERE idTagihanBulanan='$_POST[idTagihan]'"));

  $totalBayar = $cek_totalBayar['totalBayar'] + $cek_totalBayar['totalDispensasiBayar'];

  if ($totalBayar == 0) {
    $sttsBayar = '0';
  } else {
    $sttsBayar = '2';
  }

  $query1 = mysqli_query($conn, "UPDATE tagihan_bulanan SET statusBayar='$sttsBayar' WHERE idTagihanBulanan='$_POST[idTagihan]'");
  ?>

<?php elseif ($_GET['act'] == 'list_bulanan_detail') : ?>

  <table class="table table-bordered table-striped">
    <thead>
      <tr>
        <th>No</th>
        <th>Nama Bulan</th>
        <th>Status</th>
        <th>Tagihan</th>
        <th width="10%">Cetak</th>
        <th width="10%">Notifikasi Lunas</th>
        <th width="10%">Notifikasi Tagihan</th>
      </tr>
    </thead>
    <tbody>
      <?php
      $sqlTagihanBulanan = mysqli_query($conn, "SELECT
                tagihan_bulanan.idTagihanBulanan,
                tagihan_bulanan.idJenisBayar,
                tagihan_bulanan.idSiswa,
                tagihan_bulanan.idKelas,
                tagihan_bulanan.idBulan,
                tagihan_bulanan.jumlahBayar,
                tagihan_bulanan.statusBayar,
                jenis_bayar.idPosBayar,
                jenis_bayar.idTahunAjaran,
                jenis_bayar.nmJenisBayar,
                jenis_bayar.tipeBayar,
                siswa.nisSiswa,
                siswa.nisnSiswa,
                siswa.nmSiswa,
                siswa.jkSiswa,
                siswa.agamaSiswa,
                siswa.idKelas,
                siswa.statusSiswa,
                tahun_ajaran.nmTahunAjaran,
                kelas_siswa.nmKelas,
                bulan.nmBulan,
                bulan.urutan
              FROM
                tagihan_bulanan
              INNER JOIN jenis_bayar ON tagihan_bulanan.idJenisBayar = jenis_bayar.idJenisBayar
              INNER JOIN siswa ON tagihan_bulanan.idSiswa = siswa.idSiswa
              INNER JOIN tahun_ajaran ON jenis_bayar.idTahunAjaran = tahun_ajaran.idTahunAjaran
              INNER JOIN kelas_siswa ON tagihan_bulanan.idKelas = kelas_siswa.idKelas
              INNER JOIN bulan ON tagihan_bulanan.idBulan = bulan.idBulan
              INNER JOIN pos_bayar ON jenis_bayar.idPosBayar = pos_bayar.idPosBayar
              WHERE jenis_bayar.idJenisBayar='$_GET[jenis]' AND jenis_bayar.idTahunAjaran='$_GET[tahun]' AND siswa.idSiswa='$_GET[siswa]' ORDER BY bulan.urutan ASC");
      $no = 1;

      while ($rt = mysqli_fetch_array($sqlTagihanBulanan)) :
        $dts = mysqli_fetch_array(mysqli_query($conn, "SELECT sum(diBayar) as totalDibayar, sum(dispensasiBayar) as totalDispensasi FROM tagihan_bulanan_bayar WHERE idTagihanBulanan='$rt[idTagihanBulanan]'"));

        $tahun = '';
        $pisah_TA = explode('/', $rt['nmTahunAjaran']);
        if ($rt['urutan'] <= 6) {
          $tahun = $pisah_TA[0];
        } else {
          $tahun = $pisah_TA[1];
        }

        if ($rt['statusBayar'] == '1') {
          $btnDisabled = '';
          $btnTagihan = 'disabled';
          $textColor = 'success';
          $statusBayar = 'Lunas';
        } elseif ($rt['statusBayar'] == '2') {
          $btnDisabled = 'disabled';
          $btnTagihan = '';
          $textColor = 'warning';
          $statusBayar = 'Belum Lunas';
        } else {
          $btnDisabled = 'disabled';
          $btnTagihan = '';
          $textColor = 'danger';
          $statusBayar = 'Belum Bayar';
        }
      ?>
        <tr data-toggle="collapse" data-target="#demo1<?= $rt['idTagihanBulanan'] ?>" class="<?= $textColor ?>" style="cursor:pointer" onclick="show_detail_bulanan('<?= $rt[idTagihanBulanan] ?>')">
          <td><?= $no++ ?></td>
          <td><?= $rt['nmBulan'] . ' ' . $tahun ?></td>
          <td><?= $statusBayar ?></td>
          <td><?= buatRp($rt['jumlahBayar'] - ($dts['totalDibayar'] + $dts['totalDispensasi'])) ?></td>
          <td class="text-center">
            <a class="btn btn-success btn-xs <?= $btnDisabled ?>" target="_blank" title="Cetak Slip" href="./slip_bulanan_persiswa_perbulan.php?tagihan=<?= $rt[idTagihanBulanan] ?>&siswa=<?= $_GET[siswa] ?>"><span class="fa fa-print"></span> Cetak</a>
          </td>
          <td class="text-center">
            <a class="btn btn-info btn-xs <?= $btnDisabled ?>" title="Kirimkan Notifikasi Sms Lunas" href="?view=bayarbulanan&jenis=$_GET[jenis]&tahun=$_GET[tahun]&siswa=$_GET[siswa]&bln=$rt[nmBulan]&rp=$rt[jumlahBayar]&lunas"><span class="fa fa-comments-o"></span></a>
            <a class="btn btn-info btn-xs <?= $btnDisabled ?>" title="Kirimkan Notifikasi WhatsApp Lunas" href="https://api.whatsapp.com/send?phone=$dts[noHpOrtu]&text=Assalamualaikum, Terima Kasih pembayaran Tagihan bulanan untuk bulan $rt[nmBulan] sebesar  * . buatRp($rt[jumlahBayar]) . * anak anda yang bernama *$rt[nmSiswa]*, *Lunas* Terima kasih (Keuangan Smk Aswaja)." target="_blank"><span class="fa fa-commenting"></span></a>
          </td>
          <td class="text-center">
            <a class="btn btn-info btn-xs <?= $btnTagihan ?>" title="Kirimkan Notifikasi Tagihan" href="https://api.whatsapp.com/send?phone=$dts[noHpOrtu]&text=Assalamualaikum, Harap menyelesaikan pembayaran Tagihan bulanan untuk bulan $rt[nmBulan] sebesar * . buatRp($rt[jumlahBayar]) . * anak anda yang bernama *$rt[nmSiswa]*, Terima kasih (Keuangan Smk Aswaja). " target="_blank"><span class="fa fa-commenting"></span> Kirim</a>
          </td>
        </tr>
        <tr id="demo1<?= $rt['idTagihanBulanan'] ?>" class="collapse">
          <td colspan="7">
            <div id="show-detail-bulanan<?= $rt['idTagihanBulanan'] ?>"></div>
          </td>
        </tr>
      <?php endwhile; ?>
    </tbody>
  </table>

<?php endif ?>