<?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 = $_SESSION['userid'];
$message = "";
$error = "";

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) { // 1 (Mo) - 5 (Fr)
            $workingDays++;
        }
    }

    return $workingDays;
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $start_date = $_POST['start_date'];
    $end_date = $_POST['end_date'];
    $comment = trim($_POST['comment']);

    if (empty($start_date) || empty($end_date)) {
        $error = "Bitte beide Datumsfelder ausfüllen.";
    } elseif ($start_date > $end_date) {
        $error = "Enddatum liegt vor dem Startdatum.";
    } elseif ($start_date < date("Y-m-d")) {
        $error = "Urlaub kann nicht in der Vergangenheit beantragt werden.";
    } else {

        // Überschneidung prüfen
        $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([$user_id, $start_date, $end_date, $start_date, $end_date, $start_date]);
        $exists = $stmt->fetchColumn();

        if ($exists > 0) {
            $error = "Der Zeitraum überschneidet 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([$user_id, $start_date, $end_date, $days, $comment]);

            $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 $error; ?></div>
<?php endif; ?>

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

<form method="post">

    <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">
        Urlaub beantragen
    </button>

</form>

<hr>

<h4>Meine Anträge</h4>

<?php
$stmt = $pdo->prepare("
    SELECT * FROM vacations 
    WHERE user_id = ?
    ORDER BY created_at DESC
");
$stmt->execute([$user_id]);
$antraege = $stmt->fetchAll();
?>

<table class="table table-bordered">
    <tr>
        <th>Von</th>
        <th>Bis</th>
        <th>Tage</th>
        <th>Status</th>
        <th>Aktion</th>
    </tr>

<?php foreach ($antraege as $a): ?>
<tr>
    <td><?php echo $a['start_date']; ?></td>
    <td><?php echo $a['end_date']; ?></td>
    <td><?php echo $a['days']; ?></td>
    <td>
        <?php
        if ($a['status'] == 'beantragt') {
            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 löschen?');">
            <input type="hidden" name="id" value="<?php echo $a['id']; ?>">
            <input type="hidden" name="referer" value="urlaubsantrag.php">
            <button type="submit" class="btn btn-sm btn-danger">Löschen</button>
        </form>
    </td>
</tr>
<?php endforeach; ?>

</table>

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

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