<?php
require_once __DIR__ . '/../config/user_functions.php';

session_start();
require_once __DIR__ . '/../config/db_remote.php';
if (file_exists(__DIR__ . '/../includes/lang.php')) {
    require_once __DIR__ . '/../includes/lang.php';
}

$user = $_SESSION['user'] ?? null;
$role = $user['role'] ?? 'viewer';
if ($role !== 'admin') { die("Not allowed."); }

// Checkbox + range
$showSerial    = isset($_GET['show_serial'])    ? 1 : 0;
$showVariety   = isset($_GET['show_variety'])   ? 1 : 0;
$showPackaging = isset($_GET['show_packaging']) ? 1 : 0;
$showSize      = isset($_GET['show_size'])      ? 1 : 0;
$showGrower    = isset($_GET['show_grower'])    ? 1 : 0;
$showMainChart = isset($_GET['show_main'])      ? 1 : 0;

if (!$showSerial && !$showVariety && !$showPackaging && !$showSize && !$showGrower && !$showMainChart) {
    // default: show everything
    $showSerial = $showVariety = $showPackaging = $showSize = $showGrower = $showMainChart = 1;
}

$range = $_GET['range'] ?? 'today';

$where = '1';
$rangeLabel = 'Oggi';
switch ($range) {
    case '10m':
        $where = "scan_time >= NOW() - INTERVAL 10 MINUTE";
        $rangeLabel = 'Ultimi 10 minuti';
        break;
    case 'today':
        $where = "DATE(scan_time) = CURDATE()";
        $rangeLabel = 'Oggi';
        break;
    case 'week':
        $where = "scan_time >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)";
        $rangeLabel = 'Ultimi 7 giorni';
        break;
    case 'month':
        $where = "scan_time >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)";
        $rangeLabel = 'Ultimi 30 giorni';
        break;
}

// MAIN chart: production per hour
$mainLabels = [];
$mainCounts = [];
if ($showMainChart) {
    $sql = "SELECT DATE(scan_time) AS d, HOUR(scan_time) AS h, COUNT(*) AS c
            FROM production_log
            WHERE {$where}
            GROUP BY DATE(scan_time), HOUR(scan_time)
            ORDER BY d, h";
    if ($res = $mysqli->query($sql)) {
        while ($r = $res->fetch_assoc()) {
            $label = $r['d'] . ' ' . str_pad((string)$r['h'], 2, '0', STR_PAD_LEFT) . ':00';
            $mainLabels[] = $label;
            $mainCounts[] = (int)$r['c'];
        }
    }
}

// Aggregations by dimension
function fetchAgg($mysqli, $field, $where) {
    $data = [];
    $sql = "SELECT {$field} AS k, COUNT(*) AS c
            FROM production_log
            WHERE {$where}
            GROUP BY {$field}
            ORDER BY c DESC";
    if ($res = $mysqli->query($sql)) {
        while ($r = $res->fetch_assoc()) {
            $key = $r['k'] === null || $r['k'] === '' ? '(n/a)' : $r['k'];
            $data[$key] = (int)$r['c'];
        }
    }
    return $data;
}

$aggSerial = $showSerial    ? fetchAgg($mysqli, 'serial',    $where) : [];
$aggVar    = $showVariety   ? fetchAgg($mysqli, 'variety',   $where) : [];
$aggPack   = $showPackaging ? fetchAgg($mysqli, 'packaging', $where) : [];
$aggSize   = $showSize      ? fetchAgg($mysqli, 'size',      $where) : [];
$aggGrower = $showGrower    ? fetchAgg($mysqli, 'grower',    $where) : [];

function jsArray($arr) {
    return json_encode(array_values($arr), JSON_UNESCAPED_UNICODE);
}
function jsLabels($arr) {
    return json_encode(array_keys($arr), JSON_UNESCAPED_UNICODE);
}

$mainLabelsJson = json_encode($mainLabels, JSON_UNESCAPED_UNICODE);
$mainCountsJson = json_encode($mainCounts, JSON_UNESCAPED_UNICODE);

