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

  // Hitung data master
  $query_employees ="SELECT id FROM employees";
  $result_count = $connection->query($query_employees);
  $total_user   = $result_count->num_rows;

  $query_position ="SELECT position_id FROM position";
  $result_count_position = $connection->query($query_position);

  $query_building ="SELECT building_id FROM building";
  $result_count_building = $connection->query($query_building);

  $query_shift ="SELECT shift_id FROM shift";
  $result_count_shift = $connection->query($query_shift);

  // Rekap 7 hari terakhir
  $weekly = [
    'supervisi' => 0,
    'ibadah'    => 0,
    'izin'      => 0,
    'aktivitas' => 0
  ];

  $q = $connection->query("SELECT COUNT(DISTINCT pimpinan) as jml FROM supervisi WHERE tanggal >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)");
  $weekly['supervisi'] = $q ? $q->fetch_assoc()['jml'] : 0;

  $q = $connection->query("SELECT COUNT(DISTINCT nama) as jml FROM ibadah WHERE tanggal >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)");
  $weekly['ibadah'] = $q ? $q->fetch_assoc()['jml'] : 0;

  $q = $connection->query("SELECT COUNT(DISTINCT nama) as jml FROM izin WHERE tanggal >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)");
  $weekly['izin'] = $q ? $q->fetch_assoc()['jml'] : 0;

  $q = $connection->query("SELECT COUNT(DISTINCT nama) as jml FROM aktivitas WHERE tanggal >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)");
  $weekly['aktivitas'] = $q ? $q->fetch_assoc()['jml'] : 0;

  // Persentase
  $persentase = [
    'supervisi' => $total_user > 0 ? round(($weekly['supervisi'] / $total_user) * 100, 1) : 0,
    'ibadah'    => $total_user > 0 ? round(($weekly['ibadah'] / $total_user) * 100, 1) : 0,
    'izin'      => $total_user > 0 ? round(($weekly['izin'] / $total_user) * 100, 1) : 0,
    'aktivitas' => $total_user > 0 ? round(($weekly['aktivitas'] / $total_user) * 100, 1) : 0
  ];

