<?php
session_start();
require_once('inc/config.inc.php');
require_once('inc/functions.inc.php');
require_once(__DIR__ . '/../inc/company_holiday_sync.inc.php');

$user = check_user();
if (!is_admin_user()) {
    die('Zugriff verweigert. Nur Chefs duerfen Betriebsurlaub verwalten.');
}

$error = '';
$schemaError = '';

try {
    vacationSyncEnsureSchema($pdo);
} catch (Throwable $e) {
    $schemaError = 'Die Seite konnte das Urlaubsschema nicht automatisch aktualisieren: ' . $e->getMessage();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['start_date']) && isset($_POST['end_date'])) {
    $start = trim((string)($_POST['start_date'] ?? ''));
    $end = trim((string)($_POST['end_date'] ?? ''));
    $desc = trim((string)($_POST['description'] ?? 'Betriebsurlaub'));
    $vertretung = trim((string)($_POST['vertretung'] ?? ''));
    $vertretertelefon = trim((string)($_POST['vertretertelefon'] ?? ''));
    $vertreteradresse = trim((string)($_POST['vertreteradresse'] ?? ''));
    $vertreterurl = trim((string)($_POST['vertreterurl'] ?? ''));

    if ($start === '' || $end === '') {
        $error = 'Bitte Start- und Enddatum angeben.';
    } elseif ($start > $end) {
        $error = 'Das Enddatum darf nicht vor dem Startdatum liegen.';
    } elseif ($vertretung === '' || $vertretertelefon === '' || $vertreteradresse === '' || $vertreterurl === '') {
        $error = 'Bitte alle Vertreterinformationen vollstaendig ausfuellen.';
    } elseif ($schemaError !== '') {
        $error = $schemaError;
    } else {
        $stmt = $pdo->prepare("
            INSERT INTO company_holidays (
                start_date, end_date, description, vertretung, vertretertelefon, vertreteradresse, vertreterurl, created_by
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            $start,
            $end,
            $desc,
            $vertretung,
            $vertretertelefon,
            $vertreteradresse,
            $vertreterurl,
            $_SESSION['userid']
        ]);
        vacationSyncUrlaubFromCompanyHoliday($pdo, (int)$pdo->lastInsertId());

        header('Location: company_holidays.php');
        exit();
    }
}

include 'header.php';

$stmt = $pdo->prepare("SELECT * FROM company_holidays ORDER BY start_date DESC");
$stmt->execute();
$holidays = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="container">
    <h2>Betriebsurlaub verwalten</h2>

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

    <form method="post" class="mb-3">
        <div class="form-row">
            <div class="form-group col-md-3">
                <label>Von:</label>
                <input type="date" name="start_date" class="form-control" required>
            </div>
            <div class="form-group col-md-3">
                <label>Bis:</label>
                <input type="date" name="end_date" class="form-control" required>
            </div>
            <div class="form-group col-md-6">
                <label>Beschreibung:</label>
                <input type="text" name="description" class="form-control" placeholder="z. B. Betriebsurlaub Weihnachten">
            </div>
        </div>
        <div class="form-row">
            <div class="form-group col-md-6">
                <label>Vertretung:</label>
                <input type="text" name="vertretung" class="form-control" required>
            </div>
            <div class="form-group col-md-6">
                <label>Vertretung Telefon:</label>
                <input type="text" name="vertretertelefon" class="form-control" required>
            </div>
        </div>
        <div class="form-row">
            <div class="form-group col-md-8">
                <label>Vertretung Adresse:</label>
                <input type="text" name="vertreteradresse" class="form-control" required>
            </div>
            <div class="form-group col-md-4">
                <label>Vertretung Webseite:</label>
                <input type="text" name="vertreterurl" class="form-control" required>
            </div>
        </div>
        <button class="btn btn-primary">Hinzufuegen</button>
    </form>

    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Von</th>
                <th>Bis</th>
                <th>Beschreibung</th>
                <th>Vertretung</th>
                <th>Kontakt</th>
                <th>Erstellt von</th>
                <th>Aktion</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($holidays as $h): ?>
            <tr>
                <td><?php echo htmlspecialchars((string)$h['start_date']); ?></td>
                <td><?php echo htmlspecialchars((string)$h['end_date']); ?></td>
                <td><?php echo htmlspecialchars((string)$h['description']); ?></td>
                <td><?php echo htmlspecialchars((string)$h['vertretung']); ?></td>
                <td>
                    <?php echo htmlspecialchars((string)$h['vertretertelefon']); ?><br>
                    <?php echo htmlspecialchars((string)$h['vertreteradresse']); ?><br>
                    <?php echo htmlspecialchars((string)$h['vertreterurl']); ?>
                </td>
                <td><?php
                    $s = $pdo->prepare("SELECT vorname, nachname FROM users WHERE id = ?");
                    $s->execute([$h['created_by']]);
                    $u = $s->fetch(PDO::FETCH_ASSOC);
                    echo htmlspecialchars(trim(($u['vorname'] ?? '') . ' ' . ($u['nachname'] ?? '')));
                ?></td>
                <td>
                    <form method="post" action="deleteCompanyHoliday.php" onsubmit="return confirm('Betriebsurlaub wirklich loeschen?');">
                        <input type="hidden" name="id" value="<?php echo (int)$h['id']; ?>">
                        <button class="btn btn-sm btn-danger">Loeschen</button>
                    </form>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>

</div>

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