<?php

use Appwrite\Database\Database;
use Utopia\View;
use Appwrite\Database\Validator\Authorization;

$collection = $this->getParam('collection', null);
$searchFiles = $this->getParam('searchFiles', null);
$searchDocuments = $this->getParam('searchDocuments', null);
$name = $collection->getAttribute('name', '');
$db = $this->getParam('db', null);
$rules = $collection->getAttribute('rules', []);
$namespace = 'project-document';
$collections = [];
?>

<?php echo $searchFiles->render(); ?>

<?php foreach($rules as $rule): // Form to append child document
    $key = $rule['key'] ?? '';
    $label = $rule['label'] ?? '';
    $type = $rule['type'] ?? '';
    $list = $rule['list'] ?? [];
?>
    <?php foreach($list as $item):
        if($item === $collection->getId()) {
            continue; // Do not allow rec recrusion
        }

        if(!isset($collections[$item])) {
            Authorization::disable(); //TODO Try and avoid calling the DB from the template
            $collections[$item] = $db->getDocument($item, false);
            Authorization::reset();
        }

        $childCollection = $collections[$item];

        if(!$childCollection->getId() || $childCollection->getCollection() !== Database::SYSTEM_COLLECTION_COLLECTIONS) {
            continue;
        }

        $searchDocuments
            ->setParam('collection', $childCollection)
        ;

        echo $searchDocuments->render(); ?>
    <?php endforeach; ?>
<?php endforeach; ?>

<?php foreach($rules as $rule): // Form to append child document
    $key = $rule['key'] ?? '';
    $label = $rule['label'] ?? '';
    $type = $rule['type'] ?? '';
    $list = $rule['list'] ?? [];
    $array = $rule['array'] ?? false;
?>

    <?php if($type !== 'document' && $array): ?>

        <form class="margin-bottom-no"
            data-service="container.path"
            data-event="collection-child-<?php echo $this->escape($namespace.'.'.$key); ?>"
            data-scope="window.ls"
            data-success="reset">

            <input type="hidden" name="path" value="<?php echo $this->escape($namespace.'.'.$key); ?>" />
            <input type="hidden" name="type" value="append" />
            <input type="hidden" name="value" value="" />
        </form>

    <?php endif; ?>
    
    <?php if($type !== 'document'): ?>
        <?php continue; ?>
    <?php endif; ?>

    <?php foreach($list as $item):
        if($item === $collection->getId()) {
            continue; // Do not allow rec recrusion
        }

        if(!isset($collections[$item])) {
            Authorization::disable(); //TODO Try and avoid calling the DB from the template
            $collections[$item] = $db->getDocument($item, false);
            Authorization::reset();
        }

        $childCollection = $collections[$item];

        if(!$childCollection->getId() || $childCollection->getCollection() !== Database::SYSTEM_COLLECTION_COLLECTIONS) {
            continue;
        }
    ?>
        <form class="margin-bottom-no"
            data-service="container.path"
            data-event="collection-child-<?php echo $this->escape($namespace.'.'.$key); ?>-<?php echo $this->escape($childCollection->getId()); ?>"
            data-scope="window.ls"
            data-success="reset">

            <input type="hidden" name="path" value="<?php echo $this->escape($namespace.'.'.$key); ?>" />
            <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="<?php echo $this->escape($childCollection->getId()); ?>" />
            </fieldset>
        </form>

        <script type="text/html" id="collection-<?php echo ($array) ? 'array-' : ''; ?><?php echo $this->escape($childCollection->getId()); ?>">
            <?php 

            $comp = new View(__DIR__.'/form.phtml');
                                        
            $comp
                ->setParam('collection', $childCollection)
                ->setParam('namespace', ($array) ? 'node' : $namespace.'.'.$key)
                ->setParam('key', $key)
                ->setParam('array', $array)
                ->setParam('parent', 0)
            ;

            echo $comp->render();
            ?>
        </script>
    <?php endforeach; ?>
<?php endforeach; ?>

<?php foreach($rules as $rule): // Form to remove array $index key
    $key = $rule['key'] ?? '';
    $label = $rule['label'] ?? '';
    $type = $rule['type'] ?? '';
    $list = $rule['list'] ?? false;
    $array = $rule['array'] ?? false;

    if(!$array) {
        continue;
    }
?>
    <ul data-ls-loop="<?php echo $this->escape($namespace.'.'.$key); ?>" data-ls-as="xxx">
        <li>
            <form
                data-service="container.path"
                data-event="splice-<?php echo $this->escape($namespace.'.'.$key); ?>-{{$index}}"
                data-scope="window.ls"
                data-success="reset">

                <input type="hidden" name="path" value="<?php echo $this->escape($namespace.'.'.$key); ?>" />
                <input type="hidden" name="type" value="splice" />
                <input type="hidden" name="value" data-ls-bind="{{$index}}" />
            </form>
        </li>
    </ul>
<?php endforeach; ?>

