<?php
// Inventur – SOLL/IST je Fahrzeug (Fahrzeugliste aus ffw_fahrzeuge)
// “ausgesondert” wird ausgeblendet und nicht aktualisiert.
// WICHTIG: Beim Speichern wird NUR anzahlist (IST) aktualisiert. anzahl (SOLL) bleibt unverändert.

// --- Includes ----------------------------------------------------------
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/nav.php';
require_once __DIR__ . '/includes/db.php';   // stellt $conn oder $mysqli bereit

// --- DB-Helper ---------------------------------------------------------
/** @return mysqli */
function db(){
    static $m = null;
    if ($m instanceof mysqli) return $m;
    if (isset($GLOBALS['conn']) && $GLOBALS['conn'] instanceof mysqli) { $m = $GLOBALS['conn']; $m->set_charset('utf8mb4'); return $m; }
    if (isset($GLOBALS['mysqli']) && $GLOBALS['mysqli'] instanceof mysqli){ $m = $GLOBALS['mysqli']; $m->set_charset('utf8mb4'); return $m; }
    // Fallback ggf. entfernen, wenn includes/db.php immer verbindet
    $m = new mysqli('localhost', 'DB_USER', 'DB_PASS', 'kd54698_cloud');
    if ($m->connect_errno) die('DB-Verbindungsfehler: '.$m->connect_error);
    $m->set_charset('utf8mb4'); return $m;
}
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

// --- Session / Mandant ---
if (session_status() === PHP_SESSION_NONE) session_start();
$einheit = $_SESSION['einheit'] ?? null;

$mysqli = db();

// --- Fahrzeugliste -----------------------------------------------------
$params = []; $types = '';
$sqlVeh = "SELECT
             id,
             COALESCE(fahrzeugname,'')         AS fname,
             COALESCE(fahrzeugbezeichnung,'')  AS bez,
             COALESCE(fahrzeugkurz,'')         AS kurz,
             COALESCE(funkrufname,'')          AS frn,
             COALESCE(barcode_fzg,'')          AS fzg_code,
             COALESCE(einheit,'')              AS einheit
           FROM ffw_fahrzeuge";
$where = [];
if ($einheit){ $where[]="einheit=?"; $params[]=$einheit; $types.='s'; }
if ($where) $sqlVeh .= " WHERE ".implode(' AND ',$where);
$sqlVeh .= " ORDER BY bez ASC, frn ASC";

$stmtVeh = $mysqli->prepare($sqlVeh);
if ($params) $stmtVeh->bind_param($types, ...$params);
$stmtVeh->execute();
$resVeh = $stmtVeh->get_result();
$fahrzeuge = $resVeh->fetch_all(MYSQLI_ASSOC);
$stmtVeh->close();

// --- Auswahl Fahrzeug -------------
$fahrzeug_id = isset($_GET['fahrzeug_id']) ? (int)$_GET['fahrzeug_id'] : null;
$currentVeh = null;
if ($fahrzeuge){
  if ($fahrzeug_id){
    foreach($fahrzeuge as $v){ if ((int)$v['id']===$fahrzeug_id){ $currentVeh=$v; break; } }
  }
  if(!$currentVeh) $currentVeh = $fahrzeuge[0];
}