$serialLabelsJson   = jsLabels($aggSerial);
$serialCountsJson   = jsArray($aggSerial);
$varLabelsJson      = jsLabels($aggVar);
$varCountsJson      = jsArray($aggVar);
$packLabelsJson     = jsLabels($aggPack);
$packCountsJson     = jsArray($aggPack);
$sizeLabelsJson     = jsLabels($aggSize);
$sizeCountsJson     = jsArray($aggSize);
$growerLabelsJson   = jsLabels($aggGrower);
$growerCountsJson   = jsArray($aggGrower);

?>
<?php if (file_exists(__DIR__ . '/../includes/header.php')) include __DIR__ . '/../includes/header.php'; ?>
<?php if (file_exists(__DIR__ . '/../includes/sidebar.php')) include __DIR__ . '/../includes/sidebar.php'; ?>

<div class="container-fluid mt-3">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h3 class="mb-0">Keyence Production Dashboard</h3>
    <span class="text-muted small"><?= htmlspecialchars($rangeLabel) ?></span>
  </div>

  <form class="card mb-3 p-3" method="get">
    <div class="row g-2 align-items-center">
      <div class="col-md-4">
        <label class="form-label mb-1">Intervallo tempo</label>
        <select name="range" class="form-select form-select-sm">
          <option value="10m"   <?= $range === '10m'   ? 'selected' : '' ?>>Ultimi 10 minuti</option>
          <option value="today" <?= $range === 'today' ? 'selected' : '' ?>>Oggi</option>
          <option value="week"  <?= $range === 'week'  ? 'selected' : '' ?>>Ultimi 7 giorni</option>
          <option value="month" <?= $range === 'month' ? 'selected' : '' ?>>Ultimi 30 giorni</option>
        </select>
      </div>
      <div class="col-md-8">
        <label class="form-label mb-1">Dati da visualizzare</label>
        <div class="d-flex flex-wrap gap-3">
          <div class="form-check form-check-inline">
            <input class="form-check-input" type="checkbox" name="show_main" id="chkMain" value="1" <?= $showMainChart ? 'checked' : '' ?>>
            <label class="form-check-label" for="chkMain">Produzione oraria</label>
          </div>
          <div class="form-check form-check-inline">
            <input class="form-check-input" type="checkbox" name="show_variety" id="chkVariety" value="1" <?= $showVariety ? 'checked' : '' ?>>
            <label class="form-check-label" for="chkVariety">Variety</label>
          </div>
          <div class="form-check form-check-inline">
            <input class="form-check-input" type="checkbox" name="show_packaging" id="chkPack" value="1" <?= $showPackaging ? 'checked' : '' ?>>
            <label class="form-check-label" for="chkPack">Packaging</label>
          </div>
          <div class="form-check form-check-inline">
            <input class="form-check-input" type="checkbox" name="show_size" id="chkSize" value="1" <?= $showSize ? 'checked' : '' ?>>
            <label class="form-check-label" for="chkSize">Size</label>
          </div>
          <div class="form-check form-check-inline">
            <input class="form-check-input" type="checkbox" name="show_grower" id="chkGrower" value="1" <?= $showGrower ? 'checked' : '' ?>>
            <label class="form-check-label" for="chkGrower">Grower</label>
          </div>
        </div>
      </div>
      <div class="col-12 mt-2">
        <button class="btn btn-sm btn-primary">Aggiorna dashboard</button>
      </div>
    </div>
  </form>

  <div class="row g-3">
    <?php if ($showMainChart): ?>
    <div class="col-12">
      <div class="card shadow-sm">
        <div class="card-header"><strong>Produzione per ora</strong></div>
        <div class="card-body">
          <?php if (!empty($mainLabels)): ?>
            <canvas id="chartMain" height="120"></canvas>
          <?php else: ?>
            <p class="text-muted mb-0">Nessun dato.</p>
          <?php endif; ?>
        </div>
      </div>
    </div>
    <?php endif; ?>

    <?php if ($showVariety): ?>
    <div class="col-md-6">
      <div class="card shadow-sm">
        <div class="card-header"><strong>Variety</strong></div>
        <div class="card-body">
          <?php if (!empty($aggVar)): ?>
            <canvas id="chartVar" height="160"></canvas>
          <?php else: ?>
            <p class="text-muted mb-0">Nessun dato.</p>
          <?php endif; ?>
        </div>
      </div>
    </div>
    <?php endif; ?>

    <?php if ($showPackaging): ?>
    <div class="col-md-6">
      <div class="card shadow-sm">
        <div class="card-header"><strong>Packaging</strong></div>
        <div class="card-body">
          <?php if (!empty($aggPack)): ?>
            <canvas id="chartPack" height="160"></canvas>
          <?php else: ?>
            <p class="text-muted mb-0">Nessun dato.</p>
          <?php endif; ?>
        </div>
      </div>
    </div>
    <?php endif; ?>

    <?php if ($showSize): ?>
    <div class="col-md-6">
      <div class="card shadow-sm">
        <div class="card-header"><strong>Size</strong></div>
        <div class="card-body">
          <?php if (!empty($aggSize)): ?>
            <canvas id="chartSize" height="160"></canvas>
          <?php else: ?>
            <p class="text-muted mb-0">Nessun dato.</p>
          <?php endif; ?>
        </div>
      </div>
    </div>
    <?php endif; ?>

    <?php if ($showGrower): ?>
    <div class="col-md-6">
      <div class="card shadow-sm">
        <div class="card-header"><strong>Grower</strong></div>
        <div class="card-body">
          <?php if (!empty($aggGrower)): ?>
            <canvas id="chartGrower" height="160"></canvas>
          <?php else: ?>
            <p class="text-muted mb-0">Nessun dato.</p>
          <?php endif; ?>
        </div>
      </div>
    </div>
    <?php endif; ?>
  </div>
