<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css"/>
<div class="text-muted">
    {{ label }}:
    <div class="d-inline-block">
        <input {% if not null %}
            required
        {% endif %} class="form-control" type="text" id="{{ name }}" name="{{ name }}" value="{{ value }}"
            placeholder="{{ placeholder }}" size="30">
    </div>
</div>
<script>
    $(function () {
        let value = "{{value}}";
        let format = '{{ format }}';
        let option = {
            autoUpdateInput: false,
            timePicker: {% if not date %}true{% else %}false{% endif%},
            timePicker24Hour: true,
            locale: {
                format: format,
            },
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            }
        };
        if (value !== '') {
            let s = value.split(' - ')
            option.startDate = moment(s[0]);
            option.endDate = moment(s[1]);
        }

        function cb(start, end) {
            $('#{{name}} span').html(start.format(format) + ' - ' + end.format(format));
        }

        let element = $('#{{name}}');
        element.daterangepicker(option, cb);
        element.on('apply.daterangepicker', function (ev, picker) {
            $(this).val(picker.startDate.format(format) + ' - ' + picker.endDate.format(format));
        });

        element.on('cancel.daterangepicker', function (ev, picker) {
            $(this).val('');
        });

    });
</script>
