<?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;
}

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

$user_id = (int)$_SESSION['user_id'];

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

$flash_ok = '';
$flash_err = '';

/* =========================
   POST: Aktionen
   ========================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf'] ?? '')) {
    $flash_err = 'Sicherheitsprüfung fehlgeschlagen.';
  } else {
    $action = $_POST['action'] ?? '';

    // 1) Status speichern
    if ($action === 'save_status') {
      $status = $_POST['status'] ?? 'aktiv';
      $urlaub_bis = trim($_POST['urlaub_bis'] ?? '');
      $notiz = trim($_POST['notiz'] ?? '');

      if (!in_array($status, ['aktiv','urlaub','nicht_verfuegbar'], true)) {
        $flash_err = 'Ungültiger Status.';
      } else {
        // Normalisiere Datum
        $urlaubDate = null;
        if ($status === 'urlaub' && $urlaub_bis !== '') {
          $t = strtotime($urlaub_bis);
          if ($t !== false) $urlaubDate = date('Y-m-d', $t);
        }

        // Upsert
        $stmt = $conn->prepare("
          INSERT INTO user_availability_status (user_id, status, urlaub_bis, notiz)
          VALUES (?, ?, ?, ?)
          ON DUPLICATE KEY UPDATE status=VALUES(status), urlaub_bis=VALUES(urlaub_bis), notiz=VALUES(notiz), updated_at=NOW()
        ");
        $stmt->bind_param("isss", $user_id, $status, $urlaubDate, $notiz);
        if ($stmt->execute()) $flash_ok = 'Status gespeichert.';
        else $flash_err = 'Konnte Status nicht speichern.';
      }
    }

    // 2) Wöchentliche Sperrzeiten speichern
    if ($action === 'save_weekly') {
      // Wir erlauben genau ein Start/Ende je Wochentag; leer = Eintrag entfernen
      $okAll = true; $anySet = false;

      // Transaktion, damit alles konsistent ist
      $conn->begin_transaction();
      try {
        for ($wd = 0; $wd <= 6; $wd++) {
          $start = trim($_POST["wd{$wd}_start"] ?? '');
          $end   = trim($_POST["wd{$wd}_end"] ?? '');

          if ($start === '' && $end === '') {
            // ggf. löschen
            $del = $conn->prepare("DELETE FROM user_weekly_blocks WHERE user_id=? AND weekday=?");
            $del->bind_param("ii", $user_id, $wd);
            $del->execute();
            continue;
          }

          // Validierung: HH:MM
          if (!preg_match('/^\d{2}:\d{2}$/', $start) || !preg_match('/^\d{2}:\d{2}$/', $end)) {
            $okAll = false; break;
          }
          if (strtotime($start) >= strtotime($end)) {
            $okAll = false; break;
          }
          $anySet = true;

          // Upsert (per REPLACE: unique (user_id, weekday))
          $repl = $conn->prepare("
            REPLACE INTO user_weekly_blocks (user_id, weekday, start_time, end_time)
            VALUES (?, ?, ?, ?)
          ");
          $repl->bind_param("iiss", $user_id, $wd, $start, $end);
          $repl->execute();
        }

        if ($okAll) {
          $conn->commit();
          $flash_ok = $anySet ? 'Wöchentliche Sperrzeiten gespeichert.' : 'Alle wöchentlichen Sperrzeiten entfernt.';
        } else {
          $conn->rollback();
          $flash_err = 'Ungültige Zeiten (Format oder Reihenfolge).';
        }
      } catch (Throwable $e) {
        $conn->rollback();
        $flash_err = 'Fehler beim Speichern der Sperrzeiten.';
      }
    }

    // 3) Einmalige Abwesenheit hinzufügen
    if ($action === 'add_block') {
      $start_dt = trim($_POST['start_dt'] ?? '');
      $end_dt   = trim($_POST['end_dt'] ?? '');
      $reason   = trim($_POST['reason'] ?? '');

      $ts1 = strtotime($start_dt);
      $ts2 = strtotime($end_dt);

      if ($ts1 === false || $ts2 === false || $ts1 >= $ts2) {
        $flash_err = 'Bitte gültige Von/Bis-Zeiten angeben.';
      } else {
        $startSql = date('Y-m-d H:i:s', $ts1);
        $endSql   = date('Y-m-d H:i:s', $ts2);

        $ins = $conn->prepare("
          INSERT INTO user_absence_blocks (user_id, start_dt, end_dt, reason)
          VALUES (?, ?, ?, ?)
        ");
        $ins->bind_param("isss", $user_id, $startSql, $endSql, $reason);
        if ($ins->execute()) $flash_ok = 'Abwesenheit hinzugefügt.';
        else $flash_err = 'Abwesenheit konnte nicht gespeichert werden.';
      }
    }

    // 4) Einmalige Abwesenheit löschen (nur eigene)
    if ($action === 'del_block') {
      $bid = (int)($_POST['block_id'] ?? 0);
      if ($bid > 0) {
        $del = $conn->prepare("DELETE FROM user_absence_blocks WHERE id=? AND user_id=?");
        $del->bind_param("ii", $bid, $user_id);
        if ($del->execute()) $flash_ok = 'Abwesenheit entfernt.';
        else $flash_err = 'Konnte Abwesenheit nicht entfernen.';
      }
    }
  }
}

/* =========================
   GET: Daten laden
   ========================= */

