
<?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';

// Ensure tables
@$mysqli->query("CREATE TABLE IF NOT EXISTS bins_ingresso (
  id INT AUTO_INCREMENT PRIMARY KEY,
  grower VARCHAR(100) NOT NULL,
  date DATE NOT NULL,
  variety VARCHAR(100) NOT NULL,
  quantity INT NOT NULL DEFAULT 0,
  status ENUM('AVAILABLE','IN_PRODUCTION','USED','SCRAP') DEFAULT 'AVAILABLE',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

@$mysqli->query("CREATE TABLE IF NOT EXISTS bins_produzione (
  id INT AUTO_INCREMENT PRIMARY KEY,
  grower VARCHAR(100) NOT NULL,
  date DATE NOT NULL,
  variety VARCHAR(100) NOT NULL,
  quantity INT NOT NULL DEFAULT 0,
  lot VARCHAR(50) NULL,
  line VARCHAR(50) NULL,
  operator VARCHAR(100) NULL,
  status ENUM('IN_PRODUCTION','COMPLETED') DEFAULT 'IN_PRODUCTION',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

$msg = null; $err = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action = $_POST['action'] ?? '';
  if ($action === 'assign') {
    $source_id = (int)($_POST['source_id'] ?? 0);
    $qty = max(0, (int)($_POST['assign_qty'] ?? 0));
    $lot = trim($_POST['lot'] ?? '');
    $line = trim($_POST['line'] ?? '');
    $operator = trim($_POST['operator'] ?? '');
    if ($source_id > 0 && $qty > 0 && $lot && $line && $operator) {
      $res = $mysqli->prepare("SELECT id, grower, date, variety, quantity FROM bins_ingresso WHERE id=? AND quantity>=?");
      $res->bind_param('ii', $source_id, $qty);
      $res->execute();
      $src = $res->get_result()->fetch_assoc();
      if ($src) {
        $newq = (int)$src['quantity'] - $qty;
        $upd = $mysqli->prepare("UPDATE bins_ingresso SET quantity=?, status='IN_PRODUCTION' WHERE id=?");
        $upd->bind_param('ii', $newq, $source_id);
        $upd->execute();
        $ins = $mysqli->prepare("INSERT INTO bins_produzione (grower, date, variety, quantity, lot, line, operator) VALUES (?,?,?,?,?,?,?)");
        $ins->bind_param('sssisss', $src['grower'], $src['date'], $src['variety'], $qty, $lot, $line, $operator);
        if ($ins->execute()) $msg = "Assigned $qty bin(s) to production.";
        else $err = "Insert failed: " . $mysqli->error;
      } else { $err = "Not enough quantity or not found."; }
    } else { $err = "Select row, quantity, lot, line and operator."; }
  }
  if ($action === 'complete') {
    $pid = (int)($_POST['prod_id'] ?? 0);
    if ($pid > 0) {
      $stmt = $mysqli->prepare("UPDATE bins_produzione SET status='COMPLETED' WHERE id=?");
      $stmt->bind_param('i', $pid);
      if ($stmt->execute()) $msg = "Production entry completed.";
    }
  }
}

$inv = $mysqli->query("SELECT id, grower, DATE_FORMAT(date,'%Y-%m-%d') AS date, variety, quantity, status FROM bins_ingresso WHERE quantity > 0 ORDER BY date DESC, grower ASC")->fetch_all(MYSQLI_ASSOC);
$prod = $mysqli->query("SELECT id, grower, DATE_FORMAT(date,'%Y-%m-%d') AS date, variety, quantity, lot, line, operator, status FROM bins_produzione ORDER BY created_at DESC")->fetch_all(MYSQLI_ASSOC);
?>
<?php include('../includes/header.php'); ?>
<?php include('../includes/sidebar.php'); ?>

<h3 class="mb-3">Daily Production</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="row g-3">
  <div class="col-lg-7">
    <div class="card h-100">
      <div class="card-header">Inventory (assign to production)</div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table id="tbl-inv" class="table table-striped table-hover mb-0 align-middle">
            <thead class="table-light">
              <tr>
                <th class="no-sort" style="width:44px;"></th>
                <th>ID</th><th>Grower</th><th>Date</th><th>Variety</th><th>Quantity</th><th>Assign</th>
              </tr>
              <tr>
                <th></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>
                <th><input class="form-control form-control-sm col-filter" data-col-index="5" placeholder="Filter"></th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($inv as $r): ?>
                <tr>
                  <td><input type="checkbox" class="form-check-input row-check" data-id="<?= (int)$r['id'] ?>"></td>
                  <td><?= (int)$r['id'] ?></td>
                  <td><?= htmlspecialchars($r['grower']) ?></td>
                  <td><?= htmlspecialchars($r['date']) ?></td>
                  <td><?= htmlspecialchars($r['variety']) ?></td>
                  <td><?= (int)$r['quantity'] ?></td>
                  <td>
                    <form method="post" class="row g-1">
                      <input type="hidden" name="action" value="assign">
                      <input type="hidden" name="source_id" value="<?= (int)$r['id'] ?>">
                      <div class="col-3"><input type="number" name="assign_qty" class="form-control form-control-sm" min="1" max="<?= (int)$r['quantity'] ?>" placeholder="Qty" required></div>
                      <div class="col-3"><input type="text" name="lot" class="form-control form-control-sm" placeholder="Lot" required></div>
                      <div class="col-3"><input type="text" name="line" class="form-control form-control-sm" placeholder="Line" required></div>
                      <div class="col-3"><input type="text" name="operator" class="form-control form-control-sm" placeholder="Operator" required></div>
                    </form>
                  </td>
                </tr>
              <?php endforeach; ?>
              <?php if (empty($inv)): ?>
                <tr><td colspan="7" class="text-center text-muted py-4">No inventory available.</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
  <div class="col-lg-5">
    <div class="card h-100">
      <div class="card-header">Production entries</div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table id="tbl-prod" class="table table-striped table-hover mb-0 align-middle">
            <thead class="table-light">
              <tr>
                <th>Grower</th><th>Variety</th><th>Lot</th><th>Line</th><th>Qty</th><th>Status</th><th>Action</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($prod as $p): ?>
                <tr>
                  <td><?= htmlspecialchars($p['grower']) ?></td>
                  <td><?= htmlspecialchars($p['variety']) ?></td>
                  <td><?= htmlspecialchars($p['lot']) ?></td>
                  <td><?= htmlspecialchars($p['line']) ?></td>
                  <td><?= (int)$p['quantity'] ?></td>
                  <td><?= htmlspecialchars($p['status']) ?></td>
                  <td>
                    <?php if ($p['status'] === 'IN_PRODUCTION'): ?>
                    <form method="post">
                      <input type="hidden" name="action" value="complete">
                      <input type="hidden" name="prod_id" value="<?= (int)$p['id'] ?>">
                      <button class="btn btn-sm btn-success">Complete</button>
                    </form>
                    <?php endif; ?>
                  </td>
                </tr>
              <?php endforeach; ?>
              <?php if (empty($prod)): ?>
                <tr><td colspan="7" class="text-center text-muted py-4">No production entries.</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
const t1 = initManagedTable('#tbl-inv');
const t2 = initManagedTable('#tbl-prod');
</script>

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