<?php
session_start();
$is_admin = isset($_SESSION['role']) && strtolower($_SESSION['role']) === 'admin';

// Koneksi
$conn = new mysqli("localhost", "root", "", "ptpn_produksi");
if ($conn->connect_error) {
    die("Koneksi gagal: " . $conn->connect_error);
}

// Fungsi total per tahapan
function getTotal($conn, $table, $column) {
    $sql = "SELECT SUM($column) as total FROM $table";
    $result = $conn->query($sql);
    $row = $result->fetch_assoc();
    return $row['total'] ?? 0;
}

// ✅ Total tahapan produksi
$total_pucuk        = getTotal($conn, "penerimaan_pucuk", "jumlah_pucuk");
$total_pelayuan     = getTotal($conn, "pelayuan", "berat_layu");
$total_penggilingan = getTotal($conn, "penggilingan", "berat_giling");
$total_oksidasi     = getTotal($conn, "oksidasi", "berat_oksidasi");
$total_pengeringan  = getTotal($conn, "pengeringan", "berat_kering");
$total_sortasi      = getTotal($conn, "sortasi", "berat_sortasi");
$total_pengepakan   = getTotal($conn, "pengepakan", "jumlah_kemasan");

// ✅ Ambil semua kelas_mutu & mutu dan total berat_sortasi-nya
$sql_kelas = "
    SELECT jt.kelas_mutu, jt.mutu, SUM(s.berat_sortasi) AS total
    FROM sortasi s
    JOIN jenis_teh jt ON s.id_teh = jt.id_teh
    GROUP BY jt.kelas_mutu, jt.mutu
    ORDER BY jt.kelas_mutu ASC, jt.mutu ASC";
$result_kelas = $conn->query($sql_kelas);

// Siapkan data untuk chart/tabel
$kelasMutuLabels = [];
$kelasMutuValues = [];

while ($row = $result_kelas->fetch_assoc()) {
    $label = $row['kelas_mutu'] . ' - ' . $row['mutu'];
    $kelasMutuLabels[] = $label;
    $kelasMutuValues[] = (float) $row['total'];
}

// ✅ Encode ke JSON untuk Chart.js
$kelasMutuLabelsJSON = json_encode($kelasMutuLabels);
$kelasMutuValuesJSON = json_encode($kelasMutuValues);

// Ambil total berat_sortasi berdasarkan kelas_mutu
$sqlPie = "
  SELECT jt.kelas_mutu, SUM(s.berat_sortasi) as total
  FROM sortasi s
  JOIN jenis_teh jt ON s.id_teh = jt.id_teh
  GROUP BY jt.kelas_mutu
  ORDER BY jt.kelas_mutu ASC
";
$resPie = $conn->query($sqlPie);
$pieLabels = [];
$pieData = [];

while ($row = $resPie->fetch_assoc()) {
  $pieLabels[] = $row['kelas_mutu'];
  $pieData[] = (float) $row['total'];
}

// Ambil total berat_sortasi berdasarkan kelas_mutu + mutu
$sqlLine = "
  SELECT CONCAT(jt.kelas_mutu, ' - ', jt.mutu) AS label, SUM(s.berat_sortasi) AS total
  FROM sortasi s
  JOIN jenis_teh jt ON s.id_teh = jt.id_teh
  GROUP BY jt.kelas_mutu, jt.mutu
  ORDER BY jt.kelas_mutu ASC, jt.mutu ASC
";
$resLine = $conn->query($sqlLine);
$lineLabels = [];
$lineData = [];

while ($row = $resLine->fetch_assoc()) {
  $lineLabels[] = $row['label'];
  $lineData[] = (float) $row['total'];
}

// Encode JSON
$kategoriLabels = json_encode($pieLabels);
$kategoriDataJSON = json_encode($pieData);
$jenisLabels = json_encode($lineLabels);
$jenisDataJSON = json_encode($lineData);


// ===================== Penjualan Harian (30 hari terakhir) =====================
$conn2 = new mysqli("localhost", "root", "", "ptpn_produksi");
if ($conn2->connect_error) { die("Koneksi gagal: " . $conn2->connect_error); }
$sqlSales = "
  SELECT DATE(tanggal_jual) AS tgl,
         SUM(total_harga) AS total_penjualan,
         SUM(quantity_kg) AS total_qty
  FROM penjualan
  WHERE tanggal_jual >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
  GROUP BY DATE(tanggal_jual)
  ORDER BY tgl
