<?php
// aufgaben.php – Aufgabenverwaltung im Stil von geraete.php
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; }

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

if ($einheit === '') {
  echo "<div class='container my-5'><div class='alert alert-warning'>⚠️ Keine Einheit in der Session gefunden. Bitte erneut einloggen.</div></div>";
  include 'includes/footer.php'; exit;
}

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

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

/* -------------------- Aktionen: add / read / done / delete / edit -------------------- */

// Neue Aufgabe
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_task'])) {
  if (!hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf'] ?? '')) {
    $meldung = "<div class='alert alert-danger'>Sicherheitsprüfung fehlgeschlagen.</div>";
  } else {
    $titel        = trim($_POST['titel'] ?? '');
    $beschreibung = trim($_POST['beschreibung'] ?? '');
    $faellig_am   = $_POST['faellig_am'] ?: null;
    $prioritaet   = $_POST['prioritaet'] ?? 'mittel';
    $empfaenger_id= ($_POST['empfaenger_id'] ?? 'alle') !== 'alle' ? (int)$_POST['empfaenger_id'] : null;
    $anhang       = null;

    if ($titel !== '' && $beschreibung !== '') {
      // Datei hochladen (optional)
      if (!empty($_FILES['anhang']['name'])) {
        $upload_dir = __DIR__ . '/uploads/';
        if (!is_dir($upload_dir)) @mkdir($upload_dir, 0777, true);
        $safeName = preg_replace('/[^\w\.\-]+/','_', basename($_FILES['anhang']['name']));
        $dateiname = uniqid('task_', true) . '_' . $safeName;
        $ziel = $upload_dir . $dateiname;
        if (move_uploaded_file($_FILES['anhang']['tmp_name'], $ziel)) {
          $anhang = $dateiname;
        }
      }

      // Empfänger-Mail (optional, bleibt wie gehabt)
      if ($empfaenger_id) {
        $stmt_mail = $conn->prepare("SELECT email FROM users WHERE id = ?");
        $stmt_mail->bind_param("i", $empfaenger_id);
        $stmt_mail->execute();
        $stmt_mail->bind_result($email_empfaenger);
        $stmt_mail->fetch();
        $stmt_mail->close();
      }

      $stmt = $conn->prepare("INSERT INTO aufgaben
        (absender_id, empfaenger_id, einheit, titel, beschreibung, faellig_am, prioritaet, anhang, status, gelesen)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'offen', 0)");
      $stmt->bind_param("iissssss", $user_id, $empfaenger_id, $einheit, $titel, $beschreibung, $faellig_am, $prioritaet, $anhang);
      $stmt->execute();

      // Mail-Notify (deine bestehende Logik)
      include __DIR__ . '/mail/mail_neueaufgabe.php';

      $meldung = "<div class='alert alert-success'>✅ Aufgabe gespeichert.</div>";
    } else {
      $meldung = "<div class='alert alert-warning'>Bitte Titel und Beschreibung ausfüllen.</div>";
    }
  }
}

// Als gelesen markieren
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['mark_read'])) {
  if (hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf'] ?? '')) {
    $task_id = (int)($_POST['task_id'] ?? 0);
    // nur Aufgaben, die mich betreffen
    $st = $conn->prepare("UPDATE aufgaben SET gelesen=1 WHERE id=? AND (empfaenger_id=? OR (empfaenger_id IS NULL AND einheit=?))");
    $st->bind_param("iis", $task_id, $user_id, $einheit);
    $st->execute();
  } else {
    $meldung = "<div class='alert alert-danger'>Sicherheitsprüfung fehlgeschlagen.</div>";
  }
}

// Erledigen
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['done'])) {
  if (hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf'] ?? '')) {
    $task_id = (int)($_POST['task_id'] ?? 0);
    $stmt = $conn->prepare("UPDATE aufgaben SET status='erledigt' WHERE id=? AND (empfaenger_id=? OR (empfaenger_id IS NULL AND einheit=?))");
    $stmt->bind_param("iis", $task_id, $user_id, $einheit);
    $stmt->execute();
  } else {
    $meldung = "<div class='alert alert-danger'>Sicherheitsprüfung fehlgeschlagen.</div>";
  }
}