// Status laden
$stmt = $conn->prepare("SELECT status, urlaub_bis, notiz, updated_at FROM user_availability_status WHERE user_id=?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$statusRow = $stmt->get_result()->fetch_assoc();

$current_status = $statusRow['status'] ?? 'aktiv';
$current_urlaub = $statusRow['urlaub_bis'] ?? '';
$current_notiz  = $statusRow['notiz'] ?? '';

// Weekly blocks laden
$weekly = array_fill(0, 7, ['start' => '', 'end' => '']);
$wb = $conn->prepare("SELECT weekday, start_time, end_time FROM user_weekly_blocks WHERE user_id=?");
$wb->bind_param("i", $user_id);
$wb->execute();
$resW = $wb->get_result();
while ($r = $resW->fetch_assoc()) {
  $wd = (int)$r['weekday'];
  if ($wd>=0 && $wd<=6) {
    $weekly[$wd]['start'] = substr($r['start_time'], 0, 5);
    $weekly[$wd]['end']   = substr($r['end_time'], 0, 5);
  }
}

// Einmalige Blöcke
$blocks = [];
$bl = $conn->prepare("SELECT id, start_dt, end_dt, reason FROM user_absence_blocks WHERE user_id=? ORDER BY start_dt DESC");
$bl->bind_param("i", $user_id);
$bl->execute();
$blocks = $bl->get_result();

$wdNames = ['Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag','Sonntag'];
?>

<style>
  .card-elev { border:1px solid #e9ecef; border-radius:1rem; box-shadow:0 6px 20px rgba(0,0,0,.06); }
  .section-title { font-weight:600; font-size:1.05rem; color:#0d6efd; display:flex; align-items:center; gap:.5rem; }
  .badge-status { font-size:.9rem; }
</style>

<div class="container my-5">
  <div class="d-flex align-items-center justify-content-between mb-3">
    <h1 class="mb-0">⚙️ Verfügbarkeit & Zeiten</h1>
    <a class="btn btn-outline-secondary" href="index.php">Zurück</a>
  </div>

  <?php if ($flash_ok): ?>
    <div class="alert alert-success"><?= h($flash_ok) ?></div>
  <?php endif; ?>
  <?php if ($flash_err): ?>
    <div class="alert alert-danger"><?= h($flash_err) ?></div>
  <?php endif; ?>

  <!-- Status -->
  <div class="card card-elev mb-4">
    <div class="card-body">
      <div class="d-flex align-items-center justify-content-between">
        <div class="section-title"><i class="bi bi-person-check"></i> Erreichbarkeitsstatus</div>
        <div>
          <?php
            $class = 'secondary'; $label = 'Unbekannt';
            if ($current_status === 'aktiv') { $class='success'; $label='Aktiv'; }
            elseif ($current_status === 'urlaub') { $class='warning'; $label = 'Im Urlaub' . ($current_urlaub ? ' bis '.date('d.m.Y', strtotime($current_urlaub)) : ''); }
            elseif ($current_status === 'nicht_verfuegbar') { $class='danger'; $label='Nicht verfügbar'; }
          ?>
          <span class="badge text-bg-<?= $class ?> badge-status"><?= h($label) ?></span>
        </div>
      </div>

      <form method="post" class="row g-3 mt-2">
        <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
        <input type="hidden" name="action" value="save_status">
        <div class="col-md-4">
          <label class="form-label">Status</label>
          <select name="status" class="form-select" id="statusSelect" required>
            <option value="aktiv" <?= $current_status==='aktiv'?'selected':'' ?>>Aktiv</option>
            <option value="urlaub" <?= $current_status==='urlaub'?'selected':'' ?>>Im Urlaub</option>
            <option value="nicht_verfuegbar" <?= $current_status==='nicht_verfuegbar'?'selected':'' ?>>Nicht verfügbar</option>
          </select>
        </div>
        <div class="col-md-4">
          <label class="form-label">Urlaub bis (optional)</label>
          <input type="date" name="urlaub_bis" class="form-control" value="<?= h($current_urlaub) ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">Notiz (intern)</label>
          <input type="text" name="notiz" class="form-control" value="<?= h($current_notiz) ?>" placeholder="z. B. Rufbereitschaft">
        </div>
        <div class="col-12">
          <button class="btn btn-primary">💾 Status speichern</button>
        </div>
      </form>
    </div>
  </div>

  <!-- Wöchentliche Sperrzeiten -->
  <div class="card card-elev mb-4">
    <div class="card-body">
      <div class="section-title"><i class="bi bi-calendar-week"></i> Wöchentliche Nicht-Verfügbarkeiten (Sperrzeiten)</div>
      <p class="text-muted mb-3">Lasse Felder leer, wenn du an dem Tag keine wiederkehrende Sperrzeit pflegen willst.</p>
      <form method="post">
        <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
        <input type="hidden" name="action" value="save_weekly">
        <div class="row g-3">
          <?php for ($i=0; $i<7; $i++): ?>
            <div class="col-12 col-md-6">
              <div class="border rounded p-3">
                <strong><?= h($wdNames[$i]) ?></strong>
                <div class="row g-2 mt-1">
                  <div class="col-6">
                    <label class="form-label">Von</label>
                    <input type="time" class="form-control" name="wd<?= $i ?>_start" value="<?= h($weekly[$i]['start']) ?>">
                  </div>
                  <div class="col-6">
                    <label class="form-label">Bis</label>
                    <input type="time" class="form-control" name="wd<?= $i ?>_end" value="<?= h($weekly[$i]['end']) ?>">
                  </div>
                </div>
                <div class="form-text">Beispiel: 08:00–17:00 = nicht verfügbar in dieser Zeit.</div>
              </div>
            </div>
          <?php endfor; ?>
        </div>
        <div class="mt-3">
          <button class="btn btn-primary">💾 Sperrzeiten speichern</button>
        </div>
      </form>
    </div>
  </div>

  <!-- Einmalige Abwesenheiten -->
  <div class="card card-elev">
    <div class="card-body">
      <div class="section-title"><i class="bi bi-calendar-event"></i> Einmalige Abwesenheiten</div>
      <form method="post" class="row g-2 mt-2">
        <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
        <input type="hidden" name="action" value="add_block">
        <div class="col-12 col-md-4">
          <label class="form-label">Von</label>
          <input type="datetime-local" name="start_dt" class="form-control" required>
        </div>
        <div class="col-12 col-md-4">
          <label class="form-label">Bis</label>
          <input type="datetime-local" name="end_dt" class="form-control" required>
        </div>
        <div class="col-12 col-md-3">
          <label class="form-label">Grund (optional)</label>
          <input type="text" name="reason" class="form-control" placeholder="z. B. Arzttermin">
        </div>
        <div class="col-12 col-md-1 d-grid">
          <button class="btn btn-success mt-4">➕</button>
        </div>
      </form>

      <div class="table-responsive mt-3">
        <table class="table table-sm align-middle">
          <thead class="table-light">
            <tr>
              <th>Von</th>
              <th>Bis</th>
              <th>Dauer</th>
              <th>Grund</th>
              <th style="width:110px">Aktion</th>
            </tr>
          </thead>
          <tbody>
            <?php if ($blocks && $blocks->num_rows): while($b = $blocks->fetch_assoc()):
              $ts1 = strtotime($b['start_dt']); $ts2 = strtotime($b['end_dt']);
              $durH = max(0, round(($ts2 - $ts1)/3600, 2));
            ?>
              <tr>
                <td><?= date('d.m.Y H:i', $ts1) ?></td>
                <td><?= date('d.m.Y H:i', $ts2) ?></td>
                <td><?= number_format($durH, 2, ',', '.') ?> h</td>
                <td><?= h($b['reason'] ?? '') ?></td>
                <td>
                  <form method="post" onsubmit="return confirm('Abwesenheit löschen?');" class="d-inline">
                    <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
                    <input type="hidden" name="action" value="del_block">
                    <input type="hidden" name="block_id" value="<?= (int)$b['id'] ?>">
                    <button class="btn btn-sm btn-outline-danger">🗑️</button>
                  </form>
                </td>
              </tr>
            <?php endwhile; else: ?>
              <tr><td colspan="5" class="text-center text-muted py-3">Keine Abwesenheiten erfasst.</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>

    </div>
  </div>
</div>

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