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

  // Helper aman untuk output HTML
  if (!function_exists('h')) {
    function h($s) { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
  }

  // ================== Tambahan Fungsi ==================
  if (!function_exists('tgl_indo')) {
    function tgl_indo($tanggal){
      $bulan = array (
        1 => 'Januari','Februari','Maret','April','Mei','Juni',
        'Juli','Agustus','September','Oktober','November','Desember'
      );
      $pecahkan = explode('-', $tanggal); // format: YYYY-MM-DD
      return $pecahkan[2] . ' ' . $bulan[(int)$pecahkan[1]] . ' ' . $pecahkan[0];
    }
  }

  if (!function_exists('bulan_indo')) {
    function bulan_indo($bln){
      $bulan = [
        '01'=>'Januari','02'=>'Februari','03'=>'Maret','04'=>'April',
        '05'=>'Mei','06'=>'Juni','07'=>'Juli','08'=>'Agustus',
        '09'=>'September','10'=>'Oktober','11'=>'November','12'=>'Desember'
      ];
      return isset($bulan[$bln]) ? $bulan[$bln] : $bln;
    }
  }

  // ================== 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 ==================
  default:

    $rawBulan = isset($_GET['bulan']) ? $_GET['bulan'] : date('m');
    $bulan    = in_array($rawBulan, $allowed_months, true) ? $rawBulan : date('m');

    $rawTahun = isset($_GET['tahun']) ? $_GET['tahun'] : date('Y');
    $tahunInt = (int)$rawTahun;
    $tahun    = ($tahunInt >= $minYear && $tahunInt <= $maxYear) ? (string)$tahunInt : date('Y');

    $cari = isset($_GET['cari']) ? trim($_GET['cari']) : '';
    $cari = $connection->real_escape_string($cari);
    if ($cari !== '') {
      $cari = str_replace(['%', '_'], ['\%','\_'], $cari);
    }

    echo '
    <section class="content-header">
      <h1>Data <small> Supervisi</small></h1>
      <ol class="breadcrumb">
        <li><a href="./"><i class="fa fa-dashboard"></i> Beranda</a></li>
        <li class="active">Data Supervisi</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 Supervisi</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/supervisi/print.php?action=pdf&from='.$bulan.'&to='.$tahun.'" target="_blank">PDF</a></li>
                    <li><a href="mod/supervisi/print.php?action=excel&from='.$bulan.'&to='.$tahun.'" target="_blank">EXCEL</a></li>
                    <li><a href="mod/supervisi/print.php?action=excel&from='.$bulan.'&to='.$tahun.'&print=1" target="_blank">PRINT</a></li>
                  </ul>
                </div>
              </div>
            </div>
            <div class="box-body">

              <!-- Filter -->
              <form method="GET" class="form-inline mb-3">
                <input type="hidden" name="op" value="">
                <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==(string)$i)?'selected':'';
                      echo "<option value='$i' $sel>$i</option>";
                    }
    echo '       </select>
                </div>
                <div class="form-group">
                  <input type="text" name="cari" value="'.h(isset($_GET['cari'])?$_GET['cari']:'').'" class="form-control" placeholder="Cari pimpinan / karyawan">
                </div>
                <button type="submit" class="btn btn-primary"><i class="fa fa-search"></i> Tampilkan</button>
              </form>

              <!-- Tabel Supervisi -->
              <div class="table-responsive">
                <table id="swdatatable" class="table table-bordered table-striped table-hover">
                  <thead>
                    <tr>
                      <th>No</th>
                      <th>Tanggal</th>
                      <th>Pimpinan</th>
                      <th>Karyawan</th>
                      <th>Jabatan</th>
                      <th>Substansi</th>
                      <th>Lokasi</th>
                      <th>Jam Masuk</th>
                      <th>Jam Pulang</th>
                      <th>Status</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 (karyawan LIKE '%$cari%' ESCAPE '\\\\' OR pimpinan LIKE '%$cari%' ESCAPE '\\\\')";
                  }

                  $query  = "SELECT * FROM supervisi $where ORDER BY tanggal 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'])).'</td>
                        <td>'.h($row['pimpinan']).'</td>
                        <td>'.h($row['karyawan']).'</td>
                        <td>'.h($row['jabatan']).'</td>
                        <td>'.h($row['substansi']).'</td>
                        <td>'.h($row['lokasi']).'</td>
                        <td>'.h($row['waktu_mulai']).'</td>
                        <td>'.h($row['waktu_akhir']).'</td>
                        <td>';
                          if ($row['status'] === "Selesai") {
                            echo '<span class="badge bg-green">Hadir</span>';
                          } else {
                            echo '<span class="badge bg-red">'.h($row['status']).'</span>';
                          }
                      echo '</td>
                        <td class="text-center">
                          <div class="btn-group">
                            <a href="./'.$mod.'&op=views&id='.epm_encode($row['id']).'" 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']).'" 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="11" class="text-center">Data tidak ditemukan</td></tr>';
                  }

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

  // ================== DETAIL SUPERVISI (satu baris) ==================
  case 'views':
    // sama seperti versi kamu, tidak diubah
    break;

  // ================== LAPORAN 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   = "SELECT karyawan, jabatan FROM supervisi WHERE id='$id' LIMIT 1";
    $r_user   = $connection->query($q_user);

    if ($r_user && $r_user->num_rows > 0) {
      $user = $r_user->fetch_assoc();

      $rawBulan = isset($_GET['bulan']) ? $_GET['bulan'] : date('m');
      $bulan    = in_array($rawBulan, $allowed_months, true) ? $rawBulan : date('m');

      $rawTahun = isset($_GET['tahun']) ? $_GET['tahun'] : date('Y');
      $tahunInt = (int)$rawTahun;
      $tahun    = ($tahunInt >= $minYear && $tahunInt <= $maxYear) ? (string)$tahunInt : date('Y');

      $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"
      ];

      echo '
      <section class="content-header">
        <h1>Laporan <small> Supervisi 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 Supervisi</a></li>
          <li class="active">Laporan '.h($user['karyawan']).'</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($user['karyawan']).'</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($user['karyawan']).'</h4>
                <h4>Jabatan: '.h($user['jabatan']).'</h4>
                <hr>

                <form method="GET" class="form-inline mb-3">
                  <input type="hidden" name="op" value="detail">
                  <input type="hidden" name="id" value="'.h($_GET['id']).'">
                  <div class="form-group">
                    <select name="bulan" class="form-control">';
                      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==(string)$i)?'selected':'';
                        echo "<option value='$i' $sel>$i</option>";
                      }
      echo '         </select>
                  </div>
                  <button type="submit" class="btn btn-primary">Tampilkan</button>
                  <div class="btn-group">
                    <button type="button" class="btn btn-warning">Ekspor/Cetak</button>
                    <button type="button" class="btn btn-warning dropdown-toggle" data-toggle="dropdown">
                      <span class="caret"></span>
                    </button>
                    <ul class="dropdown-menu" role="menu">
                      <li><a href="mod/supervisi/print.php?action=detailpdf&id='.h($_GET['id']).'&from='.$bulan.'&to='.$tahun.'" target="_blank">PDF</a></li>
                      <li><a href="mod/supervisi/print.php?action=detailexcel&id='.h($_GET['id']).'&from='.$bulan.'&to='.$tahun.'" target="_blank">EXCEL</a></li>
                      <li><a href="mod/supervisi/print.php?action=detailexcel&id='.h($_GET['id']).'&from='.$bulan.'&to='.$tahun.'&print=1" target="_blank">PRINT</a></li>
                    </ul>
                  </div>
                </form>

                <h3>Supervisi Bulan : '.$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>Jam Masuk</th>
                        <th>Jam Pulang</th>
                        <th>Lokasi</th>
                        <th>Status</th>
                        <th>Aksi</th>
                      </tr>
                    </thead>
                    <tbody>';

                    $q2 = "SELECT * FROM supervisi
                           WHERE karyawan='".$connection->real_escape_string($user['karyawan'])."'
                           AND MONTH(tanggal)=".(int)$bulan."
                           AND YEAR(tanggal)=".(int)$tahun."
                           ORDER BY tanggal ASC";

                    $r2 = $connection->query($q2);

                    if ($r2 && $r2->num_rows > 0) {
                      $no = 1;
                      $hadir = 0; $tidak = 0;

                      while ($row = $r2->fetch_assoc()) {
                        $isHadir = ($row['status'] === 'Selesai');
                        if ($isHadir) $hadir++; else $tidak++;

                        echo '
                        <tr>
                          <td>'.$no++.'</td>
                          <td>'.h(tgl_indo($row['tanggal'])).'</td>
                          <td>'.h($row['waktu_mulai']).'</td>
                          <td>'.h($row['waktu_akhir']).'</td>
                          <td>'.h($row['lokasi']).'</td>
                          <td>';
                            if ($isHadir) {
                              echo '<span class="badge bg-green">Hadir</span>';
                            } else {
                              echo '<span class="badge bg-red">'.h($row['status']).'</span>';
                            }
                        echo '</td>
                          <td>
                            <a href="map.php?lokasi='.urlencode($row['lokasi']).'" class="btn btn-xs btn-warning">Lokasi</a>';
                            if (!empty($row['foto'])) {
                              echo ' <a href="uploads/'.h($row['foto']).'" target="_blank" class="btn btn-xs btn-info">Foto</a>';
                            }
                        echo '</td>
                        </tr>';
                      }

                      $total = $hadir + $tidak;
                      echo '
                      <tr>
                        <td colspan="7">
                          <b>Rekapitulasi:</b>
                          Hadir = <span class="badge bg-green">'.$hadir.'</span>,
                          Tidak Hadir = <span class="badge bg-red">'.$tidak.'</span>,
                          Total = <span class="badge bg-blue">'.$total.'</span>
                        </td>
                      </tr>';

                    } else {
                      echo '<tr><td colspan="7" class="text-center">Tidak ada data supervisi bulan ini</td></tr>';
                    }

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

    } else {
      echo '<section class="content"><div class="alert alert-warning">Data tidak ditemukan</div></section>';
    }
    break;

  } // end switch
  echo '</div>';
} // end session
?>
