<?php
$collection = $this->getParam('collection', []);
$rules = $collection->getAttribute('rules', []);
?>

<div
    data-service="database.getCollection"
    data-param-collection-id="{{router.params.id}}"
    data-scope="sdk"
    data-event="load,database.updateCollection"
    data-name="project-collection">

    <div class="cover">
        <h1 class="zone xl margin-bottom-large">
            <a data-ls-attrs="href=/console/database?project={{router.params.project}}" class="back text-size-small"><i class="icon-left-open"></i> Database</a>

            <br />

            <span data-ls-bind="{{project-collection.name}}">&nbsp;&nbsp;</span>
        </h1>
    </div>

    <div data-ui-modal class="modal width-large box close" data-button-hide="on" data-open-event="open-json">
        <button type="button" class="close pull-end" data-ui-modal-close=""><i class="icon-cancel"></i></button>    
        
        <h2>JSON View</h2>

        <div class="margin-bottom">
            <input type="hidden" data-ls-bind="{{project-collection}}" data-forms-code />
        </div>

        <button data-ui-modal-close="" type="button" class="reverse">Cancel</button>
    </div>

    <div class="zone xl">
        <ul class="phases clear" data-ui-phases data-selected="{{router.params.tab}}">
            <li data-state="/console/database/collection?id={{router.params.id}}&project={{router.params.project}}">
                <a data-ls-if="{{project-collection.rules.length}} > 0" data-ls-attrs="href=/console/database/document?collection={{router.params.id}}&project={{router.params.project}}&buster={{project-collection.dateUpdated}}" class="button fly round text-align-center">
                    <i class="icon-plus"></i>
                </a>

                <h2>Documents</h2>

                <form class="box padding-small margin-bottom search"
                    data-service="database.listDocuments"
                    data-event="submit"
                    data-param-collection-id="{{router.params.id}}"
                    data-param-search="{{router.params.search}}"
                    data-param-limit="<?php echo APP_PAGING_LIMIT; ?>"
                    data-param-offset=""
                    data-param-order-type="DESC"
                    data-scope="sdk"
                    data-name="project-documents"
                    data-success="state"
                    data-success-param-state-keys="search,offset">
                    <div class="row thin responsive">
                        <div class="col span-10">
                            <input name="search" id="searchDocuments" type="search" autocomplete="off" placeholder="Search" class="margin-bottom-no" data-ls-bind="{{router.params.search}}">
                        </div>
                        <div class="col span-2 desktops-only">
                            <button class="fill" title="Search" aria-label="Search"><i class="icon-search"></i></button>
                        </div>
                    </div>
                </form>

                <div
                    data-service="database.listDocuments"
                    data-event="load,database.createDocument,database.updateDocument,database.deleteDocument"
                    data-param-collection-id="{{router.params.id}}"
                    data-param-search="{{router.params.search}}"
                    data-param-limit="<?php echo APP_PAGING_LIMIT; ?>"
                    data-param-offset="{{router.params.offset}}"
                    data-param-order-type="DESC"
                    data-scope="sdk"
                    data-name="project-documents">

                    <div data-ls-if="0 == {{project-documents.sum}}" class="box margin-bottom">
                        <h3 class="margin-bottom-small text-bold">No Documnets Found</h3>

                        <p class="margin-bottom-no">Create your first document to get started</p>
                    </div>

                    <div data-ls-if="({{project-documents.sum}})">
                        <div class="margin-bottom-small margin-end-small text-align-end text-size-small"><span data-ls-bind="{{project-documents.sum}}"></span> documents found</div>
                        
                        <div class="box margin-bottom y-scroll">
                            <table class="vertical">
                                <thead>
                                    <tr>
                                        <?php foreach($rules as $rule):
                                            $label = (isset($rule['label'])) ? $rule['label'] : '';
                                            ?>
                                            <th width="120"><?php echo $this->escape($label); ?></th>
                                        <?php endforeach; ?>
                                    </tr>
                                </thead>
                                <tbody data-ls-loop="project-documents.documents" data-ls-as="node">
                                    <tr>
                                        <?php foreach($rules as $rule):
                                            $label = (isset($rule['label'])) ? $rule['label'] : '';
                                            $key = (isset($rule['key'])) ? $rule['key'] : '';
                                            $type = (isset($rule['type'])) ? $rule['type'] : '';
                                            $array = (isset($rule['array'])) ? $rule['array'] : '';
                                            ?>
                                            <td data-title="<?php echo $this->escape($label); ?>: " class="text-size-small text-height-small">
                                                <a data-ls-attrs="href=/console/database/document?id={{node.$id}}&collection={{router.params.id}}&project={{router.params.project}}&buster={{project-collection.dateUpdated}}">
                                                    <?php if(!$array): ?>
                                                        <?php switch($type):
                                                            case 'fileId': ?>
                                                                <img data-ls-if="{{node.<?php echo $this->escape($key); ?>}} != ''" src="" data-ls-attrs="src=//{{env.DOMAIN}}/v1/storage/files/{{node.<?php echo $this->escape($key); ?>}}/preview?width=65&height=65&project={{router.params.project}}&mode=admin" class="avatar" width="30" height="30" loading="lazy" />
                                                            <?php break; ?>
                                                            <?php case 'document': ?>
                                                                {...}
                                                            <?php break; ?>
                                                            <?php default: ?>
                                                                <span data-ls-bind="{{node.<?php echo $this->escape($key); ?>}}" data-ls-attrs="title={{node.<?php echo $this->escape($key); ?>}}"></span>
                                                            <?php break; ?>
                                                        <?php endswitch; ?>
                                                    <?php else: ?>
                                                        [...]
                                                    <?php endif; ?>
                                                </a>
                                            </td>
                                        <?php endforeach; ?>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div class="clear text-align-center paging">
                        <form
                            data-service="database.listDocuments"
                            data-event="submit"
                            data-param-collection-id="{{router.params.id}}"
                            data-param-search="{{router.params.search}}"
                            data-param-limit="<?php echo APP_PAGING_LIMIT; ?>"
                            data-param-order-type="DESC"
                            data-scope="sdk"
                            data-name="project-documents"
                            data-success="state"
                            data-success-param-state-keys="search,offset">
                            <button name="offset" data-paging-back data-offset="{{router.params.offset}}" data-sum="{{project-documents.sum}}" class="margin-end round small" aria-label="Back"><i class="icon-left-open"></i></button>
                        </form>

                        <span data-ls-bind="{{router.params.offset|pageCurrent}} / {{project-documents.sum|pageTotal}}"></span>

                        <form
                            data-service="database.listDocuments"
                            data-event="submit"
                            data-param-collection-id="{{router.params.id}}"
                            data-param-search="{{router.params.search}}"
                            data-param-limit="<?php echo APP_PAGING_LIMIT; ?>"
                            data-param-order-type="DESC"
                            data-scope="sdk"
                            data-name="project-documents"
                            data-success="state"
                            data-success-param-state-keys="search,offset">
                            <button name="offset" data-paging-next data-offset="{{router.params.offset}}" data-sum="{{project-documents.sum}}" class="margin-start round small" aria-label="Next"><i class="icon-right-open"></i></button>
                        </form>
                    </div>
                </div>
            </li>
            <li data-state="/console/database/collection/settings?id={{router.params.id}}&project={{router.params.project}}">
                <h2>Settings</h2>

                <div class="row responsive margin-top-negative">
                    <div class="col span-8 margin-bottom">
                        <form
                            data-analytics-event="submit"
                            data-analytics-category="console"
                            data-analytics-label="Update Database Collection"
                            data-service="database.updateCollection"
                            data-scope="sdk"
                            data-event="submit"
                            data-param-collection-id="{{router.params.id}}"
                            data-success="alert,trigger"
                            data-success-param-alert-text="Updated collection successfully"
                            data-success-param-trigger-events="database.updateCollection"
                            data-failure="alert"
                            data-failure-param-alert-text="Failed to update collection"
                            data-failure-param-alert-classname="error">

                            <label>&nbsp;</label>

                            <div class="box">
                                <label for="collection-name">Name</label>
                                <input name="name" id="collection-name" type="text" autocomplete="off" data-ls-bind="{{project-collection.name}}" data-forms-text-direction required placeholder="Collection Name" />
                                
                                <h3 class="margin-bottom-small">Rules</h3>

                                <div data-ls-if="(!{{project-collection.rules.length}})">
                                    <hr class="margin-bottom-no margin-top-no" />
                                    <div class="margin-bottom-xl margin-top-xl margin-end margin-start text-align-center">
                                        <h4 class="text-fade text-size-small">No attribute rules added yet.</h4>
                                    </div>
                                </div>

                                <input type="hidden" id="rulesInit" name="rules" data-cast-to="array-empty">

                                <div data-ls-if="({{project-collection.rules.length}})">
                                    <ul data-ls-loop="project-collection.rules" data-ls-as="rule" class="sortable">
                                        <li data-forms-remove data-forms-move-up  data-forms-move-down>
                                            <div class="toggle list sorts" data-ls-ui-open>
                                                <i class="icon-up-open pull-end margin-top-tiny"></i>
                                                <i class="icon-down-open pull-end margin-top-tiny"></i>
                                    
                                                <h4 class="margin-bottom">
                                                    <div class="pull-start margin-end-large margin-bottom-small">
                                                        <button type="button" disabled class="margin-bottom strip round" data-move-down><i class="icon-down-dir"></i></button>
                                                        <button type="button" class="margin-bottom strip round" data-move-down><i class="icon-down-dir"></i></button>
                                                        <button type="button" class="margin-bottom strip round" data-move-up><i class="icon-up-dir"></i></button>
                                                        <button type="button" disabled class="margin-bottom strip round" data-move-up><i class="icon-up-dir"></i></button>
                                                    </div>

                                                    <span data-ls-bind="{{rule.label}}"></span>

                                                    <span data-ls-if="({{rule.array}}.toString() == 'false')">
                                                        <span class="text-fade text-size-small" data-ls-bind="&nbsp;{{rule.type}}&nbsp;"></span>
                                                    </span>

                                                    <span data-ls-if="({{rule.array}}.toString() == 'true')">
                                                        <span class="text-size-small text-fade" data-ls-bind="&nbsp;{{rule.type}}[]&nbsp;"></span>
                                                    </span>

                                                    <div data-ls-if="{{rule.required}}.toString() == 'true'">
                                                        <span class="text-size-xs text-danger text-fade">required</span>
                                                    </div>

                                                    <div data-ls-if="({{rule.required}}.toString() == 'false')">
                                                        <span class="text-size-xs text-fade">optional</span>
                                                    </div>
                                                </h4>

                                                <hr class="margin-top-no fade" />

                                                <fieldset data-ls-attrs="name=rules" data-cast-to="array">
                                                    <input name="$id" type="hidden" data-ls-bind="{{rule.$id}}" />
                                                    <input name="$collection" type="hidden" data-ls-bind="{{rule.$collection}}" />
                                                    
                                                    <div class="row thin">
                                                        <div class="col span-6">
                                                            <label data-ls-attrs="for=rule-label-{{rule.$id}}">Label
                                                                <span class="tooltip" data-tooltip="Attribute internal display name"><i class="icon-info-circled"></i></span>
                                                            </label>
                                                            <input name="label" type="text" data-ls-bind="{{rule.label}}" />
                                                        </div>
                                                        <div class="col span-6">
                                                            <label data-ls-attrs="for=rule-key-{{rule.$id}}">Key
                                                                <span class="tooltip small" data-tooltip="Attribute key name. Used as the document JSON key in the Database API"><i class="icon-info-circled"></i></span>
                                                            </label>
                                                            <div class="input-copy">
                                                                <input data-forms-copy name="key" type="text" data-ls-bind="{{rule.key}}" max="32" pattern="^(\d|\w)+$" title="No spaces or special charts allowed" />
                                                            </div>
                                                        </div>
                                                    </div>

                                                    <label data-ls-attrs="for=rule-type-{{rule.$id}}">Rule Type</label>

                                                    <select data-ls-attrs="id=rule-type-{{rule.$id}}" name="type" required data-ls-bind="{{rule.type}}">
                                                        <optgroup label="General">
                                                            <option value="text">Text</option>
                                                            <option value="numeric">Numeric</option>
                                                            <option value="boolean">Boolean</option>
                                                            <option value="wildcard">Wildcard (*)</option>
                                                        </optgroup>
                                                        <!-- <optgroup label="Links">
                                                            <option value="fileId">File ID</option>
                                                            <option value="documentId">Document ID</option>
                                                        </optgroup> -->
                                                        <optgroup label="Advanced">
                                                            <option value="email">Email</option>
                                                            <option value="url">URL</option>
                                                            <option value="ip">IP</option>
                                                            <option value="markdown">Markdown</option>
                                                            <option value="document">Document (Embeded)</option>
                                                        </optgroup>
                                                    </select>
                                                        
                                                    <div class="margin-bottom">
                                                        <input name="required" type="hidden" data-forms-switch data-ls-bind="{{rule.required}}" data-cast-to="boolean" /> &nbsp; Required <span class="tooltip" data-tooltip="Mark whether this is a required attribute"><i class="icon-info-circled"></i></span>
                                                    </div>
                                                                                                        
                                                    <div class="margin-bottom">
                                                        <input name="array" type="hidden" data-forms-switch data-ls-bind="{{rule.array}}" data-cast-to="boolean" />  &nbsp; Array <span class="tooltip" data-tooltip="Mark whether this attribute should act as an array"><i class="icon-info-circled"></i></span>
                                                    </div>

                                                    <div data-ls-template="template-validation-{{rule.type}}" data-type="script" class="margin-bottom"></div>
                                                </fieldset>

                                                <button type="button" data-ls-ui-trigger="splice-rule-{{$index}}" class="reverse danger margin-bottom">Remove</button>

                                                <!-- <button type="button" data-remove="" class="reverse danger margin-bottom">Remove</button> -->
                                            </div>
                                        </li>
                                    </ul>
                                </div>

                                <hr class="margin-bottom-no margin-top-no" />

                                <button type="button" data-ls-ui-trigger="add-rule" class="reverse margin-top"><i class="icon-plus"></i>Add</button>

                                <div class="toggle margin-bottom margin-top" data-ls-ui-open>
                                    <i class="icon-plus pull-end margin-top-tiny"></i>
                                    <i class="icon-minus pull-end margin-top-tiny"></i>
                                    
                                    <h3 class="margin-bottom-large">Permissions</h3>
                                    
                                    <label for="collection-read">Read Access <span class="text-size-small">(<a data-ls-attrs="href={{env.HOME}}/docs/permissions" target="_blank">Learn more</a>)</span></label>
                                    <input type="hidden" id="collection-read" name="read" data-forms-tags data-cast-to="json" data-ls-bind="{{project-collection.$permissions.read}}" placeholder="User ID, Team ID or Role" />
                                                    
                                    <label for="collection-write">Write Access <span class="text-size-small">(<a data-ls-attrs="href={{env.HOME}}/docs/permissions" target="_blank">Learn more</a>)</label>
                                    <input type="hidden" id="collection-write" name="write" data-forms-tags data-cast-to="json" data-ls-bind="{{project-collection.$permissions.write}}" placeholder="User ID, Team ID or Role" />
                                </div>

                                <button>Update</button>
                            </form>
                        </div>
                    </div>
                    <div class="col span-4 sticky-top">
                        <label>Collection ID</label>
                        <div class="input-copy margin-bottom">
                            <input id="id" type="text" autocomplete="off" placeholder="" data-ls-bind="{{project-collection.$id}}" disabled data-forms-copy class="margin-bottom-no" />
                        </div>

                        <ul class="margin-bottom-large text-fade text-size-small">
                            <li class="margin-bottom-small"><i class="icon-angle-circled-right margin-start-tiny margin-end-tiny"></i> <button data-ls-ui-trigger="open-json" class="link text-size-small">View as JSON</button></li>
                            <li class="margin-bottom-small"><i class="icon-angle-circled-right margin-start-tiny margin-end-tiny"></i> Last Updated: <span data-ls-bind="{{project-collection.dateUpdated|date-text}}"></span></li>
                            <li class="margin-bottom-small"><i class="icon-angle-circled-right margin-start-tiny margin-end-tiny"></i> Created: <span data-ls-bind="{{project-collection.dateCreated|date-text}}"></span></li>
                        </ul>

                        <form name="database.deleteCollection" class="margin-bottom"
                            data-analytics-event="submit"
                            data-analytics-category="console"
                            data-analytics-label="Delete Database Collection"
                            data-service="database.deleteCollection"
                            data-event="submit"
                            data-param-collection-id="{{router.params.id}}"
                            data-confirm="Are you sure you want to delete this collection?"
                            data-success="alert,trigger,redirect"
                            data-success-param-alert-text="Collection deleted successfully"
                            data-success-param-trigger-events="database.deleteCollection"
                            data-success-param-redirect-url="/console/database?project={{router.params.project}}"
                            data-failure="alert"
                            data-failure-param-alert-text="Failed to delete collection"
                            data-failure-param-alert-classname="error">

                            <button type="submit" class="danger fill">Delete Collection</button>
                        </form>
                    </div>
                </div>

                <ul data-ls-loop="project-collection.rules" data-ls-as="rule" class="sortable">
                    <li data-forms-remove data-forms-move-up  data-forms-move-down>
                        <form
                            data-analytics-event="splice-rule-{{$index}}"
                            data-analytics-category="console"
                            data-analytics-label="Spliced Collection Rule"
                            data-service="container.path"
                            data-event="splice-rule-{{$index}}"
                            data-scope="window.ls"
                            data-success="reset">

                            <input type="hidden" name="path" value="project-collection.rules" />
                            <input type="hidden" name="type" value="splice" />
                            <input type="hidden" name="value" data-ls-bind="{{$index}}" />
                        </form>
                    </li>
                </ul>

                <div data-ui-modal class="box modal close" data-button-alias="none" data-open-event="add-rule">
                    <button type="button" class="close pull-end" data-ui-modal-close=""><i class="icon-cancel"></i></button>

                    <h1>Add Rule</h1>

                    <form
                        data-analytics-event="submit"
                        data-analytics-category="console"
                        data-analytics-label="Added Collection Rule"
                        data-service="container.path"
                        data-event="submit"
                        data-scope="window.ls"
                        data-success="reset">

                        <input type="hidden" name="path" value="project-collection.rules" />
                        <input type="hidden" name="type" value="append" />
                        
                        <fieldset name="value" data-cast-to="object">                            
                            <input name="$id" type="hidden" value="" />    
                            <input name="$collection" type="hidden" value="rules" />

                            <div class="row thin">
                                <div class="col span-6">
                                    <label for="rule-label-new">Label
                                        <span class="tooltip" data-tooltip="Attribute internal display name"><i class="icon-info-circled"></i></span>
                                    </label>
                                    <input name="label" type="text" required />
                                </div>
                                <div class="col span-6">
                                    <label for="rule-key-new">Key
                                        <span class="tooltip small" data-tooltip="Attribute key name. Used as the document JSON key in the Database API"><i class="icon-info-circled"></i></span>
                                    </label>
                                    <div class="input-copy">
                                        <input data-forms-copy name="key" type="text" required max="32" pattern="^(\d|\w)+$" title="No spaces or special charts allowed" />
                                    </div>
                                </div>
                            </div>

                            <label for="rule-type-new">Rule Type</label>

                            <select name="type" required>
                                <optgroup label="General">
                                    <option value="text">Text</option>
                                    <option value="numeric">Numeric</option>
                                    <option value="boolean">Boolean</option>
                                    <option value="wildcard">Wildcard (*)</option>
                                </optgroup>
                                <!-- <optgroup label="Links">
                                    <option value="fileId">File ID</option>
                                    <option value="documentId">Document ID</option>
                                </optgroup> -->
                                <optgroup label="Advanced">
                                    <option value="email">Email</option>
                                    <option value="url">URL</option>
                                    <option value="ip">IP</option>
                                    <option value="markdown">Markdown</option>
                                    <option value="document">Document (Embeded)</option>
                                </optgroup>
                            </select>
                            
                            <input name="default" type="hidden" value="" />
                            <input name="required" type="hidden" value="false" data-cast-to="boolean" />
                            <input name="array" type="hidden" value="false" data-cast-to="boolean" />
                            
                        </fieldset>

                        <hr class="margin-top-no" />

                        <button type="submit">Create</button> &nbsp; <button data-ui-modal-close="" type="button" class="reverse">Cancel</button>
                    </form>
                </div>
            </li>
        </ul>
    </div>
