<kiss-container class="kiss-margin-small">

    <ul class="kiss-breadcrumbs">
        <li><a href="<?=$this->route('/inbox')?>"><?=t('Inbox')?></a></li>
        <li><span><?=t('Submissions')?></span></li>
    </ul>

    <div class="kiss-flex kiss-flex-middle kiss-margin-bottom">
        <div class="kiss-margin-end">
            <kiss-svg class="kiss-margin-auto" src="<?= $this->base(isset($form['icon']) && $form['icon'] ? $form['icon'] : 'inbox:icon.svg') ?>" width="40" height="40" style="color:<?= ($this->escape($form['color'] ?? 'inherit')) ?>"><canvas width="40" height="40"></canvas></kiss-svg>
        </div>

        <div class="kiss-flex-1">
            <div class="kiss-flex kiss-flex-middle kiss-size-4 kiss-text-bold" gap="small">
                <?=$this->escape($form['name'])?>

                <?php if($this->helper('acl')->isAllowed('inbox/manage')): ?>
                <a class="kiss-size-large" href kiss-popout="#inbox-form-actions"><icon>more_horiz</icon></a>
                <?php endif ?>
            </div>
        </div>

        <?php if($this->helper('acl')->isAllowed('inbox/manage')): ?>
        <script>
            window.copyFormToken = () => {
                App.utils.copyText('<?=$this->escape($form['token'])?>', () => {
                    App.ui.notify('Form token copied!');
                });
            };
        </script>
        <kiss-card class="kiss-padding-small kiss-visible@m kiss-position-relative" theme="bordered contrast">
            <div class="kiss-text-caption kiss-text-bold"><?=t('Form Token')?></div>
            <div class="kiss-size-small kiss-margin-xsmall-top kiss-text-monospace kiss-color-muted">
                <?=$this->escape($form['token'])?> <icon>content_copy</icon>
            </div>
            <a class="kiss-cover" onclick="copyFormToken()"></a>
        </kiss-card>
        <?php endif; ?>

    </div>

    <vue-view>

        <template>

            <form class="kiss-margin" v-if="((!loading && items.length) || filter || staticFilterOptions)" @submit.prevent="filter = txtFilter">

                <div class="kiss-flex kiss-flex-middle" gap="small">

                    <input type="text" class="kiss-input kiss-flex-1" :placeholder="t('Filter submissions...')" v-model="txtFilter">

                    <div class="kiss-button-group kiss-margin-small-start">
                        <button type="button" class="kiss-button" @click="filter = ''" v-if="filter"><?= t('Reset') ?></button>
                        <button class="kiss-button kiss-flex"><?= t('Search') ?></button>
                    </div>
                </div>

                <div class="kiss-flex kiss-flex-middle kiss-margin" gap v-if="staticFilter">

                    <div class="kiss-overlay-input" v-for="(meta,field) in staticFilter" :key="field">
                        <button type="button" class="kiss-button kiss-button-small">
                            <div class="kiss-flex kiss-flex-middle" gap="small">
                                <span>{{ meta.label }}:</span>
                                <span>{{ staticFilterValue[field] || t('All') }}</span>
                                <icon>expand_more</icon>
                            </div>
                        </button>
                        <select v-model="staticFilterValue[field]">
                            <option :value="null">{{ t('All') }}</option>
                            <hr>
                            <option :value="option" v-for="option in meta.options">{{ option }}</option>
                        </select>
                    </div>
                </div>

            </form>

            <app-scrollcontainer mode="boundary-include" boundary="app-actionbar">

                <app-loader class="kiss-margin" v-if="loading"></app-loader>

                <div class="animated fadeIn kiss-height-50vh kiss-flex kiss-flex-middle kiss-flex-center kiss-align-center kiss-color-muted" v-if="!loading && !items.length">
                    <div>
                        <kiss-svg class="kiss-margin-auto" src="<?=$this->base('inbox:assets/icons/submissions.svg')?>" width="40" height="40"><canvas width="40" height="40"></canvas></kiss-svg>
                        <p class="kiss-size-large kiss-text-bold kiss-margin-small-top"><?= t('No submissions') ?></p>
                    </div>
                </div>

                <div class="table-scroll" ref="tblContainer" v-show="!loading && items.length">
                    <table class="kiss-table animated fadeIn" v-if="!loading && items.length">
                        <thead>
                            <tr>
                                <th fixed="left" class="kiss-align-center" width="70">
                                    <div class="kiss-flex kiss-flex-middle">
                                        <input class="kiss-checkbox" type="checkbox" @click="toggleAllSelect">
                                        <span class="kiss-margin-small-start">ID</span>
                                    </div>
                                </th>
                                <th class="kiss-position-relative" v-for="field in fields">
                                    <div class="kiss-flex kiss-flex-middle">
                                        <span>{{ t(field === '_data_' ? 'Data' : field) }}</span>
                                        <span class="kiss-size-6" v-if="sort['data.'+field]">
                                            <icon>{{sort['data.'+field] == 1 ? 'south':'north'}}</icon><span>
                                    </div>
                                    <a class="kiss-cover" @click="sortItems('data.'+field)" v-if="field !== '_data_'"></a>
                                </th>
                                <th class="kiss-position-relative" width="120">
                                    <div class="kiss-flex kiss-flex-middle">
                                        <span><?= t('Created') ?></span>
                                        <span class="kiss-size-6" v-if="sort._created">
                                            <icon>{{sort._created == 1 ? 'south':'north'}}</icon><span>
                                    </div>
                                    <a class="kiss-cover" @click="sortItems('_created')"></a>
                                </th>
                                <th fixed="right" width="20"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="item in items">
                                <td fixed="left" class="kiss-align-center">
                                    <div class="kiss-flex kiss-flex-middle">
                                        <input class="kiss-checkbox" type="checkbox" v-model="selected" :value="item._id">
                                        <a class="kiss-badge kiss-link-muted kiss-margin-small-start" :title="item._id" @click="showSubmission(item)">...{{ item._id.substr(-5) }}</a>
                                    </div>
                                </td>
                                <td class="kiss-position-relative" v-for="field in fields">
                                    <div class="kiss-text-truncate kiss-size-small">{{ preview(field === '_data_' ? item.data : (item.data[field] ?? '')) }}</div>
                                    <a class="kiss-cover" @click="showSubmission(item)"></a>
                                </td>
                                <td><span class="kiss-flex kiss-badge kiss-badge-outline kiss-color-muted"><app-datetime :datetime="item._created" /></span></td>
                                <td class="kiss-align-center" fixed="right">
                                    <a @click="toggleItemActions(item)">
                                        <icon>more_horiz</icon>
                                    </a>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </app-scrollcontainer>

            <teleport to="body">

                <kiss-popout :open="actionItem && 'true'" @popoutclose="toggleItemActions(null)">
                    <kiss-content>
                        <kiss-navlist v-if="actionItem">
                            <ul>
                                <li class="kiss-nav-header">{{ t('Item actions') }}</li>
                                <li>
                                    <a class="kiss-flex kiss-flex-middle" @click="showSubmission(actionItem)">
                                        <icon class="kiss-margin-small-end">visibility</icon>
                                        <?= t('Show submission') ?>
                                    </a>
                                </li>
                                <?php if($this->helper('acl')->isAllowed('inbox/manage')): ?>
                                <li class="kiss-nav-divider"></li>
                                <li>
                                    <a class="kiss-color-danger kiss-flex kiss-flex-middle" @click="remove(actionItem)">
                                        <icon class="kiss-margin-small-end">delete</icon>
                                        <?= t('Delete') ?>
                                    </a>
                                </li>
                                <?php endif; ?>
                            </ul>
                        </kiss-navlist>
                    </kiss-content>
                </kiss-popout>

                <?php if($this->helper('acl')->isAllowed('inbox/manage')): ?>
                <kiss-popout id="inbox-form-actions">
                    <kiss-content>
                        <kiss-navlist class="kiss-margin">
                            <ul>
                                <li class="kiss-nav-header"><?=t('Actions')?></li>
                                <li>
                                    <a class="kiss-flex kiss-flex-middle" onclick="copyFormToken()">
                                        <icon class="kiss-margin-small-end">content_copy</icon>
                                        <?=t('Copy form token')?>
                                    </a>
                                </li>
                                <li class="kiss-nav-divider"></li>
                                <li>
                                    <a class="kiss-flex kiss-flex-middle" href="<?=$this->route("/inbox/forms/form/{$form['_id']}")?>">
                                        <icon class="kiss-margin-small-end">edit</icon>
                                        <?=t('Edit form')?>
                                    </a>
                                </li>
                            </ul>
                        </kiss-navlist>
                    </kiss-content>
                </kiss-popout>
                <?php endif; ?>

                <app-actionbar space="false">

                    <kiss-container>
                        <div class="kiss-flex kiss-flex-middle" gap>
                            <div class="kiss-flex kiss-flex-middle" v-if="!loading && count">
                                <app-pagination>
                                    <div class="kiss-color-muted">{{ `${count} ${count == 1 ? t('Item') : t('Items')}` }}</div>
                                    <a class="kiss-margin-small-start" v-if="(page - 1) >= 1" @click="load(page - 1)"><?= t('Previous') ?></a>
                                    <div class="kiss-margin-small-start kiss-overlay-input" v-if="count > limit">
                                        <strong>{{ page }} &mdash; {{pages}}</strong>
                                        <select v-model="page" @change="load(page)" v-if="pages > 1">
                                            <option v-for="p in pages" :value="p">{{ p }}</option>
                                        </select>
                                    </div>
                                    <a class="kiss-margin-small-start" v-if="(page + 1) <= pages" @click="load(page + 1)"><?= t('Next') ?></a>
                                </app-pagination>
                            </div>
                            <div class="kiss-flex-1"></div>
                            <div v-if="selected.length">
                                <button class="kiss-button kiss-button-danger" @click="removeSelected()">{{ t('Delete') }} -{{ selected.length }}-</button>
                            </div>
                            <a class="kiss-button" href="<?=$this->route("/inbox")?>"><?=t('Close')?></a>
                        </div>
                    </kiss-container>

                </app-actionbar>
            </teleport>
        </template>

        <script type="module">
            export default {

                data() {

                    return {
                        form: <?=json_encode($form)?>,
                        items: [],
                        selected: [],
                        filter: '',
                        sort: {
                            _created: -1
                        },
                        txtFilter: '',
                        page: 1,
                        pages: 1,
                        limit: 25,
                        count: 0,
                        loading: false,
                        actionItem: null,

                        staticFilterValue: {}
                    }
                },

                mounted() {

                    let searchParams = new URLSearchParams(location.search);

                    if (searchParams.has('state')) {
                        try {
                            var q = JSON.parse(App.utils.base64decode(searchParams.get('state')));
                            if (q.sort) this.sort = q.sort;
                            if (q.page) this.page = q.page;
                            if (q.limit) this.limit = (parseInt(q.limit) || this.limit);
                            if (q.filter) {
                                this.filter = q.filter;
                                this.txtFilter = q.filter;
                            }
                        } catch (e) {}
                    }

                    this.load(this.page, false);
                },

                computed: {
                    staticFilter() {
                        if (!this.form._meta?.filter) {
                            return null;
                        }

                        let filter = {};

                        Object.keys(this.form._meta.filter).forEach(field => {
                            if (!Array.isArray(this.form._meta.filter[field].options)) return;

                            filter[field] = this.form._meta.filter[field];
                            filter[field].label = filter[field].label ? filter[field].label : field.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());

                        });

                        return Object.keys(filter).length ? filter : null;
                    },

                    staticFilterOptions() {

                        let filter = {};

                        Object.keys(this.staticFilterValue).forEach(field => {
                            if (this.staticFilterValue[field]) filter[`data.${field}`] = this.staticFilterValue[field];
                        });

                        return Object.keys(filter) ? filter : null;
                    },

                    fields() {
                        return Array.isArray(this.form._meta?.fields) && this.form._meta.fields.length ? this.form._meta.fields : ['_data_'];
                    }
                },

                watch: {
                    filter(val) {
                        this.txtFilter = val;
                        this.load();
                    },

                    staticFilterValue: {
                        handler() {
                            this.load();
                        },
                        deep: true,
                    },
                },

                methods: {

                    preview(data) {

                        let str = '';

                        if (typeof data == 'string') {
                            str = data;
                        } else if (typeof data == 'object') {
                            str = JSON.stringify(Object.values(data || {})).replace(/('null'|\[|\]|\{|\}|"|\\|')/g, '').replace(/,/g, ', ');
                        } else if (typeof data == 'number') {
                            str = data.toString();
                        }

                        return (str.length > 100 ? `${str.slice(0, 100)}...` : str).trim();
                    },

                    toggleItemActions(item) {

                        if (!item) {
                            setTimeout(() => this.actionItem = null, 300);
                            return;
                        }

                        this.actionItem = item;
                    },

                    toggleAllSelect(e) {

                        this.selected = [];

                        if (e.target.checked) {
                            this.items.forEach(item => this.selected.push(item._id));
                        }
                    },

                    remove(item) {

                        App.ui.confirm('Are you sure?', () => {

                            this.$request(`/inbox/submissions/remove/${this.form._id}`, {
                                ids: [item._id]
                            }).then(res => {
                                this.load(this.page == 1 ? 1 : (this.items.length - 1 ? this.page : this.page - 1));
                                App.ui.notify('Submission removed!');
                            });
                        });
                    },

                    removeSelected() {
                        App.ui.confirm('Are you sure?', () => {

                            this.$request(`/inbox/submissions/remove/${this.form._id}`, {
                                ids: this.selected
                            }).then(res => {
                                this.load(this.page == 1 ? 1 : (this.items.length - this.selected.length ? this.page : this.page - 1));
                                App.ui.notify('Submissions removed!');
                            });
                        });
                    },

                    load(page = 1, history = true) {

                        let options = {
                            filter: {},
                            limit: this.limit,
                            skip: (page - 1) * this.limit,
                            sort: this.sort
                        };

                        this.loading = true;
                        this.selected = [];

                        if (this.filter) {
                            options.query = this.filter;
                        }

                        if (this.staticFilterOptions) {
                            options.filter = this.staticFilterOptions;
                        }

                        if (history) {

                            window.history.pushState(
                                null, null,
                                App.route(['/inbox/submissions/form/', this.form._id, '?state=', App.utils.base64encode(JSON.stringify({
                                    page: this.page || null,
                                    filter: this.filter || null,
                                    sort: this.sort || null,
                                    limit: this.limit
                                }))].join(''))
                            );
                        }

                        this.$request(`/inbox/submissions/load/${this.form._id}`, {
                            options
                        }).then(rsp => {
                            this.items = rsp.items;
                            this.page = rsp.page;
                            this.pages = rsp.pages;
                            this.count = rsp.count;

                            this.loading = false;
                        })
                    },

                    sortItems(field) {

                        if (this.sort[field]) {
                            this.sort[field] = this.sort[field] == 1 ? -1 : 1;
                        } else {
                            this.sort = {};
                            this.sort[field] = 1;
                        }

                        this.load();
                    },

                    showSubmission(submission) {
                        VueView.ui.offcanvas('inbox:assets/dialogs/submission.js', {submission});
                    },

                }
            }
        </script>

    </vue-view>


</kiss-container>