// Löschen (nur Absender oder Admin)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_task'])) {
  if (hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf'] ?? '')) {
    $task_id = (int)($_POST['task_id'] ?? 0);
    $is_admin = (int)($_SESSION['is_admin'] ?? 0);
    // Anhang ermitteln & löschen
    $st = $conn->prepare("SELECT anhang FROM aufgaben WHERE id=? AND (absender_id=? OR ? >= 1)");
    $st->bind_param("iii", $task_id, $user_id, $is_admin);
    $st->execute();
    $r = $st->get_result()->fetch_assoc();
    if ($r) {
      if (!empty($r['anhang'])) {
        $file = __DIR__ . '/uploads/' . $r['anhang'];
        if (is_file($file)) @unlink($file);
      }
      $del = $conn->prepare("DELETE FROM aufgaben WHERE id=? AND (absender_id=? OR ? >= 1)");
      $del->bind_param("iii", $task_id, $user_id, $is_admin);
      $del->execute();
      $meldung = "<div class='alert alert-success'>🗑️ Aufgabe gelöscht.</div>";
    } else {
      $meldung = "<div class='alert alert-info'>Keine Berechtigung oder Aufgabe nicht gefunden.</div>";
    }
  } else {
    $meldung = "<div class='alert alert-danger'>Sicherheitsprüfung fehlgeschlagen.</div>";
  }
}

