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

session_start();
if (!isset($_SESSION['user'])) { header('Location: /smproduce/auth/login.php'); exit; }
$role = $_SESSION['user']['role'] ?? 'viewer';
if (!in_array($role, ['admin','production'])) { http_response_code(403); die('Forbidden'); }
require_once __DIR__ . '/../config/db_remote.php';

@$mysqli->query("CREATE TABLE IF NOT EXISTS casse_prodotte (
  id INT AUTO_INCREMENT PRIMARY KEY,
  barcode VARCHAR(80) NOT NULL,
  read_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  line VARCHAR(50) NULL,
  lot VARCHAR(50) NULL,
  weight DECIMAL(10,2) NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

$msg = null; $err = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'add') {
  $barcode = trim($_POST['barcode'] ?? '');
  $line = trim($_POST['line'] ?? '');
  $lot = trim($_POST['lot'] ?? '');
  if ($barcode) {
    $stmt = $mysqli->prepare("INSERT INTO casse_prodotte (barcode, line, lot) VALUES (?,?,?)");
    $stmt->bind_param('sss', $barcode, $line, $lot);
    if ($stmt->execute()) $msg = "Case added.";
    else $err = "Insert failed: " . $mysqli->error;
  } else $err = "Barcode required.";
}

$res = $mysqli->query("SELECT DATE_FORMAT(read_at,'%Y-%m-%d %H:%i:%s') AS read_at, barcode, line, lot, weight FROM casse_prodotte ORDER BY read_at DESC LIMIT 500");
$rows = $res ? $res->fetch_all(MYSQLI_ASSOC) : [];
?>
<?php include('../includes/header.php'); ?>
<?php include('../includes/sidebar.php'); ?>

<h3 class="mb-3">Cases Produced</h3>
<?php if ($msg): ?><div class="alert alert-success"><?= htmlspecialchars($msg) ?></div><?php endif; ?>
<?php if ($err): ?><div class="alert alert-danger"><?= htmlspecialchars($err) ?></div><?php endif; ?>

<div class="card mb-3">
  <div class="card-header">Manual add (optional)</div>
  <div class="card-body">
    <form method="post" class="row g-2">
      <input type="hidden" name="action" value="add">
      <div class="col-md-4"><input name="barcode" class="form-control" placeholder="Barcode"></div>
      <div class="col-md-3"><input name="line" class="form-control" placeholder="Line"></div>
      <div class="col-md-3"><input name="lot" class="form-control" placeholder="Lot"></div>
      <div class="col-md-2"><button class="btn btn-primary w-100">Add</button></div>
    </form>
  </div>
</div>

<div class="card">
  <div class="card-header d-flex justify-content-between align-items-center">
    <span>Latest scans</span>
  </div>
  <div class="card-body p-0">
    <div class="table-responsive">
      <table id="tbl-cases" class="table table-striped table-hover mb-0 align-middle">
        <thead class="table-light">
          <tr>
            <th>Read at</th><th>Barcode</th><th>Line</th><th>Lot</th><th>Weight</th>
          </tr>
          <tr>
            <th><input class="form-control form-control-sm col-filter" data-col-index="0" placeholder="Filter"></th>
            <th><input class="form-control form-control-sm col-filter" data-col-index="1" placeholder="Filter"></th>
            <th><input class="form-control form-control-sm col-filter" data-col-index="2" placeholder="Filter"></th>
            <th><input class="form-control form-control-sm col-filter" data-col-index="3" placeholder="Filter"></th>
            <th><input class="form-control form-control-sm col-filter" data-col-index="4" placeholder="Filter"></th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($rows as $r): ?>
            <tr>
              <td><?= htmlspecialchars($r['read_at']) ?></td>
              <td><?= htmlspecialchars($r['barcode']) ?></td>
              <td><?= htmlspecialchars($r['line']) ?></td>
              <td><?= htmlspecialchars($r['lot']) ?></td>
              <td><?= htmlspecialchars($r['weight'] ?? '') ?></td>
            </tr>
          <?php endforeach; ?>
          <?php if (empty($rows)): ?>
            <tr><td colspan="5" class="text-center text-muted py-4">No scans yet.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<script>
const t = initManagedTable('#tbl-cases');
</script>

<?php include('../includes/footer.php'); ?>
