<?php
session_start();
include 'includes/db.php';
include 'includes/header.php';
include 'includes/nav.php';

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

$meldung = '';
$user_id = $_SESSION['user_id'];
$einheit = $_SESSION['einheit'];
$email = $_SESSION['email'];

// Neue Aufgabe speichern
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_task'])) {
    $titel = trim($_POST['titel']);
    $beschreibung = trim($_POST['beschreibung']);
    $faellig_am = $_POST['faellig_am'] ?? null;
    $prioritaet = $_POST['prioritaet'] ?? 'mittel';
    $empfaenger_id = $_POST['empfaenger_id'] !== 'alle' ? (int)$_POST['empfaenger_id'] : null;
    $anhang = null;
    $email_empfaenger = null;

    if ($titel && $beschreibung) {
        // Datei hochladen
        if (!empty($_FILES['anhang']['name'])) {
            $upload_dir = 'uploads/';
            $dateiname = uniqid() . '_' . basename($_FILES['anhang']['name']);
            $ziel = $upload_dir . $dateiname;
            move_uploaded_file($_FILES['anhang']['tmp_name'], $ziel);
            $anhang = $dateiname;
        }

        // Empfänger-Mail (nur bei Einzelperson)
        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();

        $meldung = "<div class='alert alert-success'>✅ Aufgabe gespeichert.</div>";

        include 'mail/mail_neueaufgabe.php';


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

// Aufgabe als erledigt markieren
if (isset($_GET['done'])) {
    $task_id = (int)$_GET['done'];
    $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();
}

// Ungelesene Aufgaben zählen
$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();

// Filterstatus
$status_filter = $_GET['status'] ?? '';
$where_status = $status_filter ? "AND a.status = ?" : "";

// Aufgaben abrufen
$sql = "SELECT a.*, u.vorname, u.nachname
        FROM aufgaben a
        LEFT JOIN users u ON a.absender_id = u.id
        WHERE a.einheit = ? AND (a.empfaenger_id IS NULL OR a.empfaenger_id = ?) $where_status
        ORDER BY a.faellig_am ASC, a.erstellt_am DESC";

$stmt = $conn->prepare($sql);
if ($status_filter) {
    $stmt->bind_param("sis", $einheit, $user_id, $status_filter);
} else {
    $stmt->bind_param("si", $einheit, $user_id);
}
$stmt->execute();
$aufgaben = $stmt->get_result();

$empfaenger = $conn->query("SELECT id, vorname, nachname FROM users WHERE einheit = '$einheit' ORDER BY nachname");
?>

<div class="container my-5">
  <h2 class="mb-4">📋 Aufgabenverwaltung</h2>
  <?= $meldung ?>

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

  <form method="get" class="mb-4 d-flex gap-2">
    <select name="status" class="form-select w-auto">
      <option value="">Alle</option>
      <option value="offen" <?= $status_filter == 'offen' ? 'selected' : '' ?>>⏳ Offen</option>
      <option value="erledigt" <?= $status_filter == 'erledigt' ? 'selected' : '' ?>>✅ Erledigt</option>
    </select>
    <button class="btn btn-outline-secondary">Filtern</button>
  </form>

  <form method="post" enctype="multipart/form-data" class="card p-4 mb-4 bg-light shadow-sm">
    <h5 class="mb-3">Neue Aufgabe erstellen</h5>
    <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="<?= 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-3">
      <label class="form-label">Aufgabe senden an</label>
      <select name="empfaenger_id" class="form-select">
        <option value="alle">🌐 Alle aus meiner Einheit</option>
        <?php while ($e = $empfaenger->fetch_assoc()): ?>
          <option value="<?= $e['id'] ?>"><?= htmlspecialchars($e['vorname'] . ' ' . $e['nachname']) ?></option>
        <?php endwhile; ?>
      </select>
    </div>
    <button type="submit" name="add_task" class="btn btn-primary">➕ Aufgabe erstellen</button>
  </form>

  <h4 class="mb-3">📌 Aufgabenliste</h4>
  <table class="table table-bordered table-hover bg-white">
    <thead class="table-light">
      <tr>
        <th>Titel</th>
        <th>Beschreibung</th>
        <th>Priorität</th>
        <th>Fällig am</th>
        <th>Von</th>
        <th>Anhang</th>
        <th>Status</th>
        <th>Aktion</th>
      </tr>
    </thead>
    <tbody>
      <?php 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 => '',
        };
      ?>
        <tr class="<?= $a['status'] === 'erledigt' ? 'table-success' : '' ?>">
          <td><?= htmlspecialchars($a['titel']) ?></td>
          <td style="white-space: pre-wrap;"><?= nl2br(htmlspecialchars($a['beschreibung'])) ?></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><?= htmlspecialchars($a['vorname'] . ' ' . $a['nachname']) ?></td>
          <td>
            <?php if ($a['anhang']): ?>
              <a href="uploads/<?= htmlspecialchars($a['anhang']) ?>" target="_blank">📎 Download</a>
            <?php else: ?>–<?php endif; ?>
          </td>
          <td><strong><?= $a['status'] === 'erledigt' ? '✅ Erledigt' : '⏳ Offen' ?></strong></td>
          <td>
            <?php if ($a['status'] === 'offen'): ?>
              <a href="?done=<?= $a['id'] ?>" class="btn btn-sm btn-success">✅ Erledigt</a>
            <?php else: ?>–<?php endif; ?>
          </td>
        </tr>
      <?php endwhile; ?>
    </tbody>
  </table>
  <h4 class="mb-3 mt-5">📤 Gesendete Aufgaben</h4>
<table class="table table-bordered table-hover bg-white">
  <thead class="table-light">
    <tr>
      <th>Empfänger</th>
      <th>Titel</th>
      <th>Beschreibung</th>
      <th>Priorität</th>
      <th>Fällig am</th>
      <th>Anhang</th>
      <th>Status</th>
      <th>Gesendet am</th>
    </tr>
  </thead>
  <tbody>
    <?php
    $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();

    while ($s = $sent_tasks->fetch_assoc()):
      $tage = $s['faellig_am'] ? (new DateTime())->diff(new DateTime($s['faellig_am']))->format('%r%a') : null;
      $badge = 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'] ? htmlspecialchars($s['vorname'] . ' ' . $s['nachname']) : '🌐 Alle (Einheit)' ?>
      </td>
      <td><?= htmlspecialchars($s['titel']) ?></td>
      <td style="white-space: pre-wrap;"><?= nl2br(htmlspecialchars($s['beschreibung'])) ?></td>
      <td><?= $badge ?></td>
      <td>
        <?= $s['faellig_am'] ? date("d.m.Y", strtotime($s['faellig_am'])) : '–' ?>
        <?php if ($tage !== null): ?>
          <small class="text-muted">(<?= $tage ?> Tage)</small>
        <?php endif; ?>
      </td>
      <td>
        <?php if ($s['anhang']): ?>
          <a href="uploads/<?= htmlspecialchars($s['anhang']) ?>" target="_blank">📎 Download</a>
        <?php else: ?>–<?php endif; ?>
      </td>
      <td><strong><?= $s['status'] === 'erledigt' ? '✅ Erledigt' : '⏳ Offen' ?></strong></td>
      <td><?= date("d.m.Y H:i", strtotime($s['erstellt_am'])) ?></td>
    </tr>
    <?php endwhile; ?>
  </tbody>
</table>

</div>

<?php include 'includes/footer.php'; ?>