";
$resSales = $conn2->query($sqlSales);
$salesLabels = [];
$salesAmount = [];
$salesQty = [];
while ($r = $resSales->fetch_assoc()) {
  $salesLabels[] = date('d/m', strtotime($r['tgl']));
  $salesAmount[] = (float) ($r['total_penjualan'] ?? 0);
  $salesQty[] = (float) ($r['total_qty'] ?? 0);
}
$salesLabelsJSON = json_encode($salesLabels);
$salesAmountJSON = json_encode($salesAmount);
$salesQtyJSON = json_encode($salesQty);
$conn2->close();

$conn->close();
?>

<!DOCTYPE html>
<html :class="{ 'theme-dark': dark }" x-data="data()" lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Panglejar Dashboard</title>
    <link
      href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="./assets/css/tailwind.output.css" />
    <script
      src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js"
      defer
    ></script>
    <script src="./assets/js/init-alpine.js"></script>
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.css"
    />
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"
      defer
    ></script>
    <script src="./assets/js/charts-lines.js" defer></script>
    <script src="./assets/js/charts-pie.js" defer></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  </head>
  <body>
    <div
      class="flex h-screen bg-gray-50 dark:bg-gray-900"
      :class="{ 'overflow-hidden': isSideMenuOpen }"
    >
      <!-- Desktop sidebar -->
     <?php
$currentPage = basename($_SERVER['PHP_SELF']);
      include 'sidebar.php';
      ?>

<?php include 'header.php'; ?>
        <main class="h-full overflow-y-auto">
          <div class="container px-6 mx-auto grid">
            <h2
              class="my-6 text-2xl font-semibold text-gray-700 dark:text-gray-200"
            >
              Dashboard
            </h2>
            </a>
            <!-- Cards -->
