<?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 PERMINTAAN ==================
  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> Permintaan</small></h1>
      <ol class="breadcrumb">
        <li><a href="./"><i class="fa fa-dashboard"></i> Beranda</a></li>
        <li class="active">Data Permintaan</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 Permintaan</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/permintaan/print.php?action=pdf&from='.$bulan.'&to='.$tahun.'" target="_blank">PDF</a></li>
                    <li><a href="mod/permintaan/print.php?action=excel&from='.$bulan.'&to='.$tahun.'" target="_blank">EXCEL</a></li>
                    <li><a href="mod/permintaan/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 / divisi / status">
                </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 Permintaan</th>
                      <th>Nama Pengaju</th>
                      <th>Divisi Pengaju</th>
                      <th>Divisi Tujuan</th>
                      <th>Penanggung Jawab</th>
                      <th>Detail Permintaan</th>
                      <th>Status</th>
                      <th class="text-center">Aksi</th>
                    </tr>
                  </thead>
                  <tbody>';

                  $where = "WHERE MONTH(tanggal_permintaan)=".(int)$bulan." AND YEAR(tanggal_permintaan)=".(int)$tahun;
                  if ($cari !== '') {
                    $where .= " AND (nama_pengaju LIKE '%$cari_sql%' OR divisi_pengaju LIKE '%$cari_sql%' OR status LIKE '%$cari_sql%' OR penanggung_jawab LIKE '%$cari_sql%')";
                  }

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

                  if ($result && $result->num_rows > 0) {
                    $no=0;
                    while ($row = $result->fetch_assoc()) {
                      $no++;
                      echo '
                      <tr>
                        <td class="text-center">'.$no.'</td>
                        <td>'.h(tgl_indo($row['tanggal_permintaan'])).'</td>
                        <td>'.h($row['nama_pengaju']).'</td>
                        <td>'.h($row['divisi_pengaju']).'</td>
                        <td>'.h($row['divisi_tujuan']).'</td>
                        <td>'.h($row['penanggung_jawab']).'</td>
                        <td>'.h($row['detail_permintaan']).'</td>
                        <td>';
                          if ($row['status'] === "Selesai") {
                            echo '<span class="badge bg-green">Selesai</span>';
                          } elseif ($row['status'] === "Sedang Dikerjakan") {
                            echo '<span class="badge bg-orange">Sedang Dikerjakan</span>';
                          } elseif ($row['status'] === "Disetujui") {
                            echo '<span class="badge bg-info">Disetujui</span>';
                          } elseif ($row['status'] === "Ditolak") {
                            echo '<span class="badge bg-red">Ditolak</span>';
                          } else {
                            echo '<span class="badge bg-gray">Menunggu</span>';
                          }
                      echo '</td>
                        <td class="text-center">
                          <div class="btn-group">
                            <a href="./'.$mod.'&op=views&id='.epm_encode($row['id_permintaan']).'" class="btn btn-warning btn-xs" title="Detail"><i class="fa fa-eye"></i></a>
                            <a href="./'.$mod.'&op=detail&id='.epm_encode($row['id_permintaan']).'" class="btn btn-info btn-xs" title="Laporan Per Orang"><i class="fa fa-list"></i></a>
                          </div>
                        </td>
                      </tr>';
                    }
                  } else {
                    echo '<tr><td colspan="9" class="text-center">Tidak ada data permintaan</td></tr>';
                  }

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


  // ================== LAPORAN DETAIL PER ORANG ==================
  case 'detail':

    if (empty($_GET['id'])) {
      echo '<section class="content"><div class="alert alert-warning">Parameter tidak valid</div></section>';
      break;
    }

    $id = mysqli_real_escape_string($connection, epm_decode($_GET['id']));
    $q_user = $connection->query("SELECT penanggung_jawab FROM permintaan WHERE id_permintaan='$id' LIMIT 1");

    if ($q_user && $q_user->num_rows > 0) {
      $user = $q_user->fetch_assoc();
      $pj = $user['penanggung_jawab'];

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

      echo '
      <section class="content-header">
        <h1>Laporan <small> Permintaan Per Penanggung Jawab</small></h1>
        <ol class="breadcrumb">
          <li><a href="./"><i class="fa fa-dashboard"></i> Beranda</a></li>
          <li><a href="#" onclick="history.back()">Data Permintaan</a></li>
          <li class="active">Laporan '.h($pj).'</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($pj).'</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>Penanggung Jawab : '.h($pj).'</h4>
                <hr>
                <h3>Permintaan 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 Permintaan</th>
                        <th>Nama Pengaju</th>
                        <th>Divisi</th>
                        <th>Detail</th>
                        <th>Status</th>
                      </tr>
                    </thead>
                    <tbody>';

                    $q = $connection->query("
                      SELECT * FROM permintaan 
                      WHERE penanggung_jawab='$pj'
                      AND MONTH(tanggal_permintaan)=".(int)$bulan."
                      AND YEAR(tanggal_permintaan)=".(int)$tahun."
                      ORDER BY tanggal_permintaan ASC
                    ");

                    if ($q && $q->num_rows > 0) {
                      $no=1;
                      $selesai=0; $proses=0; $tolak=0;
                      while ($r=$q->fetch_assoc()) {
                        if ($r['status']=="Selesai") $selesai++;
                        if ($r['status']=="Sedang Dikerjakan") $proses++;
                        if ($r['status']=="Ditolak") $tolak++;
                        echo '
                        <tr>
                          <td>'.$no++.'</td>
                          <td>'.h(tgl_indo($r['tanggal_permintaan'])).'</td>
                          <td>'.h($r['nama_pengaju']).'</td>
                          <td>'.h($r['divisi_pengaju']).'</td>
                          <td>'.h($r['detail_permintaan']).'</td>
                          <td><span class="badge bg-'.(
                            $r['status']=="Selesai"?"green":
                            ($r['status']=="Sedang Dikerjakan"?"orange":
                            ($r['status']=="Ditolak"?"red":"gray"))
                          ).'">'.h($r['status']).'</span></td>
                        </tr>';
                      }
                      echo '
                      <tr>
                        <td colspan="6"><b>Rekap:</b>
                        Selesai: <span class="badge bg-green">'.$selesai.'</span>,
                        Dikerjakan: <span class="badge bg-orange">'.$proses.'</span>,
                        Ditolak: <span class="badge bg-red">'.$tolak.'</span>,
                        Total: <span class="badge bg-blue">'.($selesai+$proses+$tolak).'</span></td>
                      </tr>';
                    } else {
                      echo '<tr><td colspan="6" class="text-center">Tidak ada data permintaan</td></tr>';
                    }

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