// --- Speichern (NUR IST -> anzahlist) ---------------------------------
$updated=0; $errors=[];
if($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['ist']) && is_array($_POST['ist'])){
  $mysqli->begin_transaction();
  try{
    // anzahl (SOLL) wird NICHT verändert
    $sqlUp = "UPDATE ffw_geraete
              SET anzahlist=?, laenderung=?
              WHERE id=?
                AND LOWER(COALESCE(status,'')) <> 'ausgesondert'";
    if ($einheit) $sqlUp .= " AND einheit=?";
    $stmtUp = $mysqli->prepare($sqlUp);
    if(!$stmtUp) throw new Exception($mysqli->error);

    $ts = date('Y-m-d H:i:s');
    foreach($_POST['ist'] as $idRaw=>$istRaw){
      $id  = (int)$idRaw;
      $ist = trim((string)$istRaw);
      if($ist==='' || !preg_match('/^\d+$/',$ist)) $ist='0';

      if ($einheit) $stmtUp->bind_param('ssis', $ist, $ts, $id, $einheit); // s,s,i,s
      else          $stmtUp->bind_param('ssi',  $ist, $ts, $id);           // s,s,i

      if(!$stmtUp->execute()){ $errors[]="Update-Fehler ID $id: ".$stmtUp->error; }
      else                   { $updated += $stmtUp->affected_rows; }
    }
    if($errors) $mysqli->rollback(); else $mysqli->commit();
  }catch(Throwable $e){
    $mysqli->rollback();
    $errors[]="Transaktion abgebrochen: ".$e->getMessage();
  }
  // Fahrzeugauswahl erhalten
  $fahrzeug_id = (int)($_POST['fahrzeug_id'] ?? 0);
  if ($fahrzeug_id){
    foreach($fahrzeuge as $v){ if((int)$v['id']===$fahrzeug_id){ $currentVeh=$v; break; } }
  }
}

// --- Geräte laden (robustes Matching, ausgesondert raus) ---------------
$rows=[];
if($currentVeh){
  $fname = $currentVeh['fname'];
  $bez   = $currentVeh['bez'];
  $kurz  = $currentVeh['kurz'];
  $frn   = $currentVeh['frn'];
  $code  = $currentVeh['fzg_code'];

  $sqlG = "SELECT id, barcode, bezeichnung, gr,
                  COALESCE(anzahl,'0')    AS anzahl,
                  COALESCE(anzahlist,'0') AS anzahlist,
                  COALESCE(lscan,'0')     AS lscan
           FROM ffw_geraete
           WHERE LOWER(COALESCE(status,'')) <> 'ausgesondert'
             AND (
               fahrzeug = ? OR fahrzeug = ? OR fahrzeug = ? OR fahrzeug = ?
               OR fahrzeug LIKE CONCAT('%', ?, '%')
               OR fahrzeug LIKE CONCAT('%', ?, '%')
               OR fahrzeug LIKE CONCAT('%', ?, '%')
               OR fahrzeug LIKE CONCAT('%', ?, '%')
               OR fahrzeug LIKE CONCAT('%', ?, '%')
             )";
  $types = 'sssssssss';
  $params= [$frn,$bez,$kurz,$fname,$frn,$bez,$kurz,$fname,$code];
  if ($einheit){ $sqlG.=" AND einheit=?"; $types.='s'; $params[]=$einheit; }
  $sqlG.=" ORDER BY gr ASC, id ASC";

  $stmtG=$mysqli->prepare($sqlG);
  $stmtG->bind_param($types, ...$params);
  $stmtG->execute();
  $resG=$stmtG->get_result();
  $rows=$resG->fetch_all(MYSQLI_ASSOC);
  $stmtG->close();
}