echo'
<div class="content-wrapper">
<section class="content">
  <div class="row">
    <!-- Jumlah user -->
    <div class="col-lg-3 col-xs-6">
      <div class="small-box bg-primary">
        <div class="inner">
          <h3>'.$total_user.'</h3>
          <p>Pengguna</p>
        </div>
        <div class="icon"><i class="fa fa-user"></i></div>
        <a href="./karyawan" class="small-box-footer">Selengkapnya <i class="fa fa-arrow-circle-right"></i></a>
      </div>
    </div>

    <!-- Jabatan -->
    <div class="col-lg-3 col-xs-6">
      <div class="small-box bg-yellow">
        <div class="inner">
          <h3>'.$result_count_position->num_rows.'</h3>
          <p>Jabatan</p>
        </div>
        <div class="icon"><i class="fa fa-briefcase"></i></div>
        <a href="./jabatan" class="small-box-footer">Selengkapnya <i class="fa fa-arrow-circle-right"></i></a>
      </div>
    </div>

    <!-- Lokasi -->
    <div class="col-lg-3 col-xs-6">
      <div class="small-box bg-red">
        <div class="inner">
          <h3>'.$result_count_building->num_rows.'</h3>
          <p>Lokasi Kantor</p>
        </div>
        <div class="icon"><i class="fa fa-building"></i></div>
        <a href="./lokasi" class="small-box-footer">Selengkapnya <i class="fa fa-arrow-circle-right"></i></a>
      </div>
    </div>

    <!-- Shift -->
    <div class="col-lg-3 col-xs-6">
      <div class="small-box bg-green">
        <div class="inner">
          <h3>'.$result_count_shift->num_rows.'</h3>
          <p>Shift Kerja</p>
        </div>
        <div class="icon"><i class="fa fa-retweet"></i></div>
        <a href="./shift" class="small-box-footer">Selengkapnya <i class="fa fa-arrow-circle-right"></i></a>
      </div>
    </div>
  </div>

  <!-- Rekap Mingguan -->
  <div class="row">
    <div class="col-lg-3 col-xs-6">
      <div class="small-box bg-purple">
        <div class="inner">
          <h3>'.$weekly['supervisi'].' / '.$total_user.'</h3>
          <p>Supervisi ('.$persentase['supervisi'].'%)</p>
        </div>
        <div class="icon"><i class="fa fa-eye"></i></div>
      </div>
    </div>
    <div class="col-lg-3 col-xs-6">
      <div class="small-box bg-teal">
        <div class="inner">
          <h3>'.$weekly['ibadah'].' / '.$total_user.'</h3>
          <p>Ibadah ('.$persentase['ibadah'].'%)</p>
        </div>
        <div class="icon"><i class="fa fa-heart"></i></div>
      </div>
    </div>
    <div class="col-lg-3 col-xs-6">
      <div class="small-box bg-dark">
        <div class="inner">
          <h3>'.$weekly['izin'].' / '.$total_user.'</h3>
          <p>Izin ('.$persentase['izin'].'%)</p>
        </div>
        <div class="icon"><i class="fa fa-file-text"></i></div>
      </div>
    </div>
    <div class="col-lg-3 col-xs-6">
      <div class="small-box bg-orange">
        <div class="inner">
          <h3>'.$weekly['aktivitas'].' / '.$total_user.'</h3>
          <p>Aktivitas ('.$persentase['aktivitas'].'%)</p>
        </div>
        <div class="icon"><i class="fa fa-tasks"></i></div>
      </div>
    </div>
  </div>

  <!-- Grafik -->
  <div class="row">
    <!-- Grafik Absensi -->
    <div class="col-xs-12 col-md-6">
      <div class="box box-solid">
        <div class="box-header with-border"><h3 class="box-title">Statistik Absensi</h3></div>
        <div class="box-body"><div class="chart"><canvas id="areaChart" style="height:320px"></canvas></div></div>
      </div>
    </div>

    <!-- Grafik Pie -->
    <div class="col-xs-12 col-md-6">
      <div class="box box-solid">
        <div class="box-header with-border"><h3 class="box-title">Persentase Kegiatan User (7 Hari)</h3></div>
        <div class="box-body text-center"><canvas id="pieChart" style="max-width:320px; max-height:320px; margin:auto;"></canvas></div>
      </div>
    </div>
  </div>
</section>
</div>';

  // Data absensi seminggu
  $tgl_skrg = date("Y-m-d");
  $seminggu = strtotime("-1 week +1 day",strtotime($tgl_skrg));
  $hasilnya = date('Y-m-d', $seminggu);
  for ($i=0; $i<=6; $i++){
    $tgl_pengujung   = strtotime("+$i day",strtotime($hasilnya));
    $hasil_pengujung = date("Y-m-d", $tgl_pengujung);
    $tanggal_visitor []= tgl_ind($hasil_pengujung);
    $query_absensi ="SELECT presence_date FROM presence WHERE presence_date='$hasil_pengujung'";
    $result_absensi = $connection->query($query_absensi);
    $absensi [] = $result_absensi->num_rows;
  }
  $tanggal_visitor = implode('","',$tanggal_visitor);
