<?php
include('inc/check_login.php');
include('inc/db.php');
require_once 'inc/helpers.php';

$message = '';
$message_type = '';
$logged_in_user_id = (int)($_SESSION['user_id'] ?? 1);

// --- Hinzufügen ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] == 'add_vacation') {
    $start_date = $_POST['start_date'] ?? '';
    $end_date = $_POST['end_date'] ?? '';

    if (empty($start_date) || empty($end_date)) {
        $message = "Bitte geben Sie ein Start- und Enddatum an.";
        $message_type = "danger";
    } elseif (strtotime($end_date) < strtotime($start_date)) {
        $message = "Das Enddatum kann nicht vor dem Startdatum liegen.";
        $message_type = "danger";
    } else {
        $stmt = mysqli_prepare($conn, "INSERT INTO vacations (user_id, start_date, end_date) VALUES (?, ?, ?)");
        if ($stmt) {
            mysqli_stmt_bind_param($stmt, "iss", $logged_in_user_id, $start_date, $end_date);
            if (mysqli_stmt_execute($stmt)) {
                $message = "Urlaub erfolgreich hinzugefügt.";
                $message_type = "success";
            } else {
                $message = "Fehler beim Hinzufügen des Urlaubs.";
                $message_type = "danger";
            }
            mysqli_stmt_close($stmt);
        }
    }
}

// --- Löschen ---
if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
    $vacation_id = (int)$_GET['id'];
    $stmt = mysqli_prepare($conn, "DELETE FROM vacations WHERE id = ? AND user_id = ?");
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, "ii", $vacation_id, $logged_in_user_id);
        if (mysqli_stmt_execute($stmt)) {
            $message = "Urlaub erfolgreich gelöscht.";
            $message_type = "success";
        } else {
            $message = "Fehler beim Löschen des Urlaubs.";
            $message_type = "danger";
        }
        mysqli_stmt_close($stmt);
    }
}

// --- Eigene Abwesenheiten (nur aktuell oder zukünftig) ---
$vacations = [];
$stmt = mysqli_prepare($conn, "
    SELECT id, start_date, end_date 
    FROM vacations 
    WHERE user_id = ? 
      AND end_date >= CURDATE() 
    ORDER BY start_date ASC
");
if ($stmt) {
    mysqli_stmt_bind_param($stmt, "i", $logged_in_user_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    while ($row = mysqli_fetch_assoc($result)) {
        $vacations[] = $row;
    }
    mysqli_stmt_close($stmt);
}

// --- Prüfen, ob Admin ---
$is_admin = false;
$stmt = mysqli_prepare($conn, "SELECT role FROM users WHERE id = ?");
if ($stmt) {
    mysqli_stmt_bind_param($stmt, "i", $logged_in_user_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $user = mysqli_fetch_assoc($result);
    $is_admin = ($user && $user['role'] === 'admin');
    mysqli_stmt_close($stmt);
}

// --- Alle Abwesenheiten (nur aktuell oder zukünftig, nur für Admins) ---
$all_vacations = [];
if ($is_admin) {
    $stmt = mysqli_prepare($conn, "
        SELECT v.id, v.start_date, v.end_date, u.username 
        FROM vacations v
        JOIN users u ON v.user_id = u.id
        WHERE v.end_date >= CURDATE()
        ORDER BY v.start_date ASC, u.username ASC
    ");
    if ($stmt) {
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        while ($row = mysqli_fetch_assoc($result)) {
            $all_vacations[] = $row;
        }
        mysqli_stmt_close($stmt);
    }
}

require_once 'inc/header.php';
?>

<div class="container mt-5">
    <?php if ($message): ?>
        <div class="alert alert-<?= htmlspecialchars($message_type) ?> alert-dismissible fade show" role="alert">
            <?= htmlspecialchars($message) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="mb-0">Abwesenheitsassistent</h2>
    </div>

    <!-- Eigenen Urlaub eintragen -->
    <div class="card shadow mb-4">
        <div class="card-header bg-primary-subtle text-secondary">
            <h4 class="mb-0">Urlaub eintragen</h4>
        </div>
        <div class="card-body">
            <form action="vacation.php" method="post">
                <input type="hidden" name="action" value="add_vacation">
                <div class="row g-3">
                    <div class="col-md-5">
                        <label class="form-label">Startdatum</label>
                        <input type="date" class="form-control" name="start_date" required>
                    </div>
                    <div class="col-md-5">
                        <label class="form-label">Enddatum</label>
                        <input type="date" class="form-control" name="end_date" required>
                    </div>
                    <div class="col-md-2 d-flex align-items-end">
                        <button type="submit" class="btn btn-sm btn-outline-primary w-100">Hinzufügen</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Eigene Abwesenheiten -->
    <div class="card shadow">
        <div class="card-header bg-secondary bg-opacity-50 text-secondary">
            <h4 class="mb-0">Eingetragene Urlaube</h4>
        </div>
        <div class="card-body">
            <?php if (empty($vacations)): ?>
                <p class="text-muted text-center">Es sind keine aktuellen oder zukünftigen Urlaube eingetragen.</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>Zeitraum</th>
                                <th class="text-end">Aktionen</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($vacations as $vacation): ?>
                                <tr>
                                    <td>
                                        Vom <?= date('d.m.Y', strtotime($vacation['start_date'])) ?> bis <?= date('d.m.Y', strtotime($vacation['end_date'])) ?>
                                    </td>
                                    <td class="text-end align-middle">
                                        <div class="dropdown">
                                            <a href="#" class="text-secondary" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                                                <span class="material-icons">more_vert</span>
                                            </a>
                                            <ul class="dropdown-menu dropdown-menu-end">
                                                <li>
                                                    <a class="dropdown-item d-flex align-items-center text-danger"
                                                        href="vacation.php?action=delete&id=<?= htmlspecialchars($vacation['id']) ?>"
                                                        onclick="return confirm('Wirklich löschen?')">
                                                        <span class="material-icons me-2">delete_outline</span> Löschen
                                                    </a>
                                                </li>
                                            </ul>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Alle Abwesenheiten (nur für Admins) -->
    <?php if ($is_admin && !empty($all_vacations)): ?>
        <div class="card shadow mt-4">
            <div class="card-header bg-info bg-opacity-25 text-dark">
                <h4 class="mb-0">Abwesenheiten aller Nutzer (aktuell & zukünftig)</h4>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>Nutzer</th>
                                <th>Zeitraum</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($all_vacations as $vac): ?>
                                <tr>
                                    <td><?= htmlspecialchars($vac['username']) ?></td>
                                    <td>
                                        Vom <?= date('d.m.Y', strtotime($vac['start_date'])) ?>
                                        bis <?= date('d.m.Y', strtotime($vac['end_date'])) ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    <?php endif; ?>

</div>

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