</div>

<script>
(function() {
  // Main production chart
  <?php if ($showMainChart && !empty($mainLabels)): ?>
  (function(){
    const ctx = document.getElementById('chartMain').getContext('2d');
    new Chart(ctx, {
      type: 'bar',
      data: {
        labels: <?= $mainLabelsJson ?>,
        datasets: [{
          label: 'Produzione',
          data: <?= $mainCountsJson ?>
        }]
      },
      options: {
        scales: {
          x: { title: { display: true, text: 'Ora' } },
          y: { title: { display: true, text: 'Conteggio' }, beginAtZero: true }
        }
      }
    });
  })();
  <?php endif; ?>

  // Helper to build simple bar charts
  function buildBar(id, labels, values, labelText) {
    const el = document.getElementById(id);
    if (!el) return;
    const ctx = el.getContext('2d');
    new Chart(ctx, {
      type: 'bar',
      data: {
        labels: labels,
        datasets: [{
          label: labelText,
          data: values
        }]
      },
      options: {
        indexAxis: 'y',
        scales: {
          x: { beginAtZero: true }
        }
      }
    });
  }

  <?php if ($showVariety && !empty($aggVar)): ?>
  buildBar('chartVar', <?= $varLabelsJson ?>, <?= $varCountsJson ?>, 'Variety');
  <?php endif; ?>

  <?php if ($showPackaging && !empty($aggPack)): ?>
  buildBar('chartPack', <?= $packLabelsJson ?>, <?= $packCountsJson ?>, 'Packaging');
  <?php endif; ?>

  <?php if ($showSize && !empty($aggSize)): ?>
  buildBar('chartSize', <?= $sizeLabelsJson ?>, <?= $sizeCountsJson ?>, 'Size');
  <?php endif; ?>

  <?php if ($showGrower && !empty($aggGrower)): ?>
  buildBar('chartGrower', <?= $growerLabelsJson ?>, <?= $growerCountsJson ?>, 'Grower');
  <?php endif; ?>
})();
</script>

