<?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','warehouse','supervisor','admin'])) { http_response_code(403); die('Forbidden'); }

require_once __DIR__ . '/../config/db_remote.php';
require_once __DIR__ . '/../includes/bin_label_print.php';
include '../includes/header.php';
include '../includes/sidebar.php';

$info = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $bin_id = isset($_POST['bin_id']) ? (int)$_POST['bin_id'] : 0;
    if ($bin_id <= 0) {
        $error = 'Please enter a valid BIN ID.';
    } else {
        $stmt = $mysqli->prepare("SELECT id, grower, date, variety, lot, quantity FROM bins_ingresso WHERE id = ? LIMIT 1");
        $stmt->bind_param('i', $bin_id);
        $stmt->execute();
        $res = $stmt->get_result();
        $row = $res->fetch_assoc();

        if (!$row) {
            $error = 'Bin ID not found.';
        } else {
            $ok = smp_print_zpl_for_bin($row, 0);
            if ($ok) {
                $info = 'Label reprinted successfully for BIN ID ' . htmlspecialchars((string)$bin_id);
            } else {
                $error = 'No labels printer configured in printer settings.';
            }
        }
    }
}
?>
<div class="container-fluid py-4">
  <h1 class="mb-4">Reprint Full Bin Label</h1>

  <?php if ($info): ?>
    <div class="alert alert-success"><?= $info ?></div>
  <?php endif; ?>
  <?php if ($error): ?>
    <div class="alert alert-danger"><?= $error ?></div>
  <?php endif; ?>

  <div class="card" style="max-width:480px;">
    <div class="card-header">Reprint by BIN ID</div>
    <div class="card-body">
      <form method="post">
        <div class="mb-3">
          <label class="form-label fw-semibold">BIN ID</label>
          <input type="number" name="bin_id" class="form-control" required>
          <div class="form-text">Enter the ID of the full bin (from the Full Bins Inventory list).</div>
        </div>
        <button class="btn btn-primary">Reprint Label</button>
        <a href="/smproduce/pages/bins_ingresso.php" class="btn btn-secondary ms-2">Back to Full Bins</a>
      </form>
    </div>
  </div>
</div>

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