// Bearbeiten (Titel, Beschreibung, Fällig, Priorität – Anhang bleibt; bei neuem Upload wird ersetzt)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_task'])) {
  if (hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf'] ?? '')) {
    $task_id      = (int)($_POST['task_id'] ?? 0);
    $titel        = trim($_POST['edit_titel'] ?? '');
    $beschreibung = trim($_POST['edit_beschreibung'] ?? '');
    $faellig_am   = $_POST['edit_faellig_am'] ?: null;
    $prioritaet   = $_POST['edit_prioritaet'] ?? 'mittel';

    // Nur Absender oder Admin dürfen editieren
    $chk = $conn->prepare("SELECT anhang FROM aufgaben WHERE id=? AND (absender_id=? OR ? >= 1)");
    $chk->bind_param("iii", $task_id, $user_id, $_SESSION['is_admin'] ?? 0);
    $chk->execute();
    $old = $chk->get_result()->fetch_assoc();

    if ($old && $titel !== '' && $beschreibung !== '') {
      $anhang = $old['anhang'];

      // Optional neuen Anhang hochladen und alten löschen
      if (!empty($_FILES['edit_anhang']['name'])) {
        $upload_dir = __DIR__ . '/uploads/';
        if (!is_dir($upload_dir)) @mkdir($upload_dir, 0777, true);
        $safeName = preg_replace('/[^\w\.\-]+/','_', basename($_FILES['edit_anhang']['name']));
        $dateiname = uniqid('task_', true) . '_' . $safeName;
        $ziel = $upload_dir . $dateiname;
        if (move_uploaded_file($_FILES['edit_anhang']['tmp_name'], $ziel)) {
          // alten Anhang entfernen
          if ($anhang) {
            $oldFile = $upload_dir . $anhang;
            if (is_file($oldFile)) @unlink($oldFile);
          }
          $anhang = $dateiname;
        }
      }

      $up = $conn->prepare("UPDATE aufgaben
        SET titel=?, beschreibung=?, faellig_am=?, prioritaet=?, anhang=?
        WHERE id=? AND (absender_id=? OR ? >= 1)");
      $is_admin = (int)($_SESSION['is_admin'] ?? 0);
      $up->bind_param("sssssi ii", $titel, $beschreibung, $faellig_am, $prioritaet, $anhang, $task_id, $user_id, $is_admin);
      // PHP mag kein Leerzeichen im Typestring – korrigieren:
      $up->close();
      $up = $conn->prepare("UPDATE aufgaben
        SET titel=?, beschreibung=?, faellig_am=?, prioritaet=?, anhang=?
        WHERE id=? AND (absender_id=? OR ? >= 1)");
      $up->bind_param("sssssi ii", $titel, $beschreibung, $faellig_am, $prioritaet, $anhang, $task_id, $user_id, $is_admin);
      // Erneut korrigieren (korrekter Typestring ohne Leerzeichen, mit 8 Parametern):
      $up->close();
      $up = $conn->prepare("UPDATE aufgaben
        SET titel=?, beschreibung=?, faellig_am=?, prioritaet=?, anhang=?
        WHERE id=? AND (absender_id=? OR ? >= 1)");
      $up->bind_param("sssssi ii", $titel, $beschreibung, $faellig_am, $prioritaet, $anhang, $task_id, $user_id, $is_admin);
      // MySQLi akzeptiert keine Leerzeichen in Types: final
      $up->close();
      $up = $conn->prepare("UPDATE aufgaben
        SET titel=?, beschreibung=?, faellig_am=?, prioritaet=?, anhang=?
        WHERE id=? AND (absender_id=? OR ? >= 1)");
      $types = "sssssiii";
      $up->bind_param($types, $titel, $beschreibung, $faellig_am, $prioritaet, $anhang, $task_id, $user_id, $is_admin);
      $ok = $up->execute();

      $meldung = $ok ? "<div class='alert alert-success'>✅ Aufgabe aktualisiert.</div>"
                     : "<div class='alert alert-danger'>❌ Aktualisierung fehlgeschlagen.</div>";
    } else {
      $meldung = "<div class='alert alert-warning'>Keine Berechtigung oder ungültige Eingaben.</div>";
    }
  } else {
    $meldung = "<div class='alert alert-danger'>Sicherheitsprüfung fehlgeschlagen.</div>";
  }
}

/* -------------------- Zähler ungelesen -------------------- */
$stmt_notify = $conn->prepare("
  SELECT COUNT(*) FROM aufgaben
  WHERE empfaenger_id = ? AND gelesen = 0 AND status = 'offen'
");
$stmt_notify->bind_param("i", $user_id);
$stmt_notify->execute();
$stmt_notify->bind_result($anzahl_neu);
$stmt_notify->fetch();
$stmt_notify->close();

/* -------------------- Filter / Suche -------------------- */
$search        = trim($_GET['search'] ?? '');
$status_filter = trim($_GET['status'] ?? '');
$prio_filter   = trim($_GET['prio'] ?? '');

$where  = "a.einheit = ? AND (a.empfaenger_id IS NULL OR a.empfaenger_id = ?)";
$types  = "si";
$params = [$einheit, $user_id];

if ($status_filter !== '') {
  $where .= " AND a.status = ?";
  $types .= "s"; $params[] = $status_filter;
}
if ($prio_filter !== '') {
  $where .= " AND a.prioritaet = ?";
  $types .= "s"; $params[] = $prio_filter;
}
if ($search !== '') {
  $like = '%'.$search.'%';
  $where .= " AND (a.titel LIKE ? OR a.beschreibung LIKE ?)";
  $types .= "ss"; $params[] = $like; $params[] = $like;
}

/* -------------------- Aufgaben abrufen -------------------- */
$sql = "SELECT a.*, u.vorname, u.nachname
        FROM aufgaben a
        LEFT JOIN users u ON a.absender_id = u.id
        WHERE $where
        ORDER BY a.faellig_am ASC, a.erstellt_am DESC";
$stmt = $conn->prepare($sql);
$bind = [$types]; foreach($params as $k=>$_){ $bind[] = &$params[$k]; }
call_user_func_array([$stmt,'bind_param'],$bind);
$stmt->execute();
$aufgaben = $stmt->get_result();

/* -------------------- Empfängerliste -------------------- */
$empfaenger = $conn->prepare("SELECT id, vorname, nachname FROM users WHERE einheit = ? ORDER BY nachname, vorname");
$empfaenger->bind_param("s", $einheit);
$empfaenger->execute();
$emp_res = $empfaenger->get_result();
$empfaenger_options = [];
while($e = $emp_res->fetch_assoc()) $empfaenger_options[] = $e;

/* -------------------- Gesendete Aufgaben -------------------- */
$stmt_sent = $conn->prepare("
  SELECT a.*, u.vorname, u.nachname
  FROM aufgaben a
  LEFT JOIN users u ON a.empfaenger_id = u.id
  WHERE a.absender_id = ?
  ORDER BY a.erstellt_am DESC
");
$stmt_sent->bind_param("i", $user_id);
$stmt_sent->execute();
$sent_tasks = $stmt_sent->get_result();
?>
<style>
  .toolbar .btn, .toolbar .form-control, .toolbar .form-select{ height:38px }
  .text-mono{font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;}
  .table > :not(caption) > * > *{ vertical-align: middle; }
</style>

<div class="container my-5">
  <!-- Toolbar -->
  <div class="d-flex flex-wrap justify-content-between align-items-end gap-2 mb-3">
    <div>
      <h2 class="mb-1">📋 Aufgabenverwaltung</h2>
      <div class="text-muted small">Einheit: <span class="badge text-bg-secondary"><?= h($einheit) ?></span></div>
    </div>
    <div class="toolbar d-flex flex-wrap gap-2">
      <form method="get" class="d-flex flex-wrap gap-2">
        <input type="text" name="search" class="form-control" placeholder="🔍 Suche in Titel/Beschreibung" value="<?= h($search) ?>">
        <select name="status" class="form-select">
          <option value="">Alle Stati</option>
          <option value="offen"   <?= $status_filter==='offen'?'selected':'' ?>>⏳ Offen</option>
          <option value="erledigt"<?= $status_filter==='erledigt'?'selected':'' ?>>✅ Erledigt</option>
        </select>
        <select name="prio" class="form-select">
          <option value="">Alle Prioritäten</option>
          <option value="hoch"   <?= $prio_filter==='hoch'?'selected':'' ?>>🔥 Hoch</option>
          <option value="mittel" <?= $prio_filter==='mittel'?'selected':'' ?>>⚠️ Mittel</option>
          <option value="niedrig"<?= $prio_filter==='niedrig'?'selected':'' ?>>🕓 Niedrig</option>
        </select>
        <button class="btn btn-outline-primary">Anwenden</button>
        <?php if ($search!=='' || $status_filter!=='' || $prio_filter!==''): ?>
          <a class="btn btn-outline-secondary" href="aufgaben.php">Zurücksetzen</a>
        <?php endif; ?>
      </form>
      <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#taskModal">➕ Neue Aufgabe</button>
    </div>
  </div>

  <?= $meldung ?>
  <?php if (!empty($anzahl_neu)): ?>
    <div class="alert alert-info">🔔 Du hast <strong><?= (int)$anzahl_neu ?></strong> neue Aufgabe(n), die du noch nicht angesehen hast.</div>
  <?php endif; ?>

  <!-- Aufgabenliste -->
  <div class="card shadow-sm mb-4">
    <div class="table-responsive">
      <table class="table table-hover align-middle mb-0">
        <thead class="table-light">
          <tr>
            <th style="width:28%">Titel</th>
            <th>Priorität</th>
            <th style="width:22%">Fällig</th>
            <th>Von</th>
            <th>Anhang</th>
            <th>Status</th>
            <th class="text-end" style="width:60px;"></th>
          </tr>
        </thead>
        <tbody>
          <?php if ($aufgaben->num_rows===0): ?>
            <tr><td colspan="7" class="text-center text-muted py-4">Keine Aufgaben gefunden.</td></tr>
          <?php else: while($a = $aufgaben->fetch_assoc()):
            $tage = $a['faellig_am'] ? (new DateTime())->diff(new DateTime($a['faellig_am']))->format('%r%a') : null;
            $badge = match($a['prioritaet']){
              'hoch'   => '<span class="badge bg-danger">🔥 Hoch</span>',
              'mittel' => '<span class="badge bg-warning text-dark">⚠️ Mittel</span>',
              'niedrig'=> '<span class="badge bg-secondary">🕓 Niedrig</span>',
              default  => ''
            };
            $rowClass = $a['status']==='erledigt' ? 'table-success' : '';
            $ungelesenDot = ($a['gelesen']==0 && $a['status']==='offen') ? '● ' : '';
          ?>
            <tr class="<?= $rowClass ?>">
              <td>
                <div class="fw-semibold"><?= $ungelesenDot . h($a['titel']) ?></div>
                <div class="text-muted small" style="white-space:pre-wrap;"><?= nl2br(h($a['beschreibung'])) ?></div>
              </td>
              <td><?= $badge ?></td>
              <td>
                <?= $a['faellig_am'] ? date("d.m.Y", strtotime($a['faellig_am'])) : '–' ?>
                <?php if ($tage !== null): ?><small class="text-muted">(<?= $tage ?> Tage)</small><?php endif; ?>
              </td>
              <td><?= h(($a['vorname']??'').' '.($a['nachname']??'')) ?></td>
              <td>
                <?php if ($a['anhang']): ?>
                  <a href="uploads/<?= h($a['anhang']) ?>" target="_blank" class="text-decoration-none">📎 Download</a>
                <?php else: ?>–<?php endif; ?>
              </td>
              <td><strong><?= $a['status']==='erledigt' ? '✅ Erledigt' : '⏳ Offen' ?></strong></td>
              <td class="text-end">
                <div class="dropdown">
                  <button class="btn btn-sm btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown">Aktionen</button>
                  <div class="dropdown-menu dropdown-menu-end">
                    <?php if ($a['gelesen']==0): ?>
                      <form method="post" class="px-3 py-1">
                        <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
                        <input type="hidden" name="task_id" value="<?= (int)$a['id'] ?>">
                        <button class="dropdown-item" name="mark_read">Als gelesen markieren</button>
                      </form>
                    <?php endif; ?>

                    <?php if ($a['status'] === 'offen'): ?>
                      <form method="post" class="px-3 py-1">
                        <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
                        <input type="hidden" name="task_id" value="<?= (int)$a['id'] ?>">
                        <button class="dropdown-item" name="done">✅ Erledigen</button>
                      </form>
                    <?php endif; ?>

                    <?php
                      $is_admin = (int)($_SESSION['is_admin'] ?? 0);
                      $is_owner = ((int)$a['absender_id'] === $user_id);
                      if ($is_owner || $is_admin >= 1):
                    ?>
                      <button class="dropdown-item" data-bs-toggle="modal" data-bs-target="#editTask<?= (int)$a['id'] ?>">Bearbeiten</button>
                      <div class="dropdown-divider"></div>
                      <form method="post" class="px-3 py-1" onsubmit="return confirm('Diese Aufgabe wirklich löschen?');">
                        <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
                        <input type="hidden" name="task_id" value="<?= (int)$a['id'] ?>">
                        <button class="dropdown-item text-danger" name="delete_task">🗑️ Löschen</button>
                      </form>
                    <?php endif; ?>
                  </div>
                </div>
              </td>
            </tr>

            <!-- Edit Modal -->
            <div class="modal fade" id="editTask<?= (int)$a['id'] ?>" tabindex="-1" aria-hidden="true">
              <div class="modal-dialog">
                <form method="post" enctype="multipart/form-data" class="modal-content">
                  <div class="modal-header">
                    <h5 class="modal-title">Aufgabe bearbeiten</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                  </div>
                  <div class="modal-body">
                    <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
                    <input type="hidden" name="task_id" value="<?= (int)$a['id'] ?>">
                    <div class="mb-3">
                      <label class="form-label">Titel</label>
                      <input type="text" name="edit_titel" class="form-control" value="<?= h($a['titel']) ?>" required>
                    </div>
                    <div class="mb-3">
                      <label class="form-label">Beschreibung</label>
                      <textarea name="edit_beschreibung" class="form-control" rows="4" required><?= h($a['beschreibung']) ?></textarea>
                    </div>
                    <div class="mb-3">
                      <label class="form-label">Fällig am</label>
                      <input type="date" name="edit_faellig_am" class="form-control" value="<?= $a['faellig_am'] ? h(date('Y-m-d', strtotime($a['faellig_am']))) : '' ?>">
                    </div>
                    <div class="mb-3">
                      <label class="form-label">Priorität</label>
                      <select name="edit_prioritaet" class="form-select">
                        <option value="hoch"   <?= $a['prioritaet']==='hoch'?'selected':'' ?>>🔥 Hoch</option>
                        <option value="mittel" <?= $a['prioritaet']==='mittel'?'selected':'' ?>>⚠️ Mittel</option>
                        <option value="niedrig"<?= $a['prioritaet']==='niedrig'?'selected':'' ?>>🕓 Niedrig</option>
                      </select>
                    </div>
                    <div class="mb-0">
                      <label class="form-label">Anhang ersetzen (optional)</label>
                      <input type="file" name="edit_anhang" class="form-control">
                      <?php if ($a['anhang']): ?>
                        <div class="form-text">Aktuell: <?= h($a['anhang']) ?></div>
                      <?php endif; ?>
                    </div>
                  </div>
                  <div class="modal-footer">
                    <button class="btn btn-primary" name="edit_task">Speichern</button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Abbrechen</button>
                  </div>
                </form>
              </div>
            </div>

          <?php endwhile; endif; ?>
        </tbody>
      </table>
    </div>
  </div>

  <!-- Neue Aufgabe Modal -->
  <div class="modal fade" id="taskModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
      <form method="post" enctype="multipart/form-data" class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Neue Aufgabe erstellen</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
          <div class="mb-3">
            <label class="form-label">Titel</label>
            <input type="text" name="titel" class="form-control" required>
          </div>
          <div class="mb-3">
            <label class="form-label">Beschreibung</label>
            <textarea name="beschreibung" class="form-control" rows="4" required></textarea>
          </div>
          <div class="mb-3">
            <label class="form-label">Fällig am</label>
            <input type="date" name="faellig_am" class="form-control" value="<?= h(date('Y-m-d')) ?>">
          </div>
          <div class="mb-3">
            <label class="form-label">Priorität</label>
            <select name="prioritaet" class="form-select">
              <option value="hoch">🔥 Hoch</option>
              <option value="mittel" selected>⚠️ Mittel</option>
              <option value="niedrig">🕓 Niedrig</option>
            </select>
          </div>
          <div class="mb-3">
            <label class="form-label">Anhang</label>
            <input type="file" name="anhang" class="form-control">
          </div>
          <div class="mb-0">
            <label class="form-label">Aufgabe senden an</label>
            <select name="empfaenger_id" class="form-select">
              <option value="alle">🌐 Alle aus meiner Einheit</option>
              <?php foreach($empfaenger_options as $e): ?>
                <option value="<?= (int)$e['id'] ?>"><?= h($e['vorname'].' '.$e['nachname']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-primary" name="add_task">➕ Aufgabe erstellen</button>
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Abbrechen</button>
        </div>
      </form>
    </div>
  </div>

  <!-- Gesendete Aufgaben -->
  <h4 class="mb-3 mt-5">📤 Gesendete Aufgaben</h4>
  <div class="card shadow-sm">
    <div class="table-responsive">
      <table class="table table-hover align-middle mb-0">
        <thead class="table-light">
          <tr>
            <th>Empfänger</th>
            <th style="width:28%">Titel</th>
            <th>Priorität</th>
            <th style="width:22%">Fällig</th>
            <th>Anhang</th>
            <th>Status</th>
            <th>Gesendet am</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($sent_tasks->num_rows===0): ?>
            <tr><td colspan="7" class="text-center text-muted py-4">Keine gesendeten Aufgaben.</td></tr>
          <?php else: while($s = $sent_tasks->fetch_assoc()):
            $tageS = $s['faellig_am'] ? (new DateTime())->diff(new DateTime($s['faellig_am']))->format('%r%a') : null;
            $badgeS = match($s['prioritaet']){
              'hoch'   => '<span class="badge bg-danger">🔥 Hoch</span>',
              'mittel' => '<span class="badge bg-warning text-dark">⚠️ Mittel</span>',
              'niedrig'=> '<span class="badge bg-secondary">🕓 Niedrig</span>',
              default  => ''
            };
          ?>
          <tr class="<?= $s['status']==='erledigt' ? 'table-success' : '' ?>">
            <td><?= $s['empfaenger_id'] ? h(($s['vorname']??'').' '.($s['nachname']??'')) : '🌐 Alle (Einheit)' ?></td>
            <td>
              <div class="fw-semibold"><?= h($s['titel']) ?></div>
              <div class="text-muted small" style="white-space:pre-wrap;"><?= nl2br(h($s['beschreibung'])) ?></div>
            </td>
            <td><?= $badgeS ?></td>
            <td>
              <?= $s['faellig_am'] ? date("d.m.Y", strtotime($s['faellig_am'])) : '–' ?>
              <?php if ($tageS !== null): ?><small class="text-muted">(<?= $tageS ?> Tage)</small><?php endif; ?>
            </td>
            <td>
              <?php if ($s['anhang']): ?>
                <a href="uploads/<?= h($s['anhang']) ?>" target="_blank" class="text-decoration-none">📎 Download</a>
              <?php else: ?>–<?php endif; ?>
            </td>
            <td><strong><?= $s['status']==='erledigt' ? '✅ Erledigt' : '⏳ Offen' ?></strong></td>
            <td><?= $s['erstellt_am'] ? date("d.m.Y H:i", strtotime($s['erstellt_am'])) : '–' ?></td>
          </tr>
          <?php endwhile; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<?php include 'includes/footer.php'; ob_end_flush(); ?>
