<?php
// cart.php – Warenkorb (einheitsgebunden) mit Bestellerstellung
ob_start();
session_start();

require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/nav.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. Bitte neu anmelden.</div></div>";
  include 'includes/footer.php'; exit;
}

// CSRF
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']);

// Lieferanten (optional)
$lieferanten = [];
if ($resL = $conn->query("SELECT name FROM lieferanten WHERE aktiv=1 ORDER BY name ASC")) {
  while($r=$resL->fetch_assoc()){ $lieferanten[] = $r['name']; }
}

/* -----------------------------------------------------------
   1) Offenen Warenkorb der eigenen Einheit + User holen/erstellen
----------------------------------------------------------- */
$cart = null;
$st = $conn->prepare("SELECT * FROM warenkoerbe WHERE einheit=? AND user_id=? AND status='Offen' LIMIT 1");
$st->bind_param("si", $user_einheit, $user_id);
$st->execute();
$cart = $st->get_result()->fetch_assoc();
$st->close();

if (!$cart) {
  $ins = $conn->prepare("INSERT INTO warenkoerbe (einheit,user_id,status,erstellt_am) VALUES (?,?, 'Offen', NOW())");
  $ins->bind_param("si", $user_einheit, $user_id);
  $ins->execute();
  $cart_id = $ins->insert_id;
  $ins->close();

  $st = $conn->prepare("SELECT * FROM warenkoerbe WHERE id=? LIMIT 1");
  $st->bind_param("i", $cart_id);
  $st->execute();
  $cart = $st->get_result()->fetch_assoc();
  $st->close();
}
$cart_id = (int)$cart['id'];

