<?php
ob_start();
session_start();

include 'includes/header.php';
include 'includes/nav.php';
include 'includes/db.php';

if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit; }

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

$user_id      = (int)$_SESSION['user_id'];
$user_einheit = $_SESSION['einheit'] ?? '';

if ($user_einheit === '') {
  echo "<div class='container my-5'><div class='alert alert-danger'>Keine Einheit in der Session gesetzt.</div></div>";
  include 'includes/footer.php'; exit;
}

if (empty($_SESSION['csrf'])) { $_SESSION['csrf'] = bin2hex(random_bytes(16)); }
$CSRF = $_SESSION['csrf'];

// Flash
$ok = $_SESSION['flash_ok'] ?? null;
$er = $_SESSION['flash_err'] ?? null;
unset($_SESSION['flash_ok'], $_SESSION['flash_err']);

// Filter (Status)
$status  = $_GET['status'] ?? '';
$allowed = ['','In Bearbeitung','Geprüft','Bestellt'];

// SQL
$q = "SELECT b.*,
             (SELECT COUNT(*) FROM bestellung_positionen p WHERE p.bestellung_id=b.id) AS pos_cnt,
             CONCAT(COALESCE(u.vorname,''),' ',COALESCE(u.nachname,'')) AS besteller
      FROM bestellungen b
      LEFT JOIN users u ON u.id=b.bestellt_von
      WHERE b.einheit=?";
$params = [$user_einheit];
$types  = "s";

if (in_array($status, $allowed, true) && $status!=='') {
  $q .= " AND b.status=?";
  $params[] = $status;
  $types   .= "s";
}

// Nur nach created_at sortieren (existiert sicher)
$q .= " ORDER BY b.created_at DESC";

$stmt = $conn->prepare($q);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$res = $stmt->get_result();
?>
<!doctype html>
<html lang="de">
<head>
  <meta charset="utf-8">
  <title>Bestellungen</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container py-4">
  <div class="d-flex align-items-center justify-content-between mb-3">
    <h1 class="h4 mb-0">Bestellungen</h1>
    <div>
      <a class="btn btn-outline-secondary" href="cart.php">🛒 Mein Warenkorb</a>
    </div>
  </div>

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

  <form class="row g-2 mb-3" method="get">
    <div class="col-auto">
      <select name="status" class="form-select" onchange="this.form.submit()">
        <?php foreach($allowed as $s): ?>
          <option value="<?= h($s) ?>" <?= $status===$s ? 'selected':'' ?>>
            <?= $s==='' ? 'Alle Stati' : h($s) ?>
          </option>
        <?php endforeach; ?>
      </select>
    </div>
  </form>

  <div class="table-responsive">
    <table class="table table-sm table-hover align-middle">
      <thead class="table-light">
        <tr>
          <th>#</th>
          <th>Status</th>
          <th>Bestellt bei</th>
          <th>Pos.</th>
          <th>Besteller</th>
          <th>Erstellt</th>
          <th>Aktion</th>
        </tr>
      </thead>
      <tbody>
      <?php if ($res && $res->num_rows): while($b=$res->fetch_assoc()): ?>
        <tr>
          <td><?= (int)$b['id'] ?></td>
          <td>
            <?php
              $badge='secondary';
              if ($b['status']==='In Bearbeitung') $badge='warning';
              elseif ($b['status']==='Geprüft')    $badge='info';
              elseif ($b['status']==='Bestellt')   $badge='success';
            ?>
            <span class="badge text-bg-<?= $badge ?>"><?= h($b['status']) ?></span>
          </td>
          <td><?= h($b['bestellt_bei']) ?></td>
          <td><?= (int)$b['pos_cnt'] ?></td>
          <td><?= trim($b['besteller']) !== '' ? h($b['besteller']) : '–' ?></td>
          <td>
            <?= isset($b['created_at']) ? date('d.m.Y H:i', strtotime($b['created_at'])) : '–' ?>
          </td>
          <td>
            <a class="btn btn-sm btn-outline-primary" href="bestellung_view.php?id=<?= (int)$b['id'] ?>">Öffnen</a>
          </td>
        </tr>
      <?php endwhile; else: ?>
        <tr><td colspan="7" class="text-center text-muted py-4">Keine Bestellungen gefunden.</td></tr>
      <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
<?php ob_end_flush(); ?>