?>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script type="text/javascript">
  // Grafik absensi line chart
  var ctx = document.getElementById("areaChart").getContext("2d");
  new Chart(ctx, {
    type: 'line',
    data: {
      labels :["<?php echo $tanggal_visitor;?>"],
      datasets : [{
        label: "Statistik Absensi",
        data :<?php echo json_encode($absensi);?>,
        backgroundColor : "rgba(29,75,251,0.5)",
        borderColor : "rgba(29,75,251,1)",
        fill: true,
        tension: 0.3
      }]
    },
    options: { responsive: true, maintainAspectRatio: false }
  });

  // Grafik pie chart rekap mingguan
  var ctxPie = document.getElementById("pieChart").getContext("2d");
  new Chart(ctxPie, {
    type: 'doughnut',
    data: {
      labels: ["Supervisi","Ibadah","Izin","Aktivitas"],
      datasets: [{
        data: [
          <?= $weekly['supervisi']; ?>,
          <?= $weekly['ibadah']; ?>,
          <?= $weekly['izin']; ?>,
          <?= $weekly['aktivitas']; ?>
        ],
        backgroundColor: ["#6f42c1","#20c997","#343a40","#fd7e14"],
        borderWidth: 2,
        borderColor: "#fff"
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      cutout: "60%", // donut style
      plugins: {
        legend: { position: "bottom", labels: { boxWidth: 20, padding: 15 } },
        tooltip: {
          callbacks: {
            label: function(context) {
              let value = context.parsed;
              let persen = (value / <?= $total_user ?> * 100).toFixed(1);
              return context.label + ": " + value + " user (" + persen + "%)";
            }
          }
        }
      }
    },
    plugins: [{
      id: "centerText",
      beforeDraw: function(chart) {
        const { width, height } = chart;
        const ctx = chart.ctx;
        ctx.restore();
        const fontSize = (height / 150).toFixed(2);
        ctx.font = fontSize + "em sans-serif";
        ctx.textBaseline = "middle";
        let total = chart.data.datasets[0].data.reduce((a, b) => a + b, 0);
        let text = total + " User";
        let textX = Math.round((width - ctx.measureText(text).width) / 2);
        let textY = height / 2;
        ctx.fillText(text, textX, textY);
        ctx.save();
      }
    }]
  });
</script>
<?php } ?>

<?php
// === Data untuk Grafik Status Pekerjaan per Penanggung Jawab ===
$q_jobs = $connection->query("
  SELECT penanggung_jawab, status, COUNT(*) AS jumlah
  FROM permintaan
  WHERE penanggung_jawab IS NOT NULL AND penanggung_jawab <> ''
  GROUP BY penanggung_jawab, status
  ORDER BY penanggung_jawab ASC
");

// Siapkan data array untuk Chart.js
$data_status = [];
$labels_user = [];

while($r = $q_jobs->fetch_assoc()) {
  $pj = $r['penanggung_jawab'];
  $status = $r['status'];
  $jumlah = (int)$r['jumlah'];

  $labels_user[$pj] = true;
  $data_status[$status][$pj] = $jumlah;
}

$labels_user = array_keys($labels_user);
$statuses = array_keys($data_status);
?>

<!-- GRAFIK STATUS PEKERJAAN PER PENANGGUNG JAWAB -->
<div class="row">
  <div class="col-xs-12">
    <div class="box box-solid text-center">
      <div class="box-header with-border">
        <h3 class="box-title text-center w-100">📊 Status Pekerjaan per Penanggung Jawab</h3>
      </div>
      <div class="box-body d-flex justify-content-center align-items-center" style="min-height: 400px;">
        <div style="max-width: 800px; width: 100%;">
          <canvas id="statusChart" style="width: 100%; max-height: 400px; margin: 0 auto; display: block;"></canvas>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Script -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2"></script>

<script>
const labelsStatus = <?= json_encode($labels_user); ?>;
const rawStatusData = <?= json_encode($data_status); ?>;

// Warna untuk tiap status
const colors = {
  "Menunggu": "#6c757d",
  "Disetujui": "#17a2b8",
  "Ditolak": "#dc3545",
  "Sedang Dikerjakan": "#fd7e14",
  "Selesai": "#28a745"
};

// Dataset berdasarkan status pekerjaan
const datasetsStatus = Object.keys(rawStatusData).map(status => ({
  label: status,
  data: labelsStatus.map(pj => rawStatusData[status][pj] || 0),
  backgroundColor: colors[status] || "#999",
  borderWidth: 1
}));

// Buat grafik bar dengan angka di atas batang
new Chart(document.getElementById("statusChart").getContext("2d"), {
  type: "bar",
  data: {
    labels: labelsStatus,
    datasets: datasetsStatus
  },
  options: {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: { position: "bottom" },
      tooltip: {
        callbacks: {
          label: ctx => `${ctx.dataset.label}: ${ctx.parsed.y} pekerjaan`
        }
      },
      datalabels: {
        anchor: "end",
        align: "end",
        color: "#000",
        font: {
          weight: "bold",
          size: 12
        },
        formatter: value => value > 0 ? value : ""
      }
    },
    scales: {
      x: {
        title: { display: true, text: "Penanggung Jawab" },
        ticks: { color: "#333" }
      },
      y: {
        beginAtZero: true,
        title: { display: true, text: "Jumlah Pekerjaan" },
        ticks: { color: "#333" }
      }
    }
  },
  plugins: [ChartDataLabels]
});
</script>