<div
    data-service="database.getDocument"
    data-param-collection-id="{{router.params.collection}}"
    data-param-document-id="{{router.params.id}}"
    data-scope="sdk"
    data-event="load,database.updateDocument"
    data-name="project-document"
    data-success="default">

    <div class="cover">
        <h1 class="zone xl margin-bottom-large">
            <a data-ls-attrs="href=/console/database/collection?id={{router.params.collection}}&project={{router.params.project}}" class="back text-size-small link-return-animation--start"><i class="icon-left-open"></i> <?php echo $this->escape($name); ?></a>

            <br />

            <span data-ls-if="({{project-document.$id}})" data-ls-bind="Document">&nbsp;&nbsp;</span>
            <span data-ls-if="(!{{project-document.$id}})" data-ls-bind="Document">&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-document}}" data-forms-code />
        </div>

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

    <div class="zone xl margin-bottom-no">
        <ul class="phases clear" data-ui-phases data-selected="{{router.params.tab}}">
            <li data-state="/console/database/document?id={{router.params.id}}&collection={{router.params.collection}}&project={{router.params.project}}">
                <h2>Update</h2>

                <div class="row responsive margin-top-negative">
                    <div class="col span-8 margin-bottom">
                        <form
                            data-analytics
                            data-analytics-activity
                            data-analytics-event="submit"
                            data-analytics-category="console"
                            data-analytics-label="Update Database Document"
                            data-service="{{|documentAction}}"
                            data-name="project-document"
                            data-scope="sdk"
                            data-event="submit"
                            data-success="alert,trigger{{|documentSuccess}}"
                            data-success-param-alert-text="Updated document successfully"
                            data-success-param-trigger-events="database.updateDocument"
                            data-success-param-redirect-url="/console/database/document?id={{serviceData.$id}}&collection={{router.params.collection}}&project={{router.params.project}}"
                            data-failure="alert"
                            data-failure-param-alert-text="Failed to update document"
                            data-failure-param-alert-classname="error">

                            <label>&nbsp;</label>

                            <div class="box">

                                <!-- <div class="document-nav" data-forms-nav>
                                    <ul class="text-align-end margin-end-small">
                                        <?php foreach($rules as $rule): // Form to append child document
                                            $key = $rule['key'] ?? '';
                                            $label = $rule['label'] ?? '';
                                            $type = $rule['type'] ?? '';
                                            $list = $rule['list'] ?? [];
                                        ?>
                                            <li class="text-size-small">
                                                <span class="link text-fade" data-forms-nav-link="<?php echo $this->escape($key); ?>"><?php echo $this->escape($label); ?></span>
                                            </li>
                                        <?php endforeach; ?>
                                    </ul>
                                </div> -->
                                
                                <?php if(empty($rules)): ?>
                                    <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.<br /><br /><a data-ls-attrs="href=/console/database/collection/settings?id={{router.params.collection}}&project={{router.params.project}}">Update Collection</a></h4>
                                    </div>
                                <?php else: ?>
                                    <?php

                                    $comp = new View(__DIR__.'/form.phtml');
                        
                                    $comp
                                        ->setParam('collection', $collection)
                                        ->setParam('collections', $collections)
                                        ->setParam('namespace', $namespace)
                                        ->setParam('key', 'data')
                                        ->setParam('parent', 1)
                                    ;

                                    echo $comp->render();
                                    ?>

                                    <div class="toggle margin-bottom" data-ls-ui-open data-button-aria="Open Permissions">
                                        <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" rel="noopener">Learn more</a>)</span></label>
                                        <input type="hidden" id="collection-read" name="read" data-forms-tags data-cast-to="json" data-ls-bind="{{project-document.$permissions.read}}" placeholder="User ID, Team ID or Role" />
                                        <div class="text-fade text-size-xs margin-top-negative-small margin-bottom">Add * for wildcard access</div>

                                        <label for="collection-write">Write Access <span class="text-size-small">(<a data-ls-attrs="href={{env.HOME}}/docs/permissions" target="_blank" rel="noopener">Learn more</a>)</label>
                                        <input type="hidden" id="collection-write" name="write" data-forms-tags data-cast-to="json" data-ls-bind="{{project-document.$permissions.write}}" placeholder="User ID, Team ID or Role" />
                                        <div class="text-fade text-size-xs margin-top-negative-small margin-bottom">Add * for wildcard access</div>
                                    </div>

                                    <button data-ls-if="({{project-document.$id}})">Update</button>
                                    <button data-ls-if="(!{{project-document.$id}})">Create</button>
                                <?php endif; ?>
                            </div>

                        </form>
                    </div>
                    <div class="col span-4 sticky-top">

                        <div data-ls-if="({{project-document.$id}})">
                            <label>Document ID</label>
                            <div class="input-copy margin-bottom">
                                <input type="text" autocomplete="off" placeholder="" data-ls-bind="{{project-document.$id}}" disabled data-forms-copy class="margin-bottom-no" />
                            </div>
                        </div>

                        <label>Collection ID</label>
                        <div class="input-copy margin-bottom">
                            <input type="text" autocomplete="off" placeholder="" data-ls-bind="{{router.params.collection}}" disabled data-forms-copy class="margin-bottom-no" />
                        </div>

                        <ul class="margin-bottom-large text-fade text-size-small" data-ls-if="({{project-document.$id}})">
                            <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>
                        </ul>

                        <div data-ls-if="({{project-document.$id}})">
                            <form name="database.deleteDocument" class="margin-bottom"
                                data-analytics
                                data-analytics-activity
                                data-analytics-event="submit"
                                data-analytics-category="console"
                                data-analytics-label="Delete Collection Document"
                                data-service="database.deleteDocument"
                                data-event="submit"
                                data-param-collection-id="{{router.params.collection}}"
                                data-param-document-id="{{project-document.$id}}"
                                data-confirm="Are you sure you want to delete this document?"
                                data-success="alert,trigger,redirect"
                                data-success-param-alert-text="Document deleted successfully"
                                data-success-param-trigger-events="database.deleteDocument"
                                data-success-param-redirect-url="/console/database/collection?id={{router.params.collection}}&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 Document</button>
                            </form>
                        </div>
                    </div>
                </div>
            </li>
            <!-- <li data-ls-if="{{project-document.$id}}" data-state="/console/database/document/activity?id={{router.params.id}}&collection={{router.params.collection}}&project={{router.params.project}}">
                <h2>Activity</h2>
            </li> -->
        </ul>
    </div>
</div>