</div>

<script type="text/html" id="template-validation-text">
    <div class="margin-bottom">
        <label data-ls-attrs="for=rule-default-{{rule.$id}}">Default Value</label>
        <input name="default" type="text" data-ls-bind="{{rule.default}}" data-forms-text-direction />
    </div>
</script>

<script type="text/html" id="template-validation-numeric">
    <div class="margin-bottom">
        <label data-ls-attrs="for=rule-default-{{rule.$id}}">Default Value</label>
        <input name="default" type="number" data-ls-bind="{{rule.default}}" data-cast-to="integer" placeholder="0" />
    </div>
</script>

<script type="text/html" id="template-validation-boolean">
    <div class="margin-bottom">
        <label data-ls-attrs="for=rule-default-{{rule.$id}}">Default Value</label>
        <input name="default" data-ls-bind="{{rule.default}}" type="hidden" data-forms-switch data-cast-to="boolean" />
    </div>
</script>

<script type="text/html" id="template-validation-text">
    <div class="margin-bottom">
        <label data-ls-attrs="for=rule-default-{{rule.$id}}">Default Value</label>
        <input name="default" type="text" data-ls-bind="{{rule.default}}" data-forms-text-direction />
    </div>
</script>

<script type="text/html" id="template-validation-documentId">
    <div data-ls-template="template-validation-document-array-false" data-type="script"></div>

    <div class="margin-bottom text-align-center margin-top-xl margin-bottom-large" data-ls-if="{{project-collections.sum}} == 1">
        No Collections Found.
    </div>