// --- Summen vorbereiten -----------
$sumSol = 0; $sumIst = 0;
foreach($rows as $r){ $sumSol+=(int)preg_replace('/\D/','',$r['anzahl']); $sumIst+=(int)preg_replace('/\D/','',$r['anzahlist']); }
$sumDelta = $sumIst - $sumSol;
?>
<style>
  /* dezente UI-Verbesserungen */
  .inv-card{ border-radius:14px; box-shadow:0 8px 24px rgba(2,6,23,.06); }
  .badge-delta{ font-variant-numeric: tabular-nums; }
  .badge-delta.zero{ background:#e9ecef; color:#495057; }
  .badge-delta.pos{ background:#e6f6ed; color:#107e3e; border:1px solid #c7ebd3; }
  .badge-delta.neg{ background:#fde7e9; color:#b42318; border:1px solid #fac5cb; }
  .badge-scan{ background:#e6f6ed; color:#107e3e; border:1px solid #c7ebd3; font-size:.75rem; padding:.15rem .4rem; border-radius:.5rem; }
  tr.has-diff{ background:linear-gradient(0deg, rgba(255,235,235,.35), rgba(255,235,235,.0)); }
  .qty{ max-width:110px; }
  .toolbar .stat{ display:flex; gap:.5rem; align-items:center; padding:.5rem .75rem; border:1px solid #e5e7eb; border-radius:12px; }
  .toolbar .btn-scan{ display:flex; gap:.5rem; align-items:center; }
  .sticky-save{ position:sticky; bottom:0; background:#fff; border-top:1px solid #e5e7eb; padding:12px; display:flex; gap:8px; justify-content:flex-end; z-index:5; }
  .btn-ghost{ background:#fff; border:1px solid #e5e7eb; }
  .muted{ color:#6b7280; }
  .col-gr{ min-width: 80px; }
  .legend { gap:.5rem; }
</style>

<div class="container my-4">
  <div class="card inv-card">
    <div class="card-body">
      <div class="d-flex flex-wrap gap-2 align-items-center justify-content-between mb-3">
        <div>
          <h1 class="h4 mb-0">Inventur</h1>
          <div class="muted small">Einheit: <?= $einheit ? h($einheit) : '—' ?></div>
        </div>

        <div class="d-flex flex-wrap gap-2 align-items-center">
          <div class="toolbar d-flex flex-wrap gap-2">
            <div class="stat"><span class="muted">Geräte</span><strong><?= count($rows) ?></strong></div>
            <div class="stat"><span class="muted">SOLL</span><strong id="sumSolTop"><?= (int)$sumSol ?></strong></div>
            <div class="stat"><span class="muted">IST</span><strong id="sumIstTop"><?= (int)$sumIst ?></strong></div>
            <div class="stat"><span class="muted">Δ</span>
              <span id="sumDeltaTop" class="badge badge-delta <?= $sumDelta===0?'zero':($sumDelta>0?'pos':'neg') ?>">
                <?= ($sumDelta>=0?'+':'').$sumDelta ?>
              </span>
            </div>
          </div>

          <!-- Neuer Button: Barcode-Scan-Seite -->
          <a href="inventur_scan.php" class="btn btn-success btn-scan" title="Hier können Sie mit Handscanner Barcodes scannen">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-upc-scan" viewBox="0 0 16 16" aria-hidden="true">
              <path d="M1.5 1a.5.5 0 0 0-.5.5V4h1V2h2V1H1.5zM12 1v1h2v2h1V1.5a.5.5 0 0 0-.5-.5H12zM1 12v2.5a.5.5 0 0 0 .5.5H4v-1H2v-2H1zm12 2h-2v1h2.5a.5.5 0 0 0 .5-.5V12h-1v2z"/>
              <path d="M1 7V5h1v6H1V7zm2 4V5h1v6H3zm2 0V5h1v6H5zm2 0V5h2v6H7zm3 0V5h1v6h-1zm2 0V5h1v6h-1z"/>
            </svg>
            <span>Barcode-Scan</span>
          </a>
        </div>
      </div>

      <div class="d-flex legend align-items-center mb-2 small">
        <span class="badge-scan">gescannt</span>
        <span class="muted">= Datensatz wurde per Scan/Erfassung bestätigt (lscan = 1). Tipp: Über <strong>Barcode-Scan</strong> können Sie mit Handscanner arbeiten.</span>
      </div>

      <?php if ($errors): ?>
        <div class="alert alert-danger"><strong>Fehler:</strong> <?= h(implode(' | ', $errors)) ?></div>
      <?php elseif ($_SERVER['REQUEST_METHOD']==='POST'): ?>
        <div class="alert alert-success">Änderungen gespeichert. (Betroffene Zeilen: <?= (int)$updated ?>)</div>
      <?php endif; ?>

      <form class="row g-2 mb-3" method="get" action="">
        <div class="col-12 col-md-8">
          <label class="form-label">Fahrzeug</label>
          <select name="fahrzeug_id" class="form-select" onchange="this.form.submit()">
            <?php foreach($fahrzeuge as $v):
              $label = trim(($v['bez'] ?: ($v['fname'] ?: '—')) . ($v['frn'] ? ' — '.$v['frn'] : ''));
            ?>
              <option value="<?= (int)$v['id'] ?>" <?= ($currentVeh && (int)$v['id']===(int)$currentVeh['id'] ? 'selected':'') ?>>
                <?= h($label) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-12 col-md-4 d-flex align-items-end">
          <button class="btn btn-ghost w-100" type="submit">Anzeigen</button>
        </div>
      </form>

      <?php if (!$currentVeh): ?>
        <div class="alert alert-info mb-0">Bitte zuerst ein Fahrzeug auswählen.</div>
      <?php else: ?>
        <form method="post" action="" id="invForm">
          <input type="hidden" name="fahrzeug_id" value="<?= (int)$currentVeh['id'] ?>">
          <div class="table-responsive">
            <table class="table align-middle">
              <thead class="table-light position-sticky top-0" style="z-index:4">
                <tr>
                  <th style="min-width:220px;">Bezeichnung</th>
                  <th class="col-gr">GR</th>
                  <th>Barcode</th>
                  <th class="text-end">SOLL</th>
                  <th class="text-end" style="width:200px;">IST (zählbar)</th>
                  <th class="text-end">Δ</th>
                  <th class="text-end" style="width:210px;">Aktion</th>
                </tr>
              </thead>
              <tbody id="inv-body">
              <?php if (!$rows): ?>
                <tr><td colspan="7" class="muted">Keine Geräte für dieses Fahrzeug gefunden.</td></tr>
              <?php else:
                  $sumSol = 0; $sumIst = 0;
                  foreach ($rows as $r):
                    $id  = (int)$r['id'];
                    $sol = (int)preg_replace('/\D/','',$r['anzahl']);
                    $ist = (int)preg_replace('/\D/','',$r['anzahlist']);
                    $sumSol += $sol; $sumIst += $ist;
                    $delta = $ist - $sol;
                    $deltaClass = $delta===0?'zero':($delta>0?'pos':'neg');
                    $scanned = (string)$r['lscan'] === '1';
              ?>
                <tr data-id="<?= $id ?>" class="<?= $delta===0?'':'has-diff' ?>">
                  <td>
                    <strong><?= h($r['bezeichnung']) ?></strong>
                    <?php if ($scanned): ?>
                      <span class="badge-scan ms-2" title="per Scan bestätigt">gescannt</span>
                    <?php endif; ?>
                  </td>
                  <td><?= h($r['gr'] ?? '') ?></td>
                  <td class="muted"><?= h($r['barcode']) ?></td>
                  <td class="text-end sol" data-sol="<?= $sol ?>"><?= $sol ?></td>
                  <td class="text-end">
                    <input type="number" name="ist[<?= $id ?>]" class="form-control text-end qty ist"
                           value="<?= $ist ?>" min="0" step="1" inputmode="numeric">
                  </td>
                  <td class="text-end">
                    <span class="badge badge-delta <?= $deltaClass ?> delta"><?= ($delta>=0?'+':'').$delta ?></span>
                  </td>
                  <td class="text-end">
                    <div class="btn-group btn-group-sm" role="group" aria-label="quick">
                      <button class="btn btn-ghost btn-dec" type="button">−1</button>
                      <button class="btn btn-ghost btn-inc" type="button">+1</button>
                      <button class="btn btn-outline-secondary btn-reset" type="button" title="IST = SOLL setzen">Reset</button>
                    </div>
                  </td>
                </tr>
              <?php endforeach; ?>
              <?php endif; ?>
              </tbody>

              <?php if ($rows): ?>
              <tfoot class="table-light">
                <tr>
                  <th colspan="3" class="text-end">Summe</th>
                  <th class="text-end" id="sum-sol"><?= (int)$sumSol ?></th>
                  <th class="text-end" id="sum-ist"><?= (int)$sumIst ?></th>
                  <?php $sumDelta = $sumIst-$sumSol; $dc = $sumDelta===0?'zero':($sumDelta>0?'pos':'neg'); ?>
                  <th class="text-end" colspan="2">
                    <span id="sum-delta" class="badge badge-delta <?= $dc ?>"><?= ($sumDelta>=0?'+':'').$sumDelta ?></span>
                  </th>
                </tr>
              </tfoot>
              <?php endif; ?>
            </table>
          </div>

          <?php if ($rows): ?>
          <div class="sticky-save">
            <div class="me-auto d-none d-md-block small muted">
              Tipp: Für schnelle Erfassung nutzen Sie den <a href="inventur_scan.php" class="link-primary">Barcode-Scan</a> (Handscanner).
            </div>
            <a href="inventur_scan.php" class="btn btn-outline-success">Barcode-Scan</a>
            <button type="submit" class="btn btn-primary btn-lg">Speichern</button>
          </div>
          <?php endif; ?>
        </form>
      <?php endif; ?>
    </div>
  </div>
</div>

<script>
(function(){
  const body = document.getElementById('inv-body');
  if(!body) return;

  function updateRow(tr){
    const solCell = tr.querySelector('.sol');
    const istInput= tr.querySelector('input.ist');
    const deltaBadge = tr.querySelector('.delta');
    if(!solCell || !istInput || !deltaBadge) return;

    const sol = parseInt(solCell.dataset.sol || '0', 10) || 0;
    let ist   = parseInt(istInput.value || '0', 10) || 0;
    const delta = ist - sol;

    // Badge text + style
    deltaBadge.textContent = (delta>=0?'+':'') + delta;
    deltaBadge.classList.remove('pos','neg','zero');
    deltaBadge.classList.add(delta===0 ? 'zero' : (delta>0 ? 'pos' : 'neg'));

    // Row highlight
    tr.classList.toggle('has-diff', delta !== 0);
  }

  function recalcTotals(){
    let sumSol=0, sumIst=0;
    body.querySelectorAll('tr').forEach(tr=>{
      const solCell = tr.querySelector('.sol');
      const istInput= tr.querySelector('input.ist');
      if(!solCell || !istInput) return;
      sumSol += (parseInt(solCell.dataset.sol||'0',10)||0);
      sumIst += (parseInt(istInput.value||'0',10)||0);
    });
    const d = sumIst - sumSol;

    const sumSolEl = document.getElementById('sum-sol');
    const sumIstEl = document.getElementById('sum-ist');
    const sumDeltaEl = document.getElementById('sum-delta');
    const sumSolTop = document.getElementById('sumSolTop');
    const sumIstTop = document.getElementById('sumIstTop');
    const sumDeltaTop = document.getElementById('sumDeltaTop');

    if(sumSolEl) sumSolEl.textContent = sumSol;
    if(sumIstEl) sumIstEl.textContent = sumIst;
    if(sumDeltaEl){
      sumDeltaEl.textContent = (d>=0?'+':'')+d;
      sumDeltaEl.classList.remove('pos','neg','zero');
      sumDeltaEl.classList.add(d===0?'zero':(d>0?'pos':'neg'));
    }
    if(sumSolTop) sumSolTop.textContent=sumSol;
    if(sumIstTop) sumIstTop.textContent=sumIst;
    if(sumDeltaTop){
      sumDeltaTop.textContent=(d>=0?'+':'')+d;
      sumDeltaTop.classList.remove('pos','neg','zero');
      sumDeltaTop.classList.add(d===0?'zero':(d>0?'pos':'neg'));
    }
  }

  body.addEventListener('input', e=>{
    if(e.target && e.target.classList.contains('ist')){
      const tr = e.target.closest('tr');
      updateRow(tr);
      recalcTotals();
    }
  });

  body.addEventListener('click', e=>{
    const tr = e.target.closest('tr');
    if(!tr) return;

    // +1 / -1
    if(e.target.classList.contains('btn-inc') || e.target.classList.contains('btn-dec')){
      const input = tr.querySelector('input.ist');
      let v = parseInt(input.value||'0',10)||0;
      v += e.target.classList.contains('btn-inc') ? 1 : -1;
      if(v<0) v=0;
      input.value = v;
      updateRow(tr); recalcTotals();
    }

    // Reset IST = SOLL (nur im Formular; speichern ändert weiterhin nur IST)
    if(e.target.classList.contains('btn-reset')){
      const sol = parseInt(tr.querySelector('.sol').dataset.sol||'0',10)||0;
      const input = tr.querySelector('input.ist');
      input.value = sol;
      updateRow(tr); recalcTotals();
    }
  });

  // Initial berechnen
  body.querySelectorAll('tr').forEach(updateRow);
  recalcTotals();
})();
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