<div class="grid gap-6 mb-8 md:grid-cols-2 xl:grid-cols-4">
  <!-- Penerimaan Pucuk -->
  <a href="penerimaan_pucuk.php">
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
      <div class="p-3 mr-4 text-orange-500 bg-orange-100 rounded-full dark:text-orange-100 dark:bg-orange-500">
        <!-- Inbox Icon -->
        <svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2"
             viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round">
          <path d="M20 13V5a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8"/>
          <polyline points="3 13 12 22 21 13"/>
        </svg>
      </div>
      <div>
        <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Penerimaan Pucuk</p>
        <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">
          <?= number_format($total_pucuk) ?> Kg
        </p>
      </div>
    </div>
  </a>

  <!-- Pelayuan -->
  <a href="pelayuan.php">
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
      <div class="p-3 mr-4 text-green-500 bg-green-100 rounded-full dark:text-green-100 dark:bg-green-500">
        <!-- Leaf Icon -->
        <svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2"
             viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round">
          <path d="M11 21c1.104 0 2-.896 2-2V7a6 6 0 0 0-12 0v12c0 1.104.896 2 2 2h8z"/>
          <path d="M18 21c1.104 0 2-.896 2-2V11a4 4 0 0 0-8 0v8c0 1.104.896 2 2 2h4z"/>
        </svg>
      </div>
      <div>
        <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Pelayuan</p>
        <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">
          <?= number_format($total_pelayuan) ?> Kg
        </p>
      </div>
    </div>
  </a>

  <!-- Penggilingan -->
  <a href="penggilingan.php">
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
      <div class="p-3 mr-4 text-blue-500 bg-blue-100 rounded-full dark:text-blue-100 dark:bg-blue-500">
        <!-- Cog Icon -->
        <svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2"
             viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round">
          <circle cx="12" cy="12" r="3"/>
          <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33
                   1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51
                   1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06
                   a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3
                   a2 2 0 0 1 0-4h.09c.7 0 1.33-.4 1.51-1
                   a1.65 1.65 0 0 0-.33-1.82l-.06-.06
                   a2 2 0 0 1 2.83-2.83l.06.06
                   c.49.49 1.2.65 1.82.33.58-.32.95-.94.95-1.63V3
                   a2 2 0 0 1 4 0v.09c0 .7.4 1.33 1 1.51
                   .62.18 1.33.02 1.82-.33l.06-.06
                   a2 2 0 0 1 2.83 2.83l-.06.06
                   a1.65 1.65 0 0 0-.33 1.82c.18.62.81 1 1.51 1H21
                   a2 2 0 0 1 0 4h-.09c-.7 0-1.33.4-1.51 1z"/>
        </svg>
      </div>
      <div>
        <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Penggilingan</p>
        <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">
          <?= number_format($total_penggilingan) ?> Kg
        </p>
      </div>
    </div>
  </a>

  <!-- Oksidasi -->
  <a href="oksidasi.php">
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
      <div class="p-3 mr-4 text-teal-500 bg-teal-100 rounded-full dark:text-teal-100 dark:bg-teal-500">
        <!-- Refresh Icon -->
        <svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2"
             viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round">
          <polyline points="23 4 23 10 17 10"/>
          <polyline points="1 20 1 14 7 14"/>
          <path d="M3.51 9a9 9 0 0 1 14.13-3.36L23 10M1 14l5.36 5.36A9 9 0 0 0 20.49 15"/>
        </svg>
      </div>
      <div>
        <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Oksidasi</p>
        <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">
          <?= number_format($total_oksidasi) ?> Kg
        </p>
      </div>
    </div>
  </a>

  <!-- Pengeringan -->
  <a href="pengeringan.php">
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
      <div class="p-3 mr-4 text-yellow-500 bg-yellow-100 rounded-full dark:text-yellow-100 dark:bg-yellow-500">
        <!-- Sun Icon -->
        <svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2"
             viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round">
          <circle cx="12" cy="12" r="5"/>
          <line x1="12" y1="1" x2="12" y2="3"/>
          <line x1="12" y1="21" x2="12" y2="23"/>
          <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/>
          <line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/>
          <line x1="1" y1="12" x2="3" y2="12"/>
          <line x1="21" y1="12" x2="23" y2="12"/>
          <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/>
          <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>
        </svg>
      </div>
      <div>
        <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Pengeringan</p>
        <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">
          <?= number_format($total_pengeringan) ?> Kg
        </p>
      </div>
    </div>
  </a>

  <!-- Sortasi -->
  <a href="sortasi.php">
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
      <div class="p-3 mr-4 text-purple-500 bg-purple-100 rounded-full dark:text-purple-100 dark:bg-purple-500">
        <!-- Filter Icon -->
        <svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2"
             viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round">
          <polygon points="22 3 2 3 10 13 10 19 14 21 14 13 22 3"/>
        </svg>
      </div>
      <div>
        <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Sortasi</p>
        <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">
          <?= number_format($total_sortasi) ?> Kg
        </p>
      </div>
    </div>
  </a>

  <!-- Pengepakan -->
  <a href="pengepakan.php">
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
      <div class="p-3 mr-4 text-pink-500 bg-pink-100 rounded-full dark:text-pink-100 dark:bg-pink-500">
        <!-- Package Icon -->
        <svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2"
             viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round">
          <path d="M21 16V8a2 2 0 0 0-1-1.73L12 2 4 6.27A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73L12 22l8-4.27A2 2 0 0 0 21 16z"/>
          <polyline points="3.27 6.96 12 12.01 20.73 6.96"/>
          <line x1="12" y1="22" x2="12" y2="12"/>
        </svg>
      </div>
      <div>
        <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Pengepakan</p>
        <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">
          <?= number_format($total_pengepakan) ?> Pack
        </p>
      </div>
    </div>
  </a>

  <!-- Hasil Produksi -->
  <a href="laporan.php">
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
      <div class="p-3 mr-4 text-indigo-500 bg-indigo-100 rounded-full dark:text-indigo-100 dark:bg-indigo-500">
        <!-- Bar Chart Icon -->
        <svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2"
             viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round">
          <line x1="12" y1="20" x2="12" y2="10"/>
          <line x1="18" y1="20" x2="18" y2="4"/>
          <line x1="6" y1="20" x2="6" y2="16"/>
        </svg>
      </div>
      <div>
        <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Hasil Produksi</p>
        <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">
          <?= number_format($total_pengepakan) ?> Pack
        </p>
      </div>
    </div>
  </a>
</div>

            <!-- Charts -->
            <div class="grid gap-6 mb-8 md:grid-cols-2">
              <div
                class="min-w-0 p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800"
              >
                <h4 class="mb-4 font-semibold text-gray-800 dark:text-gray-300">
                  KELAS MUTU
                </h4>
                <!-- Container Pie Chart -->
