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

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

// 1) Offenen Warenkorb des Users (pro Einheit) holen/erstellen
$stmt = $conn->prepare("SELECT * FROM warenkoerbe WHERE einheit=? AND user_id=? AND status='Offen' LIMIT 1");
$stmt->bind_param("si", $user_einheit, $user_id);
$stmt->execute();
$cart = $stmt->get_result()->fetch_assoc();

if (!$cart) {
  $ins = $conn->prepare("INSERT INTO warenkoerbe (einheit,user_id,status) VALUES (?,?, 'Offen')");
  $ins->bind_param("si", $user_einheit, $user_id);
  $ins->execute();
  $cart_id = $ins->insert_id;
  $ins->close();
  // Reload cart
  $stmt = $conn->prepare("SELECT * FROM warenkoerbe WHERE id=? LIMIT 1");
  $stmt->bind_param("i", $cart_id);
  $stmt->execute();
  $cart = $stmt->get_result()->fetch_assoc();
}
$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.';
    header("Location: cart.php"); exit;
  }
  $action = $_POST['action'] ?? '';

  // Add item
  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) VALUES (?,?,?,?,?)");
      $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;
  }

  // Update qty
  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;
  }

  // Remove item
  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;
  }

  // Submit cart -> create order
  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);

    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 anlegen
      $ins = $conn->prepare("INSERT INTO bestellungen (einheit,bestellt_von,bestellt_bei,status,bemerkung) VALUES (?,?,?,'In Bearbeitung',?)");
      $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) VALUES (?,?,?,?,?,?)");
      $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' WHERE id=?");
      $upd->bind_param("i", $cart_id);
      $upd->execute();

      // Optional: Warenkorb-Positionen leeren (Daten bleiben meist egal, Cart ist abgeschlossen)
      // $del = $conn->prepare("DELETE FROM warenkorb_positionen WHERE warenkorb_id=?");
      // $del->bind_param("i", $cart_id);
      // $del->execute();

      $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) Warenkorb-Positionen laden
$stmt = $conn->prepare("SELECT * FROM warenkorb_positionen WHERE warenkorb_id=? ORDER BY id DESC");
$stmt->bind_param("i", $cart_id);
$stmt->execute();
$items = $stmt->get_result();

?>
<!doctype html>
<html lang="de">
<head>
  <meta charset="utf-8">
  <title>Mein Warenkorb</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">Warenkorb <small class="text-muted">#<?= (int)$cart_id ?> (<?= h($user_einheit) ?>)</small></h1>
    <div>
      <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#submitModal" <?= ($items->num_rows ? '' : '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; ?>

  <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" required>
        </div>
        <div class="col-12 col-md-5">
          <label class="form-label">Bezeichnung</label>
          <input name="bezeichnung" class="form-control" 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>

  <div class="table-responsive mt-3">
    <table class="table table-sm align-middle">
      <thead class="table-light">
        <tr>
          <th>#</th>
          <th>Artikel</th>
          <th>Bezeichnung</th>
          <th class="text-end">Menge</th>
          <th>Einheit</th>
          <th style="width:180px">Aktion</th>
        </tr>
      </thead>
      <tbody>
      <?php if ($items && $items->num_rows): while($it=$items->fetch_assoc()): ?>
        <tr>
          <td><?= (int)$it['id'] ?></td>
          <td><?= h($it['artikel_nr']) ?></td>
          <td><?= h($it['bezeichnung']) ?></td>
          <td class="text-end">
            <form class="d-inline-flex gap-1" method="post" style="min-width:160px">
              <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:90px">
              <button class="btn btn-sm btn-outline-primary">💾</button>
            </form>
          </td>
          <td><?= h($it['einheit_text']) ?></td>
          <td>
            <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>

<!-- 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" 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"></textarea>
        </div>
        <p class="small text-muted mb-0">Die Positionen deines Warenkorbs werden in eine neue Bestellung kopiert. Dein Warenkorb wird anschließend abgeschlossen.</p>
      </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>
</body>
</html>
