<?php
session_start();
require_once("inc/config.inc.php");
require_once("inc/functions.inc.php");

$user = check_user();

if (!isset($_SESSION['userid'])) {
    die("Kein Benutzer angemeldet.");
}

if ($_SESSION['admin'] != 1) {
    die("Kein Zugriff.");
}

$admin_id = $_SESSION['userid'];
$message = "";

/* ===== Antrag bearbeiten ===== */
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['vacation_id'])) {

    $vacation_id = (int)$_POST['vacation_id'];
    $action = $_POST['action'];
    $comment_admin = trim($_POST['comment_admin']);

    if ($action == "genehmigen") {
        $status = "genehmigt";
    } elseif ($action == "ablehnen") {
        $status = "abgelehnt";
    } else {
        die("Ungültige Aktion.");
    }

    $stmt = $pdo->prepare("
        UPDATE vacations 
        SET status = ?, 
            approved_by = ?, 
            approved_at = NOW()
        WHERE id = ?
    ");
    $stmt->execute([$status, $admin_id, $vacation_id]);

    $message = "Antrag erfolgreich aktualisiert.";
}

/* ===== Offene Anträge laden ===== */
$stmt = $pdo->prepare("
    SELECT v.*, u.vorname, u.nachname 
    FROM vacations v
    JOIN users u ON u.id = v.user_id
    WHERE v.status = 'beantragt'
    ORDER BY v.start_date ASC
");
$stmt->execute();
$antraege = $stmt->fetchAll();
?>

<?php include 'header.php'; ?>

<div class="container">
<div class="row">
<div class="col-md-12">

<h2>Urlaubsanträge genehmigen</h2>

<?php if ($message): ?>
<div class="alert alert-success"><?php echo $message; ?></div>
<?php endif; ?>

<?php if (count($antraege) == 0): ?>
<div class="alert alert-info">Keine offenen Anträge.</div>
<?php else: ?>

<table class="table table-bordered table-striped">
    <tr>
        <th>Mitarbeiter</th>
        <th>Von</th>
        <th>Bis</th>
        <th>Tage</th>
        <th>Kommentar</th>
        <th>Aktion</th>
    </tr>

<?php foreach ($antraege as $a): ?>
<tr>
    <td><?php echo htmlspecialchars($a['vorname'] . " " . $a['nachname']); ?></td>
    <td><?php echo $a['start_date']; ?></td>
    <td><?php echo $a['end_date']; ?></td>
    <td><?php echo $a['days']; ?></td>
    <td><?php echo htmlspecialchars($a['comment_user']); ?></td>
    <td>

        <form method="post" style="display:inline;">
            <input type="hidden" name="vacation_id" value="<?php echo $a['id']; ?>">
            <input type="hidden" name="action" value="genehmigen">
            <button type="submit" class="btn btn-success btn-sm">
                Genehmigen
            </button>
        </form>

        <form method="post" style="display:inline;">
            <input type="hidden" name="vacation_id" value="<?php echo $a['id']; ?>">
            <input type="hidden" name="action" value="ablehnen">
            <button type="submit" class="btn btn-danger btn-sm">
                Ablehnen
            </button>
        </form>

    </td>
</tr>
<?php endforeach; ?>

</table>

<?php endif; ?>

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

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