<?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.");
}

$user_id = (int)$_SESSION['userid'];
$canManageTeamVacations = can_manage_team_vacations();
$message = "";
$error = "";
$selected_user_id = $user_id;

$selectableUsers = [];
if ($canManageTeamVacations) {
    $stmtUsers = $pdo->prepare("
        SELECT id, vorname, nachname, email
        FROM users
        WHERE zeiterfassung = 1
        ORDER BY nachname, vorname
    ");
    $stmtUsers->execute();
    $selectableUsers = $stmtUsers->fetchAll(PDO::FETCH_ASSOC);
}

function calculateWorkingDays($start, $end) {
    $start = new DateTime($start);
    $end = new DateTime($end);
    $end->modify('+1 day');

    $interval = new DateInterval('P1D');
    $period = new DatePeriod($start, $interval, $end);

    $workingDays = 0;
    foreach ($period as $day) {
        if ($day->format('N') < 6) {
            $workingDays++;
        }
    }

    return $workingDays;
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $start_date = trim((string)($_POST['start_date'] ?? ''));
    $end_date = trim((string)($_POST['end_date'] ?? ''));
    $comment = trim((string)($_POST['comment'] ?? ''));
    $selected_user_id = $canManageTeamVacations ? (int)($_POST['user_id'] ?? $user_id) : $user_id;

    $selectedUser = null;
    if ($selected_user_id <= 0) {
        $error = "Bitte einen Mitarbeiter auswaehlen.";
    } else {
        $stmtSelectedUser = $pdo->prepare("
            SELECT id, vorname, nachname
            FROM users
            WHERE id = ?
              AND zeiterfassung = 1
            LIMIT 1
        ");
        $stmtSelectedUser->execute([$selected_user_id]);
        $selectedUser = $stmtSelectedUser->fetch(PDO::FETCH_ASSOC);

        if (!$selectedUser) {
            $error = "Der ausgewaehlte Mitarbeiter wurde nicht gefunden.";
        }
    }

    if ($error === "" && ($start_date === '' || $end_date === '')) {
        $error = "Bitte beide Datumsfelder ausfuellen.";
    } elseif ($error === "" && $start_date > $end_date) {
        $error = "Enddatum liegt vor dem Startdatum.";
    } elseif ($error === "" && $start_date < date("Y-m-d")) {
        $error = "Urlaub kann nicht in der Vergangenheit beantragt werden.";
    } elseif ($error === "") {
        $stmt = $pdo->prepare("
            SELECT COUNT(*)
            FROM vacations
            WHERE user_id = ?
              AND status != 'abgelehnt'
              AND (
                  (start_date BETWEEN ? AND ?)
                  OR (end_date BETWEEN ? AND ?)
                  OR (? BETWEEN start_date AND end_date)
              )
        ");
        $stmt->execute([$selected_user_id, $start_date, $end_date, $start_date, $end_date, $start_date]);
        $exists = (int)$stmt->fetchColumn();

        if ($exists > 0) {
            $error = "Der Zeitraum ueberschneidet sich mit einem bestehenden Antrag.";
        } else {
            $days = calculateWorkingDays($start_date, $end_date);

            $insert = $pdo->prepare("
                INSERT INTO vacations (user_id, start_date, end_date, days, comment_user)
                VALUES (?, ?, ?, ?, ?)
            ");
            $insert->execute([$selected_user_id, $start_date, $end_date, $days, $comment]);

            if ($selected_user_id !== $user_id && $selectedUser) {
                $message = "Urlaub fuer " . $selectedUser['vorname'] . " " . $selectedUser['nachname'] . " erfolgreich eingereicht ($days Werktage).";
            } else {
                $message = "Urlaubsantrag erfolgreich eingereicht ($days Werktage).";
            }
        }
    }
}
?>

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

<div class="container">
<div class="row">
<div class="col-md-8 offset-md-2">

<h2>Urlaubsantrag</h2>

<?php if ($error): ?>
<div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
<?php endif; ?>

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

<form method="post">

    <?php if ($canManageTeamVacations): ?>
    <div class="form-group">
        <label>Mitarbeiter:</label>
        <select name="user_id" class="form-control" required>
            <?php foreach ($selectableUsers as $employee): ?>
                <?php $employeeId = (int)$employee['id']; ?>
                <option value="<?php echo $employeeId; ?>" <?php echo ($selected_user_id === $employeeId) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars(trim($employee['nachname'] . ', ' . $employee['vorname'] . ' | ' . $employee['email'])); ?>
                </option>
            <?php endforeach; ?>
        </select>
    </div>
    <?php endif; ?>

    <div class="form-group">
        <label>Von:</label>
        <input type="date" name="start_date" class="form-control" required>
    </div>

    <div class="form-group">
        <label>Bis:</label>
        <input type="date" name="end_date" class="form-control" required>
    </div>

    <div class="form-group">
        <label>Kommentar (optional):</label>
        <textarea name="comment" class="form-control"></textarea>
    </div>

    <br>

    <button type="submit" class="btn btn-primary btn-block">
        <?php echo $canManageTeamVacations ? 'Urlaub eintragen' : 'Urlaub beantragen'; ?>
    </button>

</form>

<hr>

<h4><?php echo $canManageTeamVacations ? 'Urlaubseintraege' : 'Meine Antraege'; ?></h4>

<?php
$listSql = "
    SELECT v.*, u.vorname, u.nachname
    FROM vacations v
    JOIN users u ON u.id = v.user_id
";

if ($canManageTeamVacations) {
    $listSql .= " ORDER BY v.created_at DESC";
    $stmt = $pdo->prepare($listSql);
    $stmt->execute();
} else {
    $listSql .= " WHERE v.user_id = ? ORDER BY v.created_at DESC";
    $stmt = $pdo->prepare($listSql);
    $stmt->execute([$user_id]);
}

$antraege = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<table class="table table-bordered">
    <tr>
        <?php if ($canManageTeamVacations): ?>
        <th>Mitarbeiter</th>
        <?php endif; ?>
        <th>Von</th>
        <th>Bis</th>
        <th>Tage</th>
        <th>Status</th>
        <th>Aktion</th>
    </tr>

<?php foreach ($antraege as $a): ?>
<tr>
    <?php if ($canManageTeamVacations): ?>
    <td><?php echo htmlspecialchars(trim($a['vorname'] . ' ' . $a['nachname'])); ?></td>
    <?php endif; ?>
    <td><?php echo htmlspecialchars((string)$a['start_date']); ?></td>
    <td><?php echo htmlspecialchars((string)$a['end_date']); ?></td>
    <td><?php echo (int)$a['days']; ?></td>
    <td>
        <?php
        if ($a['status'] === 'beantragt' || $a['status'] === null || $a['status'] === '') {
            echo '<span class="badge badge-warning">Beantragt</span>';
        } elseif ($a['status'] === 'genehmigt') {
            echo '<span class="badge badge-success">Genehmigt</span>';
        } else {
            echo '<span class="badge badge-danger">Abgelehnt</span>';
        }
        ?>
    </td>
    <td>
        <form method="post" action="deleteVacation.php" onsubmit="return confirm('Wirklich loeschen?');">
            <input type="hidden" name="id" value="<?php echo (int)$a['id']; ?>">
            <input type="hidden" name="referer" value="urlaubsantrag.php">
            <button type="submit" class="btn btn-sm btn-danger">Loeschen</button>
        </form>
    </td>
</tr>
<?php endforeach; ?>

</table>

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

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