<?php
session_start();
if (empty($connection)) {
  header('location:../../');
  exit;
} else {
  include_once 'mod/sw-panel.php';

  // ================== Helper Aman ==================
  if (!function_exists('h')) {
    function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
  }

  if (!function_exists('tgl_indo')) {
    function tgl_indo($tanggal){
      $bulan = [
        1=>'Januari','Februari','Maret','April','Mei','Juni',
        'Juli','Agustus','September','Oktober','November','Desember'
      ];
      $pecah = explode('-', $tanggal);
      return $pecah[2].' '.$bulan[(int)$pecah[1]].' '.$pecah[0];
    }
  }

  // ================== Validasi Bulan & Tahun ==================
  $allowed_months = ['01','02','03','04','05','06','07','08','09','10','11','12'];
  $thisYear = (int)date('Y');
  $minYear  = $thisYear - 5;
  $maxYear  = $thisYear + 4;

  echo '<div class="content-wrapper">';

  switch (@$_GET['op']) {

  // ================== LIST DATA IBADAH ==================
  default:

    $bulan = isset($_GET['bulan']) ? $_GET['bulan'] : date('m');
    $tahun = isset($_GET['tahun']) ? $_GET['tahun'] : date('Y');
    $cari  = isset($_GET['cari']) ? trim($_GET['cari']) : '';

    $bulan = in_array($bulan, $allowed_months) ? $bulan : date('m');
    $tahun = (int)$tahun;
    if ($tahun < $minYear || $tahun > $maxYear) $tahun = (int)date('Y');

    $cari_sql = $connection->real_escape_string($cari);

    echo '
    <section class="content-header">
      <h1>Data <small>Ibadah</small></h1>
      <ol class="breadcrumb">
        <li><a href="./"><i class="fa fa-dashboard"></i> Beranda</a></li>
        <li class="active">Data Ibadah</li>
      </ol>
    </section>

    <section class="content">
      <div class="row">
        <div class="col-xs-12">
          <div class="box box-solid">
            <div class="box-header with-border">
              <h3 class="box-title"><b>Data Ibadah</b></h3>
              <div class="box-tools pull-right">
                <div class="btn-group">
                  <button type="button" class="btn btn-success">Ekspor</button>
                  <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown">
                    <span class="caret"></span>
                  </button>
                  <ul class="dropdown-menu" role="menu">
                    <li><a href="mod/ibadah/print.php?action=pdf&from='.$bulan.'&to='.$tahun.'" target="_blank">PDF</a></li>
                    <li><a href="mod/ibadah/print.php?action=excel&from='.$bulan.'&to='.$tahun.'" target="_blank">EXCEL</a></li>
                    <li><a href="mod/ibadah/print.php?action=excel&from='.$bulan.'&to='.$tahun.'&print=1" target="_blank">PRINT</a></li>
                  </ul>
                </div>
              </div>
            </div>

            <div class="box-body">
              <form method="GET" class="form-inline mb-3">
                <div class="form-group">
                  <select name="bulan" class="form-control">';
                    $bulan_array = [
                      "01"=>"Januari","02"=>"Februari","03"=>"Maret","04"=>"April",
                      "05"=>"Mei","06"=>"Juni","07"=>"Juli","08"=>"Agustus",
                      "09"=>"September","10"=>"Oktober","11"=>"November","12"=>"Desember"
                    ];
                    foreach($bulan_array as $key=>$nama){
                      $sel = ($bulan==$key)?'selected':'';
                      echo "<option value='$key' $sel>$nama</option>";
                    }
    echo '       </select>
                </div>
                <div class="form-group">
                  <select name="tahun" class="form-control">';
                    for($i=$minYear; $i<=$maxYear; $i++){
                      $sel = ($tahun==$i)?'selected':'';
                      echo "<option value='$i' $sel>$i</option>";
                    }
    echo '       </select>
                </div>
                <div class="form-group">
                  <input type="text" name="cari" value="'.h($cari).'" class="form-control" placeholder="Cari nama">
                </div>
                <button type="submit" class="btn btn-primary"><i class="fa fa-search"></i> Tampilkan</button>
              </form>

              <div class="table-responsive">
                <table id="swdatatable" class="table table-bordered table-striped table-hover">
                  <thead>
                    <tr>
                      <th>No</th>
                      <th>Tanggal</th>
                      <th>Nama</th>
                      <th>Kebiasaan Baik</th>
                      <th>Shalat Wajib</th>
                      <th>Shalat Sunnah</th>
                      <th>Dzikir</th>
                      <th>Tilawah</th>
                      <th class="text-center">Aksi</th>
                    </tr>
                  </thead>
                  <tbody>';

                  $where = "WHERE MONTH(tanggal)=".(int)$bulan." AND YEAR(tanggal)=".(int)$tahun;
                  if ($cari !== '') {
                    $where .= " AND nama LIKE '%$cari_sql%'";
                  }

                  $query = "SELECT * FROM ibadah $where ORDER BY tanggal DESC";
                  $result = $connection->query($query);

                  if ($result && $result->num_rows > 0) {
                    $no=0;
                    while ($row = $result->fetch_assoc()) {
                      $no++;
                      $kebiasaan = implode(", ", json_decode($row['kebiasaan_baik'], true) ?: []);
                      $sunnah = implode(", ", json_decode($row['shalat_sunnah'], true) ?: []);
                      $wajib = '';
                      foreach(json_decode($row['shalat_wajib'], true) ?: [] as $s=>$v){
                        $wajib .= ucfirst($s).': '.$v.' | ';
                      }

                      echo '
                      <tr>
                        <td class="text-center">'.$no.'</td>
                        <td>'.h(tgl_indo($row['tanggal'])).'</td>
                        <td>'.h($row['nama']).'</td>
                        <td>'.h($kebiasaan).'</td>
                        <td>'.h($wajib).'</td>
                        <td>'.h($sunnah).'</td>
                        <td>'.h($row['dzikir']).'</td>
                        <td>'.h($row['tilawah']).'</td>
                        <td class="text-center">
                          <a href="./'.$mod.'&op=detail&nama='.urlencode($row['nama']).'" class="btn btn-info btn-xs"><i class="fa fa-list"></i> Detail</a>
                        </td>
                      </tr>';
                    }
                  } else {
                    echo '<tr><td colspan="9" class="text-center">Tidak ada data ibadah</td></tr>';
                  }

    echo '       </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>';
    break;

  // ================== DETAIL LAPORAN PER ORANG ==================
  case 'detail':
    if (empty($_GET['nama'])) {
      echo '<section class="content"><div class="alert alert-warning">Parameter tidak valid</div></section>';
      break;
    }

    $nama = $connection->real_escape_string($_GET['nama']);
    $bulan = isset($_GET['bulan']) ? $_GET['bulan'] : date('m');
    $tahun = isset($_GET['tahun']) ? $_GET['tahun'] : date('Y');

    echo '
    <section class="content-header">
      <h1>Laporan <small>Ibadah Per Orang</small></h1>
      <ol class="breadcrumb">
        <li><a href="./"><i class="fa fa-dashboard"></i> Beranda</a></li>
        <li><a href="#" onclick="history.back()">Data Ibadah</a></li>
        <li class="active">Laporan '.h($nama).'</li>
      </ol>
    </section>

    <section class="content">
      <div class="row">
        <div class="col-xs-12">
          <div class="box box-solid">
            <div class="box-header with-border">
              <h3 class="box-title"><b>Laporan '.h($nama).'</b></h3>
              <div class="box-tools pull-right">
                <button type="button" onclick="history.back()" class="btn btn-default">Kembali</button>
              </div>
            </div>

            <div class="box-body">
              <h4>Nama: '.h($nama).'</h4>
              <hr>
              <h3>Data Ibadah Bulan '.h($bulan_array[$bulan]).' '.$tahun.'</h3>
              <div class="table-responsive">
                <table class="table table-bordered table-striped table-hover">
                  <thead>
                    <tr>
                      <th>No</th>
                      <th>Tanggal</th>
                      <th>Kebiasaan Baik</th>
                      <th>Shalat Wajib</th>
                      <th>Shalat Sunnah</th>
                      <th>Dzikir</th>
                      <th>Tilawah</th>
                    </tr>
                  </thead>
                  <tbody>';

                  $q = $connection->query("
                    SELECT * FROM ibadah 
                    WHERE nama='$nama'
                    AND MONTH(tanggal)=".(int)$bulan."
                    AND YEAR(tanggal)=".(int)$tahun."
                    ORDER BY tanggal ASC
                  ");

                  if ($q && $q->num_rows > 0) {
                    $no=1;
                    while ($r=$q->fetch_assoc()) {
                      $kebiasaan = implode(", ", json_decode($r['kebiasaan_baik'], true) ?: []);
                      $sunnah = implode(", ", json_decode($r['shalat_sunnah'], true) ?: []);
                      $wajib = '';
                      foreach(json_decode($r['shalat_wajib'], true) ?: [] as $s=>$v){
                        $wajib .= ucfirst($s).': '.$v.' | ';
                      }

                      echo '
                      <tr>
                        <td>'.$no++.'</td>
                        <td>'.h(tgl_indo($r['tanggal'])).'</td>
                        <td>'.h($kebiasaan).'</td>
                        <td>'.h($wajib).'</td>
                        <td>'.h($sunnah).'</td>
                        <td>'.h($r['dzikir']).'</td>
                        <td>'.h($r['tilawah']).'</td>
                      </tr>';
                    }
                  } else {
                    echo '<tr><td colspan="7" class="text-center">Tidak ada data ibadah</td></tr>';
                  }

    echo '       </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>';
    break;
  } // end switch

  echo '</div>';
}
?>