/* -----------------------------------------------------------
   2) Actions (Add / Update / Delete / Submit)
----------------------------------------------------------- */
if ($_SERVER['REQUEST_METHOD']==='POST') {
  if (!hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf'] ?? '')) {
    $_SESSION['flash_err'] = 'Sicherheitsprüfung fehlgeschlagen (CSRF).';
    header("Location: cart.php"); exit;
  }
  $action = $_POST['action'] ?? '';

  // Position hinzufügen
  if ($action === 'add_item') {
    $artikel = trim($_POST['artikel_nr'] ?? '');
    $bez     = trim($_POST['bezeichnung'] ?? '');
    $menge   = (float)($_POST['menge'] ?? 1);
    $einh    = trim($_POST['einheit_text'] ?? 'Stk');

    if ($artikel!=='' && $bez!=='' && $menge>0) {
      $stmt = $conn->prepare("
        INSERT INTO warenkorb_positionen (warenkorb_id, artikel_nr, bezeichnung, menge, einheit_text, erstellt_am)
        VALUES (?,?,?,?,?, NOW())
      ");
      $stmt->bind_param("issds", $cart_id, $artikel, $bez, $menge, $einh);
      $stmt->execute();
      $_SESSION['flash_ok'] = 'Position hinzugefügt.';
    } else {
      $_SESSION['flash_err'] = 'Bitte Artikel, Bezeichnung und Menge prüfen.';
    }
    header("Location: cart.php"); exit;
  }

  // Menge aktualisieren
  if ($action === 'upd_qty') {
    $pos_id = (int)($_POST['pos_id'] ?? 0);
    $menge  = (float)($_POST['menge'] ?? 0);
    if ($pos_id>0 && $menge>0) {
      $stmt = $conn->prepare("UPDATE warenkorb_positionen SET menge=? WHERE id=? AND warenkorb_id=?");
      $stmt->bind_param("dii", $menge, $pos_id, $cart_id);
      $stmt->execute();
      $_SESSION['flash_ok'] = 'Menge aktualisiert.';
    } else {
      $_SESSION['flash_err'] = 'Ungültige Menge.';
    }
    header("Location: cart.php"); exit;
  }

  // Position löschen
  if ($action === 'del_item') {
    $pos_id = (int)($_POST['pos_id'] ?? 0);
    if ($pos_id>0) {
      $stmt = $conn->prepare("DELETE FROM warenkorb_positionen WHERE id=? AND warenkorb_id=?");
      $stmt->bind_param("ii", $pos_id, $cart_id);
      $stmt->execute();
      $_SESSION['flash_ok'] = 'Position entfernt.';
    }
    header("Location: cart.php"); exit;
  }

  // Warenkorb absenden -> Bestellung erzeugen (einheitsgebunden)
  if ($action === 'submit_cart') {
    $lieferant = trim($_POST['bestellt_bei'] ?? '');
    $bemerkung = trim($_POST['bemerkung'] ?? '');

    // Positionen holen
    $pos = $conn->prepare("SELECT * FROM warenkorb_positionen WHERE warenkorb_id=?");
    $pos->bind_param("i", $cart_id);
    $pos->execute();
    $rows = $pos->get_result()->fetch_all(MYSQLI_ASSOC);
    $pos->close();

    if ($lieferant==='' ) {
      $_SESSION['flash_err'] = 'Bitte einen Lieferanten angeben.';
      header("Location: cart.php"); exit;
    }
    if (!$rows) {
      $_SESSION['flash_err'] = 'Warenkorb ist leer.';
      header("Location: cart.php"); exit;
    }

    $conn->begin_transaction();
    try {
      // Bestellung
      $ins = $conn->prepare("
        INSERT INTO bestellungen (einheit, bestellt_von, bestellt_bei, status, bemerkung, erstellt_am)
        VALUES (?,?,?, 'In Bearbeitung', ?, NOW())
      ");
      $ins->bind_param("siss", $user_einheit, $user_id, $lieferant, $bemerkung);
      $ins->execute();
      $order_id = $ins->insert_id;
      $ins->close();

      // Positionen kopieren
      $insP = $conn->prepare("
        INSERT INTO bestellung_positionen (bestellung_id, artikel_nr, bezeichnung, menge, einheit_text)
        VALUES (?,?,?,?,?)
      ");
      foreach($rows as $r){
        $insP->bind_param("issds", $order_id, $r['artikel_nr'], $r['bezeichnung'], $r['menge'], $r['einheit_text']);
        $insP->execute();
      }
      $insP->close();

      // Log
      $log = $conn->prepare("
        INSERT INTO bestellung_logs (bestellung_id, user_id, aktion, feld, altwert, neuwert, erstellt_am)
        VALUES (?,?,?,?,?,?, NOW())
      ");
      $aktion='CREATE_ORDER'; $feld='from_cart'; $alt=null; $neu='Warenkorb '.$cart_id;
      $log->bind_param("iissss", $order_id, $user_id, $aktion, $feld, $alt, $neu);
      $log->execute();
      $log->close();

      // Warenkorb schließen
      $upd = $conn->prepare("UPDATE warenkoerbe SET status='Abgeschlossen', abgeschlossen_am=NOW() WHERE id=?");
      $upd->bind_param("i", $cart_id);
      $upd->execute();
      $upd->close();

      $conn->commit();

      $_SESSION['flash_ok'] = "Bestellung #$order_id erstellt.";
      header("Location: orders.php"); exit;
    } catch (Throwable $e) {
      $conn->rollback();
      $_SESSION['flash_err'] = 'Fehler beim Erstellen der Bestellung.';
      header("Location: cart.php"); exit;
    }
  }
}

/* -----------------------------------------------------------
   3) Positionen laden + kleine KPIs
----------------------------------------------------------- */
$items = null;
$st = $conn->prepare("SELECT * FROM warenkorb_positionen WHERE warenkorb_id=? ORDER BY id DESC");
$st->bind_param("i", $cart_id);
$st->execute();
$items = $st->get_result();

$kpi_count = $items->num_rows ?? 0;
$items->data_seek(0);
$total_qty = 0.0;
while($t = $items->fetch_assoc()){ $total_qty += (float)$t['menge']; }
$items->data_seek(0);
?>
<style>
  .kpi-card{border:1px solid #eee;border-radius:14px;padding:16px;background:#fff}
  .kpi-val{font-size:1.3rem;font-weight:700}
  .kpi-sub{font-size:.9rem;color:#6c757d}
</style>

<div class="container py-4">
  <div class="d-flex align-items-center justify-content-between mb-3">
    <div>
      <h1 class="h4 mb-0">Warenkorb
        <small class="text-muted">#<?= (int)$cart_id ?></small>
      </h1>
      <div class="text-muted small">Einheit: <span class="badge text-bg-secondary"><?= h($user_einheit) ?></span></div>
    </div>
    <div class="d-flex gap-2">
      <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#submitModal" <?= ($kpi_count ? '' : 'disabled') ?>>✅ Bestellung erstellen</button>
      <a class="btn btn-outline-secondary" href="orders.php">📦 Bestellungen</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; ?>

  <!-- KPIs -->
  <div class="row g-3 mb-3">
    <div class="col-6 col-md-3"><div class="kpi-card"><div class="kpi-sub">Positionen</div><div class="kpi-val"><?= (int)$kpi_count ?></div></div></div>
    <div class="col-6 col-md-3"><div class="kpi-card"><div class="kpi-sub">Gesamtmenge</div><div class="kpi-val"><?= rtrim(rtrim(number_format($total_qty,2,'.',''), '0'),'.') ?></div></div></div>
    <div class="col-6 col-md-3"><div class="kpi-card"><div class="kpi-sub">Status</div><div class="kpi-val"><span class="badge bg-primary">Offen</span></div></div></div>
    <div class="col-6 col-md-3"><div class="kpi-card"><div class="kpi-sub">Erstellt am</div><div class="kpi-val"><?= $cart['erstellt_am'] ? date('d.m.Y H:i', strtotime($cart['erstellt_am'])) : '—' ?></div></div></div>
  </div>

  <!-- Position hinzufügen -->
  <div class="card shadow-sm">
    <div class="card-body">
      <form class="row gy-2 gx-2 align-items-end" method="post">
        <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
        <input type="hidden" name="action" value="add_item">
        <div class="col-12 col-md-3">
          <label class="form-label">Artikel-Nr.</label>
          <input name="artikel_nr" class="form-control" placeholder="z. B. 4711-ABC" required>
        </div>
        <div class="col-12 col-md-5">
          <label class="form-label">Bezeichnung</label>
          <input name="bezeichnung" class="form-control" placeholder="z. B. Einsatzhandschuh Größe 9" required>
        </div>
        <div class="col-6 col-md-2">
          <label class="form-label">Menge</label>
          <input name="menge" type="number" step="0.01" min="0.01" value="1" class="form-control" required>
        </div>
        <div class="col-6 col-md-1">
          <label class="form-label">Einheit</label>
          <input name="einheit_text" class="form-control" value="Stk">
        </div>
        <div class="col-12 col-md-1 d-grid">
          <button class="btn btn-primary">➕</button>
        </div>
      </form>
    </div>
  </div>

  <!-- Positionstabelle -->
  <div class="card shadow-sm mt-3">
    <div class="table-responsive">
      <table class="table table-hover align-middle mb-0">
        <thead class="table-light">
          <tr>
            <th style="width:70px">#</th>
            <th style="width:160px">Artikel</th>
            <th>Bezeichnung</th>
            <th class="text-end" style="width:220px">Menge</th>
            <th style="width:100px">Einheit</th>
            <th style="width:160px" class="text-end">Aktion</th>
          </tr>
        </thead>
        <tbody>
        <?php if ($kpi_count): $items->data_seek(0); while($it=$items->fetch_assoc()): ?>
          <tr>
            <td class="text-muted">#<?= (int)$it['id'] ?></td>
            <td class="text-monospace"><?= h($it['artikel_nr']) ?></td>
            <td><?= h($it['bezeichnung']) ?></td>
            <td class="text-end">
              <form class="d-inline-flex gap-1 justify-content-end" method="post">
                <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
                <input type="hidden" name="action" value="upd_qty">
                <input type="hidden" name="pos_id" value="<?= (int)$it['id'] ?>">
                <input name="menge" type="number" step="0.01" min="0.01"
                       value="<?= h($it['menge']) ?>"
                       class="form-control form-control-sm text-end" style="max-width:100px">
                <button class="btn btn-sm btn-outline-primary" title="Menge speichern">💾</button>
              </form>
            </td>
            <td><?= h($it['einheit_text']) ?></td>
            <td class="text-end">
              <form class="d-inline" method="post" onsubmit="return confirm('Position entfernen?');">
                <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
                <input type="hidden" name="action" value="del_item">
                <input type="hidden" name="pos_id" value="<?= (int)$it['id'] ?>">
                <button class="btn btn-sm btn-outline-danger">🗑️ Entfernen</button>
              </form>
            </td>
          </tr>
        <?php endwhile; else: ?>
          <tr><td colspan="6" class="text-center text-muted py-4">Noch keine Positionen im Warenkorb.</td></tr>
        <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- Modal: Bestellung erstellen -->
<div class="modal fade" id="submitModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <form class="modal-content" method="post">
      <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
      <input type="hidden" name="action" value="submit_cart">
      <div class="modal-header">
        <h5 class="modal-title">Bestellung erstellen</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="mb-3">
          <label class="form-label">Bestellt bei</label>
          <input name="bestellt_bei" class="form-control" list="dl_lief" placeholder="Lieferant (Pflichtfeld)" required>
          <datalist id="dl_lief">
            <?php foreach($lieferanten as $n): ?>
              <option value="<?= h($n) ?>"></option>
            <?php endforeach; ?>
          </datalist>
        </div>
        <div class="mb-3">
          <label class="form-label">Bemerkung (optional)</label>
          <textarea name="bemerkung" class="form-control" rows="3" placeholder="z. B. Projekt/Referenz, Lieferhinweise …"></textarea>
        </div>
        <div class="alert alert-info small mb-0">
          Die Positionen deines Warenkorbs werden in eine neue Bestellung kopiert.
          Dein Warenkorb wird anschließend <strong>abgeschlossen</strong>.
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-success">✅ Bestellung erstellen</button>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Abbrechen</button>
      </div>
    </form>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<?php ob_end_flush(); ?>
