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

// ID
$oid = (int)($_GET['id'] ?? 0);
if ($oid <= 0) {
  echo "<div class='container my-5'><div class='alert alert-danger'>Ungültige Bestell-ID.</div></div>";
  include 'includes/footer.php'; exit;
}

// Bestellung laden (nur eigene Einheit)
function load_order($conn, $oid, $einheit){
  $stmt = $conn->prepare("SELECT b.*, u.vorname, u.nachname
                          FROM bestellungen b
                          LEFT JOIN users u ON u.id=b.bestellt_von
                          WHERE b.id=? AND b.einheit=? LIMIT 1");
  $stmt->bind_param("is", $oid, $einheit);
  $stmt->execute();
  return $stmt->get_result()->fetch_assoc();
}
$order = load_order($conn, $oid, $user_einheit);
if (!$order) {
  echo "<div class='container my-5'><div class='alert alert-danger'>Bestellung nicht gefunden oder keine Berechtigung.</div></div>";
  include 'includes/footer.php'; exit;
}

// optional: Lieferanten für Datalist
$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'];

// Aktionen
$allowed_status = ['In Bearbeitung','Geprüft','Bestellt'];

if ($_SERVER['REQUEST_METHOD']==='POST') {
  if (!hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf'] ?? '')) {
    $_SESSION['flash_err'] = 'Sicherheitsprüfung fehlgeschlagen.';
    header("Location: bestellung_view.php?id=".$oid); exit;
  }
  $action = $_POST['action'] ?? '';

  // Status ändern
  if ($action === 'update_status') {
    $neu = $_POST['status'] ?? '';
    if (!in_array($neu, $allowed_status, true)) {
      $_SESSION['flash_err'] = 'Ungültiger Status.';
      header("Location: bestellung_view.php?id=".$oid); exit;
    }
    $alt = $order['status'];
    if ($neu !== $alt) {
      $stmt = $conn->prepare("UPDATE bestellungen SET status=? WHERE id=? AND einheit=?");
      $stmt->bind_param("sis", $neu, $oid, $user_einheit);
      $stmt->execute();

      // Log
      $log = $conn->prepare("INSERT INTO bestellung_logs (bestellung_id,user_id,aktion,feld,altwert,neuwert) VALUES (?,?,?,?,?,?)");
      $aktion='UPDATE_STATUS'; $feld='status';
      $log->bind_param("iissss", $oid, $user_id, $aktion, $feld, $alt, $neu);
      $log->execute();
      $_SESSION['flash_ok'] = 'Status aktualisiert.';
    } else {
      $_SESSION['flash_ok'] = 'Status unverändert.';
    }
    header("Location: bestellung_view.php?id=".$oid); exit;
  }

  // Kopf (Lieferant/Bemerkung) ändern
  if ($action === 'update_header') {
    $bestellt_bei = trim($_POST['bestellt_bei'] ?? '');
    $bemerkung    = trim($_POST['bemerkung'] ?? '');

    if ($bestellt_bei === '') {
      $_SESSION['flash_err'] = 'Lieferant darf nicht leer sein.';
      header("Location: bestellung_view.php?id=".$oid); exit;
    }

    // Änderungen ermitteln
    $changes = [];
    if ($bestellt_bei !== (string)$order['bestellt_bei']) {
      $changes[] = ['feld'=>'bestellt_bei','alt'=>$order['bestellt_bei'],'neu'=>$bestellt_bei];
    }
    if ($bemerkung !== (string)$order['bemerkung']) {
      $changes[] = ['feld'=>'bemerkung','alt'=>$order['bemerkung'],'neu'=>$bemerkung];
    }

    // Update
    $stmt = $conn->prepare("UPDATE bestellungen SET bestellt_bei=?, bemerkung=? WHERE id=? AND einheit=?");
    $stmt->bind_param("ssis", $bestellt_bei, $bemerkung, $oid, $user_einheit);
    $stmt->execute();

    // Logs
    if ($changes) {
      $log = $conn->prepare("INSERT INTO bestellung_logs (bestellung_id,user_id,aktion,feld,altwert,neuwert) VALUES (?,?,?,?,?,?)");
      $aktion='UPDATE_HEADER';
      foreach($changes as $c){
        $feld=$c['feld']; $alt=$c['alt']; $neu=$c['neu'];
        $log->bind_param("iissss", $oid, $user_id, $aktion, $feld, $alt, $neu);
        $log->execute();
      }
      $_SESSION['flash_ok'] = 'Kopfdaten gespeichert.';
    } else {
      $_SESSION['flash_ok'] = 'Keine Änderungen erkannt.';
    }
    header("Location: bestellung_view.php?id=".$oid); exit;
  }

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

    if ($artikel!=='' && $bez!=='' && $menge>0) {
      $ins = $conn->prepare("INSERT INTO bestellung_positionen (bestellung_id,artikel_nr,bezeichnung,menge,einheit_text) VALUES (?,?,?,?,?)");
      $ins->bind_param("issds", $oid, $artikel, $bez, $menge, $einh);
      $ins->execute();

      $log = $conn->prepare("INSERT INTO bestellung_logs (bestellung_id,user_id,aktion,feld,altwert,neuwert) VALUES (?,?,?,?,?,?)");
      $aktion='ADD_ITEM'; $feld='position';
      $alt=null; $neu=$artikel.' | '.$bez.' | '.$menge.' '.$einh;
      $log->bind_param("iissss", $oid, $user_id, $aktion, $feld, $alt, $neu);
      $log->execute();

      $_SESSION['flash_ok'] = 'Position hinzugefügt.';
    } else {
      $_SESSION['flash_err'] = 'Bitte Artikel, Bezeichnung und Menge prüfen.';
    }
    header("Location: bestellung_view.php?id=".$oid); exit;
  }

  // Position-Menge ändern
  if ($action === 'upd_qty') {
    $pos_id = (int)($_POST['pos_id'] ?? 0);
    $menge  = (float)($_POST['menge'] ?? 0);
    if ($pos_id>0 && $menge>0) {
      // alte Menge holen
      $s = $conn->prepare("SELECT menge FROM bestellung_positionen WHERE id=? AND bestellung_id=?");
      $s->bind_param("ii", $pos_id, $oid);
      $s->execute();
      $old = $s->get_result()->fetch_assoc();
      if ($old) {
        $alt = (string)$old['menge'];
        $stmt = $conn->prepare("UPDATE bestellung_positionen SET menge=? WHERE id=? AND bestellung_id=?");
        $stmt->bind_param("dii", $menge, $pos_id, $oid);
        $stmt->execute();

        $log = $conn->prepare("INSERT INTO bestellung_logs (bestellung_id,user_id,aktion,feld,altwert,neuwert) VALUES (?,?,?,?,?,?)");
        $aktion='UPDATE_ITEM'; $feld='menge:pos_'.$pos_id; $neu=(string)$menge;
        $log->bind_param("iissss", $oid, $user_id, $aktion, $feld, $alt, $neu);
        $log->execute();

        $_SESSION['flash_ok'] = 'Menge aktualisiert.';
      }
    } else {
      $_SESSION['flash_err'] = 'Ungültige Menge.';
    }
    header("Location: bestellung_view.php?id=".$oid); exit;
  }

  // Position löschen
  if ($action === 'del_item') {
    $pos_id = (int)($_POST['pos_id'] ?? 0);
    if ($pos_id>0) {
      // Position prüfen + Daten für Log
      $s = $conn->prepare("SELECT artikel_nr,bezeichnung,menge,einheit_text FROM bestellung_positionen WHERE id=? AND bestellung_id=?");
      $s->bind_param("ii", $pos_id, $oid);
      $s->execute();
      $row = $s->get_result()->fetch_assoc();
      if ($row) {
        $del = $conn->prepare("DELETE FROM bestellung_positionen WHERE id=? AND bestellung_id=?");
        $del->bind_param("ii", $pos_id, $oid);
        $del->execute();

        $log = $conn->prepare("INSERT INTO bestellung_logs (bestellung_id,user_id,aktion,feld,altwert,neuwert) VALUES (?,?,?,?,?,?)");
        $aktion='DELETE_ITEM'; $feld='position_id';
        $alt = $pos_id.': '.$row['artikel_nr'].' | '.$row['bezeichnung'].' | '.$row['menge'].' '.$row['einheit_text'];
        $neu = null;
        $log->bind_param("iissss", $oid, $user_id, $aktion, $feld, $alt, $neu);
        $log->execute();

        $_SESSION['flash_ok'] = 'Position entfernt.';
      }
    }
    header("Location: bestellung_view.php?id=".$oid); exit;
  }
}