<div class="flex justify-center items-center h-[200px]">
  <canvas id="pie" width="250" height="250"></canvas>
</div>


                <div
                  class="flex justify-center items-center h-40"
                >
                  <!-- Chart legend -->
                  <!-- Chart legend untuk Pie -->



                </div>
              </div>
              <div
                class="min-w-0 p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800"
              >
                <h4 class="mb-4 font-semibold text-gray-800 dark:text-gray-300">
                  MUTU
                </h4>
                <canvas id="line" width="600" height="300"></canvas>
                <div
                  class="flex justify-center mt-4 space-x-3 text-sm text-gray-600 dark:text-gray-400"
                >
                  <!-- Chart legend -->
                  <!-- Legend bisa statis atau dibuat loop -->
<div class="flex flex-wrap gap-2 mt-2">
  <span class="text-xs"></span>
</div>

                </div>
              </div>
            </div>

            <!-- Grafik Penjualan & Quantity Harian (diletakkan di bawah grafik KELAS MUTU dan MUTU) -->
            <div class="grid gap-6 mb-8 md:grid-cols-2">
              <div class="min-w-0 p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
                <h4 class="mb-4 font-semibold text-gray-800 dark:text-gray-300">Grafik Penjualan Harian (Rp)</h4>
                <canvas id="chartPenjualanDashboard" height="220"></canvas>
              </div>
              <div class="min-w-0 p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
                <h4 class="mb-4 font-semibold text-gray-800 dark:text-gray-300">Grafik Quantity Harian (Kg)</h4>
                <canvas id="chartQuantityDashboard" height="220"></canvas>
              </div>
            </div>
          </div>
        </main>
      </div>
    </div>
   <script>
const kategoriLabels = <?= $kategoriLabels ?>;
const kategoriData = <?= $kategoriDataJSON ?>;
const jenisLabels = <?= $jenisLabels ?>;
const jenisData = <?= $jenisDataJSON ?>;

// Pie chart - kelas mutu
const pieCtx = document.getElementById("pie").getContext("2d");
new Chart(pieCtx, {
  type: "doughnut",
  data: {
    labels: kategoriLabels,
    datasets: [{
      data: kategoriData,
      backgroundColor: ["#0ea5e9", "#8b5cf6", "#f59e0b"], // MUTU I, II, III
    }]
  },
  options: {
    responsive: true,
    maintainAspectRatio: false, // ✅ ini bagian pentingnya
    plugins: {
      legend: { position: "bottom" }
    }
  }
});

// Line chart - kelas + mutu
const lineCtx = document.getElementById("line").getContext("2d");
new Chart(lineCtx, {
  type: "line",
  data: {
    labels: jenisLabels,
    datasets: [{
      label: "Produksi per Jenis Teh",
      data: jenisData,
      fill: false,
      borderColor: "#f59e0b", // hijau teal
      tension: 0.4
    }]
  },
  options: {
    responsive: true,
    plugins: { legend: { position: "bottom" } },
    scales: {
      y: { beginAtZero: true }
    }
  }
});

// Dashboard Sales Charts
const salesLabels = <?= $salesLabelsJSON ?>;
const salesAmount = <?= $salesAmountJSON ?>;
const salesQty = <?= $salesQtyJSON ?>;

// Penjualan (Line)
const ctxPenjualanDash = document.getElementById('chartPenjualanDashboard').getContext('2d');
new Chart(ctxPenjualanDash, {
  type: 'line',
  data: {
    labels: salesLabels,
    datasets: [{
      label: 'Total Penjualan (Rp)',
      data: salesAmount,
      borderColor: 'rgb(147, 51, 234)',
      backgroundColor: 'rgba(147, 51, 234, 0.1)',
      tension: 0.2,
      fill: true
    }]
  },
  options: { responsive: true, scales: { y: { beginAtZero: true } } }
});

// Quantity (Bar)
const ctxQtyDash = document.getElementById('chartQuantityDashboard').getContext('2d');
new Chart(ctxQtyDash, {
  type: 'bar',
  data: {
    labels: salesLabels,
    datasets: [{
      label: 'Total Quantity (kg)',
      data: salesQty,
      backgroundColor: 'rgba(59, 130, 246, 0.8)',
      borderColor: 'rgb(59, 130, 246)',
      borderWidth: 1
    }]
  },
  options: { responsive: true, scales: { y: { beginAtZero: true } } }
});

</script>


  </body>
</html>
