<?php
// Gesamtübersicht Inventur – alle Fahrzeuge & Geräte (ohne 'ausgesondert')

// --- Includes ---
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/nav.php';
require_once __DIR__ . '/includes/db.php';

// --- 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; }
  $m = new mysqli('localhost','DB_USER','DB_PASS','kd54698_cloud'); // Fallback
  if($m->connect_errno) die('DB-Fehler: '.$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();

// --- Fahrzeuge laden (optional nach Einheit) ---
$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();

// --- Prepared Statement für Gerätestats je Fahrzeug ---
// Wir matchen robust gegen mehrere Felder des Fahrzeugs (equals + LIKE),
// blenden 'ausgesondert' case-insensitive aus und summieren CAST(... AS UNSIGNED).
$baseSql = "
  SELECT
    COUNT(*) AS cnt,
    SUM(CAST(COALESCE(anzahl,'0')    AS UNSIGNED)) AS sol,
    SUM(CAST(COALESCE(anzahlist,'0') AS UNSIGNED)) AS ist,
    SUM(CASE
          WHEN CAST(COALESCE(anzahl,'0')    AS UNSIGNED)
             <> CAST(COALESCE(anzahlist,'0') AS UNSIGNED)
          THEN 1 ELSE 0
        END) AS diff_cnt
  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('%', ?, '%')
    )";
if($einheit) $baseSql .= " AND einheit = ?";

$statsStmt = $mysqli->prepare($baseSql);

// --- Übersicht berechnen ---
$rowsOut = [];
$totCnt=0; $totSol=0; $totIst=0; $totDiff=0;

foreach($fahrzeuge as $v){
  $fname = $v['fname'];
  $bez   = $v['bez'];
  $kurz  = $v['kurz'];
  $frn   = $v['frn'];
  $code  = $v['fzg_code'];

  if($einheit){
    $types = 'sssssssss' . 's'; // 9 + 1
    $bind  = [$frn,$bez,$kurz,$fname,$frn,$bez,$kurz,$fname,$code,$einheit];
  }else{
    $types = 'sssssssss'; // 9
    $bind  = [$frn,$bez,$kurz,$fname,$frn,$bez,$kurz,$fname,$code];
  }
  $statsStmt->bind_param($types, ...$bind);
  $statsStmt->execute();
  $res = $statsStmt->get_result();
  $row = $res->fetch_assoc() ?: ['cnt'=>0,'sol'=>0,'ist'=>0,'diff_cnt'=>0];

  $cnt = (int)$row['cnt'];
  $sol = (int)$row['sol'];
  $ist = (int)$row['ist'];
  $dif = (int)$row['diff_cnt'];
  $delta = $ist - $sol;

  $rowsOut[] = [
    'id'   => (int)$v['id'],
    'label'=> trim(($v['bez'] ?: ($v['fname'] ?: '—')) . ($v['frn'] ? ' — '.$v['frn'] : '')),
    'cnt'  => $cnt,
    'sol'  => $sol,
    'ist'  => $ist,
    'delta'=> $delta,
    'diff' => $dif
  ];

  $totCnt += $cnt; $totSol += $sol; $totIst += $ist; $totDiff += $dif;
}
$totDelta = $totIst - $totSol;

// Optional: nach größten Abweichungen sortieren (DESC)
// usort($rowsOut, fn($a,$b)=>($b['delta']<=>$a['delta']));

// --- UI ---
?>
<style>
  .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; }
  .muted{ color:#6b7280; }
  .table thead th{ position:sticky; top:0; background:#f8f9fa; z-index:2; }
  .sumbar{ display:flex; gap:.75rem; flex-wrap:wrap; }
  .sumbar .stat{ display:flex; gap:.5rem; align-items:center; padding:.5rem .75rem; border:1px solid #e5e7eb; border-radius:12px; background:#fff; }
</style>

<div class="container my-4">
  <div class="card inv-card">
    <div class="card-body">
      <div class="d-flex flex-wrap align-items-center justify-content-between mb-3">
        <div>
          <h1 class="h4 mb-0">Inventur – Gesamtübersicht</h1>
          <div class="muted small">Einheit: <?= $einheit ? h($einheit) : '—' ?></div>
        </div>
        <div class="sumbar">
          <div class="stat"><span class="muted">Fahrzeuge</span><strong><?= count($fahrzeuge) ?></strong></div>
          <div class="stat"><span class="muted">Geräte gesamt</span><strong><?= (int)$totCnt ?></strong></div>
          <div class="stat"><span class="muted">SOLL</span><strong><?= (int)$totSol ?></strong></div>
          <div class="stat"><span class="muted">IST</span><strong><?= (int)$totIst ?></strong></div>
          <?php $dc=$totDelta===0?'zero':($totDelta>0?'pos':'neg'); ?>
          <div class="stat"><span class="muted">Δ</span><span class="badge-delta <?= $dc ?>"><?= ($totDelta>=0?'+':'').$totDelta ?></span></div>
          <div class="stat"><span class="muted">Abweichungen</span><strong><?= (int)$totDiff ?></strong></div>
        </div>
      </div>

      <div class="table-responsive">
        <table class="table align-middle">
          <thead class="table-light">
            <tr>
              <th>Fahrzeug</th>
              <th class="text-end">Geräte</th>
              <th class="text-end">SOLL</th>
              <th class="text-end">IST</th>
              <th class="text-end">Δ</th>
              <th class="text-end">Abweichungen</th>
              <th class="text-end" style="width:160px;">Aktion</th>
            </tr>
          </thead>
          <tbody>
            <?php if(!$rowsOut): ?>
              <tr><td colspan="7" class="muted">Keine Fahrzeuge gefunden.</td></tr>
            <?php else:
              foreach($rowsOut as $r):
                $dc = $r['delta']===0?'zero':($r['delta']>0?'pos':'neg');
            ?>
              <tr>
                <td><strong><?= h($r['label']) ?></strong></td>
                <td class="text-end"><?= (int)$r['cnt'] ?></td>
                <td class="text-end"><?= (int)$r['sol'] ?></td>
                <td class="text-end"><?= (int)$r['ist'] ?></td>
                <td class="text-end"><span class="badge-delta <?= $dc ?>"><?= ($r['delta']>=0?'+':'').(int)$r['delta'] ?></span></td>
                <td class="text-end"><?= (int)$r['diff'] ?></td>
                <td class="text-end">
                  <a class="btn btn-sm btn-primary" href="inventur.php?fahrzeug_id=<?= (int)$r['id'] ?>">Öffnen</a>
                </td>
              </tr>
            <?php endforeach; endif; ?>
          </tbody>
          <?php if($rowsOut): ?>
          <tfoot class="table-light">
            <tr>
              <th>Gesamt</th>
              <th class="text-end"><?= (int)$totCnt ?></th>
              <th class="text-end"><?= (int)$totSol ?></th>
              <th class="text-end"><?= (int)$totIst ?></th>
              <?php $dc=$totDelta===0?'zero':($totDelta>0?'pos':'neg'); ?>
              <th class="text-end"><span class="badge-delta <?= $dc ?>"><?= ($totDelta>=0?'+':'').(int)$totDelta ?></span></th>
              <th class="text-end"><?= (int)$totDiff ?></th>
              <th></th>
            </tr>
          </tfoot>
          <?php endif; ?>
        </table>
      </div>

    </div>
  </div>
</div>

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