</script>

<script type="text/html" id="template-validation-document">
    <div data-ls-template="template-validation-document-array-{{rule.array}}" data-type="script"></div>

    <div class="margin-bottom text-align-center margin-top-xl margin-bottom-large" data-ls-if="{{project-collections.sum}} == 1">
        No Collections Found.
    </div>
</script>

<script type="text/html" id="template-validation-document-array-true">
    <label data-ls-attrs="for=rule-list-{{rule.$id}}" class="margin-bottom">Allowed Collections</label>

    <div data-ls-loop="project-collections.collections" data-ls-as="project" data-ls-key="$index2" class="tiles cell-3 margin-bottom-negative" style="visibility: hidden">
        <div class="margin-bottom" data-ls-if="{{project.$id}} != {{router.params.id}}">
            <input type="checkbox" name="list" data-ls-attrs="value={{project.$id}}" data-ls-bind="{{rule.list}}" /> <span data-ls-bind="{{project.name}}"></span>
        </div>
    </div>
</script>

<script type="text/html" id="template-validation-document-array-false">
    <label data-ls-attrs="for=rule-list-{{rule.$id}}" class="margin-bottom">Allowed Collection</label>

    <div data-ls-loop="project-collections.collections" data-ls-as="project" data-ls-key="$index2" class="tiles cell-3 margin-bottom-negative" style="visibility: hidden">
        <div class="margin-bottom" data-ls-if="{{project.$id}} != {{router.params.id}}">
            <input type="radio" name="list" data-ls-attrs="value={{project.$id}}" data-ls-bind="{{rule.list|firstElement}}" data-cast-to="array" required /> <span data-ls-bind="{{project.name}}"></span>
        </div>
    </div>
</script>

<div class="margin-top"
    data-service="database.listCollections"
    data-event="load,database.createCollection,database.updateCollection,database.deleteCollection"
    data-scope="sdk"
    data-name="project-collections">
</div>