<div class="container mt-4">
    <h2>Modifier la fiche de paie</h2>

    <div id="toast-container" style="position: fixed; top: 1rem; right: 1rem; z-index: 9999;"></div>

    <form id="editPayslipForm">
        <input type="hidden" name="id" value="<?= htmlspecialchars($payslip['id']) ?>">

        <div class="mb-3">
            <label for="employee" class="form-label">Employé</label>
            <input type="text" readonly class="form-control"
                   value="<?= htmlspecialchars($payslip['employee_id']) ?> - <?= htmlspecialchars($payslip['last_name'] ?? '') ?> <?= htmlspecialchars($payslip['first_name'] ?? '') ?>">
        </div>

        <div class="mb-3">
            <label for="period" class="form-label">Période</label>
            <input type="text" name="period" id="period" class="form-control"
                   value="<?= htmlspecialchars($payslip['period']) ?>" required>
        </div>

        <div class="mb-3">
            <label for="gross_salary" class="form-label">Salaire brut (€)</label>
            <input type="number" name="gross_salary" id="gross_salary" class="form-control" step="0.01"
                   value="<?= htmlspecialchars($payslip['gross_salary']) ?>" required>
        </div>

        <button type="submit" class="btn btn-primary">Mettre à jour</button>
        <a href="/payslips" class="btn btn-secondary">Annuler</a>
    </form>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
$('#editPayslipForm').on('submit', function (e) {
    e.preventDefault();

    const formData = {
        id: $('input[name="id"]').val(),
        period: $('#period').val(),
        gross_salary: $('#gross_salary').val()
    };

    $.ajax({
        url: '/payslips/update?id=' + formData.id,
        method: 'POST',
        data: formData,
        success: function (response) {
            showToast('Fiche de paie mise à jour avec succès.', 'success');
            setTimeout(() => window.location.href = '/payslips', 1500);
        },
        error: function (xhr) {
            showToast('Erreur lors de la mise à jour.', 'danger');
            console.error(xhr.responseText);
        }
    });
});

function showToast(message, type) {
    const toastHTML = `
        <div class="toast align-items-center text-bg-${type} border-0 show" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="d-flex">
                <div class="toast-body">${message}</div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
        </div>`;
    $('#toast-container').html(toastHTML);
}
</script>
