<div class="page-title">
    <h1><?php echo $this->user->lang("Email List");?></h1>
    <span><?php echo $this->user->lang("List of emails that have been sent to your clients."); ?></span>
</div>

<div class="cm-holder dt-info">
    <div class="head padding-bottom">
        <div class="dt-header">
            <div class="dt-header-left">
                <div class="dt-filters">

                    <div class="filter-group">
                        <label><?php echo $this->user->lang("Date Created");?></label>
                        <input
                            class="form-control"
                            type="date"
                            name="startdate"
                            id="startdate"
                        />
                        <span class="separator">-</span>
                        <input
                            class="form-control"
                            type="date"
                            name="enddate"
                            id="enddate"
                        />
                    </div>
                </div>
            </div>

            <div class="dt-header-right">
                <div class="filter-group dt-length"></div>
            </div>

        </div>
    </div>
    <div class="dt-wrapper pull-top">
        <div class="table-responsive">
            <table id="email-list" class="display" style="width:100%">
                <thead>
                    <tr>
                        <th></th>
                        <th class="width4 "><?php echo $this->user->lang('User'); ?></th>
                        <th class="width4 "><?php echo $this->user->lang('Subject'); ?></th>
                        <th class=""><?php echo $this->user->lang('Date'); ?></th>
                        <th class=""><?php echo $this->user->lang('To'); ?></th>
                        <th class=""><?php echo $this->user->lang('From'); ?></th>
                    </tr>
                </thead>
            </table>
        </div>
    </div>
</div>

<script data-cfasync="false">
    var emaillist = emaillist || {};

    $(document).ready(function () {
        document.getElementById("startdate").value = parseFormattedDate("<?php echo $this->startDateValue; ?>");
        document.getElementById("enddate").value = parseFormattedDate("<?php echo $this->endDateValue; ?>");

        var ajaxUrl = 'index.php?fuse=clients&action=getemaillist&controller=email&limit=0';
        var table = $('#email-list').DataTable({
            "searching": false,
            "ajax": {
                url: ajaxUrl,
                dataSrc: 'data', // The root is data in the ajax call.
                data: function(d) {
                    d.startdate = formatDate($('#startdate').val());
                    d.enddate = formatDate($('#enddate').val());
                }
            },
            "columns": [
                {
                    "className": 'details-control',
                    "orderable": false,
                    "data": null,
                    "defaultContent": ''
                },
                {
                    "data": "clientName",
                    render: function (data, type, row) {
                        if (type === 'display') {
                            return '<a href="index.php?fuse=clients&controller=userprofile&view=profilecontact&frmClientID=' + row.userId + '">' + row.clientName + '</a>';
                        }

                        return data;
                    }
                },
                { "data": "subject" },
                { "data": "date" },
                { "data": "to" },
                {
                    "data": "sender",
                    render: function (data, type, row) {
                        if (type === 'display') {
                            if (row.fromName == '') {
                                return 'N/A';
                            }

                            return row.fromName + ' (' + row.sender + ')';
                        }

                        return data;
                    }
                }
            ],
            "order": [[3, 'desc']]
        });

        $('#email-list tbody').on('click', 'td.details-control', function () {
            var tr = $(this).closest('tr');
            var row = table.row(tr);

            if (row.child.isShown()) {
                row.child.hide();
                tr.removeClass('shown');
            }
            else {
                var expanderBody = row.data().content;
                row.child(expanderBody).show();
                tr.addClass('shown');
            }
        });

        $('#startdate, #enddate').on('change', function () {
            table.ajax.reload();
        });

        function formatDate(dateString) {
            if (dateString == '') {
                return '';
            }

            date = new Date(dateString+'T12:00:00Z');
            options = {
                day:   "2-digit",
                month: "2-digit",
                year:  "numeric"
            };

            switch (clientexec.dateFormat) {
                case 'm/d/Y':
                    newDate = new Intl.DateTimeFormat("en-US", options).format(date);
                    break;
                case 'd/m/Y':
                    newDate = new Intl.DateTimeFormat("en-GB", options).format(date);
                    break;
            }

            return newDate;
        }

        function parseFormattedDate(dateString) {
            if (dateString == '') {
                return '';
            }

            switch (clientexec.dateFormat) {
                case 'm/d/Y':
                    parts = dateString.split('/');

                    return `${parts[2]}-${parts[0].padStart(2, "0")}-${parts[1].padStart(2, "0")}`;
                case 'd/m/Y':
                    parts = dateString.split('/');

                    return `${parts[2]}-${parts[1].padStart(2, "0")}-${parts[0].padStart(2, "0")}`;
            }
        }
    });
</script>