// Daten für Anzeige neu laden
$order = load_order($conn, $oid, $user_einheit);

// Positionen
$stmt = $conn->prepare("SELECT * FROM bestellung_positionen WHERE bestellung_id=? ORDER BY id ASC");
$stmt->bind_param("i", $oid);
$stmt->execute();
$pos = $stmt->get_result();

// Logs
$stmt = $conn->prepare("SELECT l.*, CONCAT(COALESCE(u.vorname,''),' ',COALESCE(u.nachname,'')) AS uname
                        FROM bestellung_logs l
                        LEFT JOIN users u ON u.id=l.user_id
                        WHERE l.bestellung_id=?
                        ORDER BY l.created_at DESC");
$stmt->bind_param("i", $oid);
$stmt->execute();
$logs = $stmt->get_result();

// Badge
function status_badge($st){
  $badge='secondary';
  if ($st==='In Bearbeitung') $badge='warning';
  elseif ($st==='Geprüft') $badge='info';
  elseif ($st==='Bestellt') $badge='success';
  return '<span class="badge text-bg-'.$badge.'">'.h($st).'</span>';
}
$editable = ($order['status'] !== 'Bestellt'); // Optional: nach Bedarf sperren
?>
<!doctype html>
<html lang="de">
<head>
  <meta charset="utf-8">
  <title>Bestellung #<?= (int)$order['id'] ?></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 flex-wrap gap-2 mb-3">
    <h1 class="h4 mb-0">Bestellung #<?= (int)$order['id'] ?> <?= status_badge($order['status']) ?></h1>
    <div class="d-flex gap-2">
      <a class="btn btn-outline-secondary" href="orders.php">← Zur Übersicht</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="row g-3">
    <div class="col-12 col-lg-6">
      <div class="card shadow-sm">
        <div class="card-header">Kopfdaten</div>
        <div class="card-body">
          <dl class="row mb-3">
            <dt class="col-4">Einheit</dt><dd class="col-8"><?= h($order['einheit']) ?></dd>
            <dt class="col-4">Besteller</dt><dd class="col-8"><?= h(trim(($order['vorname']??'').' '.($order['nachname']??''))) ?></dd>
            <dt class="col-4">Erstellt</dt><dd class="col-8"><?= date('d.m.Y H:i', strtotime($order['created_at'])) ?></dd>
          </dl>

          <form method="post" class="mb-3">
            <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
            <input type="hidden" name="action" value="update_header">
            <div class="mb-2">
              <label class="form-label">Bestellt bei</label>
              <input name="bestellt_bei" class="form-control" value="<?= h($order['bestellt_bei']) ?>" list="dl_lief" <?= $editable?'':'disabled' ?>>
              <datalist id="dl_lief">
                <?php foreach($lieferanten as $n): ?>
                  <option value="<?= h($n) ?>"></option>
                <?php endforeach; ?>
              </datalist>
            </div>
            <div class="mb-2">
              <label class="form-label">Bemerkung</label>
              <textarea name="bemerkung" class="form-control" rows="3" <?= $editable?'':'disabled' ?>><?= h($order['bemerkung']) ?></textarea>
            </div>
            <div class="d-flex gap-2">
              <button class="btn btn-primary" <?= $editable?'':'disabled' ?>>💾 Speichern</button>
            </div>
          </form>

          <form method="post" class="d-inline">
            <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
            <input type="hidden" name="action" value="update_status">
            <div class="input-group" style="max-width:420px">
              <label class="input-group-text">Status</label>
              <select name="status" class="form-select">
                <?php foreach($allowed_status as $s): ?>
                  <option value="<?= h($s) ?>" <?= $order['status']===$s ? 'selected':'' ?>><?= h($s) ?></option>
                <?php endforeach; ?>
              </select>
              <button class="btn btn-outline-primary">Aktualisieren</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <div class="col-12 col-lg-6">
      <div class="card shadow-sm h-100">
        <div class="card-header">Positionen hinzufügen</div>
        <div class="card-body">
          <form class="row g-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 <?= $editable?'':'disabled' ?>>
            </div>
            <div class="col-12 col-md-5">
              <label class="form-label">Bezeichnung</label>
              <input name="bezeichnung" class="form-control" required <?= $editable?'':'disabled' ?>>
            </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 <?= $editable?'':'disabled' ?>>
            </div>
            <div class="col-6 col-md-2">
              <label class="form-label">Einheit</label>
              <input name="einheit_text" class="form-control" value="Stk" <?= $editable?'':'disabled' ?>>
            </div>
            <div class="col-12 d-grid">
              <button class="btn btn-success" <?= $editable?'':'disabled' ?>>➕ Hinzufügen</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <div class="col-12">
      <div class="card shadow-sm">
        <div class="card-header">Bestellpositionen</div>
        <div class="card-body">
          <div class="table-responsive">
            <table class="table table-sm align-middle">
              <thead class="table-light">
                <tr>
                  <th>#</th>
                  <th>Artikel</th>
                  <th>Bezeichnung</th>
                  <th class="text-end" style="width:140px">Menge</th>
                  <th style="width:120px">Einheit</th>
                  <th style="width:180px">Aktion</th>
                </tr>
              </thead>
              <tbody>
              <?php if ($pos && $pos->num_rows): while($p=$pos->fetch_assoc()): ?>
                <tr>
                  <td><?= (int)$p['id'] ?></td>
                  <td><?= h($p['artikel_nr']) ?></td>
                  <td><?= h($p['bezeichnung']) ?></td>
                  <td class="text-end">
                    <form class="d-inline-flex gap-1" 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)$p['id'] ?>">
                      <input name="menge" type="number" step="0.01" min="0.01" value="<?= h($p['menge']) ?>" class="form-control form-control-sm text-end" style="max-width:90px" <?= $editable?'':'disabled' ?>>
                      <button class="btn btn-sm btn-outline-primary" <?= $editable?'':'disabled' ?>>💾</button>
                    </form>
                  </td>
                  <td><?= h($p['einheit_text']) ?></td>
                  <td>
                    <form class="d-inline" method="post" onsubmit="return confirm('Position wirklich löschen?');">
                      <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
                      <input type="hidden" name="action" value="del_item">
                      <input type="hidden" name="pos_id" value="<?= (int)$p['id'] ?>">
                      <button class="btn btn-sm btn-outline-danger" <?= $editable?'':'disabled' ?>>🗑️ Entfernen</button>
                    </form>
                  </td>
                </tr>
              <?php endwhile; else: ?>
                <tr><td colspan="6" class="text-center text-muted py-4">Keine Positionen vorhanden.</td></tr>
              <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <div class="col-12">
      <div class="card shadow-sm">
        <div class="card-header">Änderungsprotokoll</div>
        <div class="card-body">
          <div class="table-responsive">
            <table class="table table-sm align-middle">
              <thead class="table-light">
                <tr>
                  <th>Zeit</th>
                  <th>Benutzer</th>
                  <th>Aktion</th>
                  <th>Feld</th>
                  <th>Alt</th>
                  <th>Neu</th>
                </tr>
              </thead>
              <tbody>
              <?php if ($logs && $logs->num_rows): while($l=$logs->fetch_assoc()): ?>
                <tr>
                  <td><?= date('d.m.Y H:i', strtotime($l['created_at'])) ?></td>
                  <td><?= h(trim($l['uname'] ?? (string)$l['user_id'])) ?></td>
                  <td><code><?= h($l['aktion']) ?></code></td>
                  <td><?= h($l['feld']) ?></td>
                  <td><?= h($l['altwert']) ?></td>
                  <td><?= h($l['neuwert']) ?></td>
                </tr>
              <?php endwhile; else: ?>
                <tr><td colspan="6" class="text-center text-muted py-4">Noch keine Änderungen protokolliert.</td></tr>
              <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

  </div><!-- /row -->
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
