<?php $meta['scripts']['raw']['table'] = '
    var $filterRow = $(".filter-row")
    var $inputs    = $filterRow.find("input");
    var $btnFilter = $filterRow.find(".table-filter");
    var $btnClear  = $filterRow.find(".table-filter-clear");

    $inputs.keyup(function(e) {
        var $this = $(this);

        if($this.val() == "" && $this.attr("value") == "")
            $this.css("background-color", "transparent");
        else if($this.val() != $this.attr("value"))
            $this.css("background-color", "aliceblue");
        else
            $this.css("background-color", "#FFFFDD");

        //$this.css("background-color", $this.val() ? "#FFFFDD" : "transparent");

        var filled = $inputs.filter(function() {
            return $(this).val() != $(this).attr("value");
        }).length > 0;

        if(filled) {
            $btnFilter.removeClass("btn-default").addClass("btn-primary");
            //$btnClear.removeClass("btn-default").addClass("btn-warning");
        } else {
            $btnFilter.removeClass("btn-primary").addClass("btn-default");
            //$btnClear.removeClass("btn-warning").addClass("btn-default");
        }
    }).trigger("keyup");

    $filterFields = $(".table-filter-field").keydown(function(e) {
        if (e.keyCode == 13) {
            $(".table-filter").click();
            window.location.reload();
        }
    });

    $(".table-filter").click(function() {
        $filterFields.each(function(i, el) {
            //$el = $(el);
            var inputValue = el.value.trim();
            var cookieName = "table_filter_'.$table['route'].'_" + el.name;

            if(inputValue == "")
                $.removeCookie(cookieName, {path: "/"});
            else
                $.cookie(cookieName, inputValue, {path: "/"});
        });
    });

    $(".table-filter-clear").click(function() {
        $filterFields.each(function(i, el) {
            var cookieName = "table_filter_'.$table['route'].'_" + el.name;
            $.removeCookie(cookieName, {path: "/"});
        });
    });

    $(".table-sort").click(function() {
        var cookieField = "table_sort_'.$table['route'].'";
        var cookieOrder = "table_order_'.$table['route'].'";
        var field = $(this).data("field");
        if(field != $.cookie(cookieField)) {
            $.cookie(cookieField, field, {path: "/"});
            $.removeCookie(cookieOrder, {path: "/"});
        }

        switch($.cookie(cookieOrder)) {
            case "asc" : {
                $.cookie(cookieOrder, "desc", {path: "/"});
                break;
            }
            case "desc": {
                $.removeCookie(cookieOrder, {path: "/"});
                $.removeCookie(cookieField, {path: "/"});
                break;
            };
            default    : $.cookie(cookieOrder, "asc", {path: "/"});
        }
    });

    $(".table-filter-clear").click(function() {
        $filterFields.each(function(i, el) {
            var cookieName = "table_filter_'.$table['route'].'_" + el.name;
            $.removeCookie(cookieName, {path: "/"});
        });
    });

    $(".table-export").click(function() {
        var csv = $("#table_'.$table['route'].'").TableCSVExport({
            header:'.json_encode(array_values($table['cols'])).',
            columns:'.json_encode(array_values($table['cols'])).',
            rowfilter: ":not(.filter-row)",
            delivery: "value",
            separator: "'.$app['table']['export']['csv']['separator'].'"
        });
        var blob = new Blob([csv], {type: "application/octet-binary"});
        this.href = URL.createObjectURL(blob);
        this.download = "exportacao.csv";
    });
    ';

    $meta['scripts']['local']['inputmask']    = 'jquery.inputmask.bundle.min.js';
    $meta['scripts']['local']['inputmasknum']   = 'inputmask/inputmask.numeric.extensions.min.js';
    $meta['scripts']['local']['inputmaskbind']  = 'inputmask/inputmask.binding.js';
    $meta['scripts']['local']['cookie'] = 'jquery.cookie.min.js';
    $meta['styles']['raw']['fix_table'] = '.box-header a.btn-primary, .box-header a.btn-success, .box-header a.btn-danger, .box-header a.btn-info, .box-header a.btn-warning { color:white; }';

    if(!isset($page['description'])) $page['description'] = 'Lista'; ?>
<?php echo $this->render('hwapx/admin/admin/header.html',NULL,get_defined_vars(),0); ?>
<style>
@media print {
    body * {
        visibility: hidden;
    }
    .print, .print * {
        visibility: visible;
    }
    .print {
        position: relative;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
    }
    .dont-print, .content-header, .filter-row, .box-header, .box-footer {
        display: none;
    }
    .wrapper, .right-side {
        margin: 0 !important;
    }
    a:link:after, a:visited:after {
        content: "" !important;
    }
    .content, .box-body {
        margin: 0;
    }
}
</style>
<div class="row">
    <div class="col-lg-12">
        <div class="box">
            <div class="box-header">
                <h3 class="box-title"><span class="glyphicon glyphicon-th-list"></span> &nbsp;<?= (\Base::instance()->call($this->filter('dict'),[$table['title']])) ?></h3>
                <?php if (isset($table['actions'])): ?>
                    <div class="box-tools">
                        <div class="input-groupx pull-right">
                            <?php $counter=0; foreach (($table['actions']?:[]) as $action): $counter++; ?>
                                <?php if (\Hwapx\Core\Library\ModuleManager::instance()->hasRole($action['role'])): ?>
                                    
                                        <?php if ($counter < $app['table']['maxactions'] or count($table['actions']) <= $app['table']['maxactions']): ?>
                                            
                                                <a onclick="<?= ((isset($action['confirm']) and $action['confirm']) ? 'return confirm(\''.addslashes(is_string($action['confirm']) ? $action['confirm'] : 'Confirma esta ação?').'\');' : '') ?>" href="<?= (isset($ALIASES[$action['route']]) ? $BASE.\F3::alias($action['route']) : $action['route']) ?>" class="btn <?= (isset($action['class']) ? $action['class'] : 'btn-default') ?> btn-flat"><?= ($action['description']) ?></a>
                                            
                                            <?php else: ?>
                                                <?php if ((count($table['actions']) > $app['table']['maxactions'] and $counter == $app['table']['maxactions'])): ?>
                                                    <div class="btn-group">
                                                        <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                                                            Mais Ações
                                                            <span class="caret"></span>
                                                        </button>
                                                        <ul class="dropdown-menu pull-right" role="menu">
                                                <?php endif; ?>
                                                    <li>
                                                        <?php if (is_array($action)): ?>
                                                            
                                                                <a onclick="<?= ((isset($action['confirm']) and $action['confirm']) ? 'return confirm(\''.addslashes(is_string($action['confirm']) ? $action['confirm'] : 'Confirma esta ação?').'\');' : '') ?>" href="<?= (isset($ALIASES[$action['route']]) ? $BASE.\F3::alias($action['route']) : $action['route']) ?>"><?= ($action['description']) ?></a>
                                                            
                                                            <?php else: ?>
                                                                <li class="divider"></li>
                                                            
                                                        <?php endif; ?>
                                                    </li>
                                                <?php if ($counter == count($table['actions'])): ?>
                                                        </ul>
                                                    </div>
                                                <?php endif; ?>
                                            
                                        <?php endif; ?>
                                    
                                    <?php else: ?>
                                        <?php $counter-- ?>
                                    
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
            <!-- /.panel-heading -->
            <div class="box-body no-padding">
                <div >
                    <table id="table_<?= ($table['route']) ?>" class="table table-hover print">
                        <thead>
                            <tr>
                                <?php $count=0; foreach (($table['cols']?:[]) as $field=>$col): $count++; ?>
                                    <th <?= ($count == 1 ? 'style="width: 120px"' : '') ?>>
                                        <?php $sort  = isset($COOKIE['table_sort_'.$table['route']])  ? $COOKIE['table_sort_'.$table['route']] : '';
                                            $order = isset($COOKIE['table_order_'.$table['route']]) ? $COOKIE['table_order_'.$table['route']] : ''; ?>
                                        <?php if ($sort == $field): ?>
                                            <span class="glyphicon glyphicon-chevron-<?= ($order == 'desc' ? 'up' : 'down') ?>"></span>
                                        <?php endif; ?>
                                        <a class="table-sort" data-field="<?= ($field) ?>" href="<?= ($URI) ?>"><?= (isset($col['label']) ? $col['label'] : $col) ?></a>
                                    </th>
                                <?php endforeach; ?>
                                <?php if (isset($table['rowactions'])): ?>
                                    <th class="dont-print text-center" style="width:220px;"><span class="glyphicon glyphicon-flash"></span> Ações</th>
                                <?php endif; ?>
                            </tr>
                            <tr class="filter-row">
                                <?php $counter=0; foreach (($table['cols']?:[]) as $field=>$col): $counter++; ?>
                                    <td>
                                        <div class="form-group">
                                            <div class="<?= ($counter == count($table['cols']) && !isset($table['rowactions']) ? 'input-group' : '') ?>">
                                                <?php if(isset($COOKIE['table_filter_'.$table['route'].'_'.$field])) $filter_set = true; ?>
                                                <?php if (isset($col['options'])): ?>
                                                    <datalist id="datalist_<?= ($field) ?>">
                                                        <?php foreach (($col['options']?:[]) as $option_value=>$option_text): ?>
                                                            <option value="<?= ($option_text) ?>"><?= ($option_value) ?></option>
                                                        <?php endforeach; ?>
                                                    </datalist>
                                                <?php endif; ?>
                                                <input
                                                    class="form-control table-filter-field"
                                                    name="<?= ($field) ?>"
                                                    placeholder="Filtrar por <?= (isset($col['label']) ? $col['label'] : $col) ?>"
                                                    <?= (isset($col['mask']) ? 'data-inputmask-skipOptionalPartCharacter: " " data-inputmask data-inputmask-mask="'.$col['mask'].'"' : '')."
" ?>
                                                    <?= (isset($col['options']) ? 'list="datalist_'.$field.'"' : '')."
" ?>
                                                    <?= (isset($col['attributes']) ? packXMLAttributes($col['attributes']) : '')."
" ?>
                                                    value="<?= (isset($COOKIE['table_filter_'.$table['route'].'_'.$field]) ? $COOKIE['table_filter_'.$table['route'].'_'.$field] : '') ?>">
                                                <?php if ($counter == count($table['cols']) and !isset($table['rowactions'])): ?>
                                                    <span class="input-group-btn">
                                                        <a class="btn btn-default table-filter" href="<?= ($BASE) ?><?= (Base::instance()->alias($table['route'])) ?>"><span class="glyphicon glyphicon-search"></span></a>
                                                    </span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </td>
                                <?php endforeach; ?>
                                <?php if (isset($table['rowactions'])): ?>
                                    <td class="text-center">
                                        <div class="form-group">
                                             <a class="btn btn-default btn-flat table-filter" href="<?= ($BASE) ?><?= (Base::instance()->alias($table['route'])) ?>"><span class="glyphicon glyphicon-search"></span> Filtrar</a>
                                             <a <?= (isset($filter_set) ? '' : 'disabled') ?> class="btn btn-<?= (isset($filter_set) ? 'warning' : 'default') ?> btn-flat table-filter-clear" href="<?= ($BASE) ?><?= (Base::instance()->alias($table['route'])) ?>"><span class="glyphicon glyphicon-erase"></span> Limpar</a>
                                        </div>
                                    </td>
                                <?php endif; ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach (($table['subset']?:[]) as $row): ?>
                                <?php $rowparams = array();
                                    if(isset($table['rowcallback']))
                                        $rowparams = $table['rowcallback']($row); ?>
                                <tr class="<?= (isset($rowparams['class']) ? $rowparams['class'] : '') ?>">
                                    <?php foreach (($table['cols']?:[]) as $field=>$col): ?>
                                        <?php $_fields = is_object($row) ? $row->schema() : array();

                                        F3::set('PARAMS.id', $row['id']);

                                        $cellaction = '';

                                        if(isset($table['rowactions'])):
                                            $act = array_filter($table['rowactions'], function($a) { return isset($a['default']) && $a['default']; });
                                            $act = count($act) ? reset($act) : $act;

                                            if($act && \Hwapx\Core\Library\ModuleManager::instance()->hasRole($act['role']))
                                                $cellaction = isset($ALIASES[$act['route']]) ? $BASE.\F3::alias($act['route'], is_array($row) ? $row : $row->cast()) : F3::build($act['route'], is_array($row) ? $row : $row->cast());
                                        endif;

                                        $cellAttr = array(
                                            'onclick' => $cellaction ? "window.location.href = '$cellaction'" : '',
                                            'class'   => (isset($_fields[$field]['pdo_type']) && $_fields[$field]['pdo_type'] == \PDO::PARAM_INT) || (isset($col['type']) && $col['type'] == 'number') ? 'text-right' : '',
                                            'data-field' => $field
                                        );

                                        if(is_array($col) && isset($col['callback'])):
                                            $cellAttr = $col['callback']($col, $cellAttr);
                                        endif;
                                        if(isset($table['cellcallback'])):
                                            $cellAttr = $table['cellcallback']($field, $row, $col, $cellAttr);
                                        endif; ?>
                                        <td <?= (packXMLAttributes($cellAttr)) ?>>
                                            <?php switch (isset($col['type']) && $row[$field] !== null ? $col['type'] : (isset($_fields[$field]) ? strtolower($_fields[$field]['type']) : 'UNKNOW')): ?><?php case 'date': ?>
                                                    <?= ($row[$field] ? date($app['date']['format'], strtotime($row[$field])) : '')."
" ?>
                                                <?php if (TRUE) break; ?><?php case 'time': ?>
                                                    <?= ($row[$field] ? date($app['time']['format'], strtotime($row[$field])) : '')."
" ?>
                                                <?php if (TRUE) break; ?><?php case 'datetime': ?>
                                                    <?= ($row[$field] ? date($app['datetime']['format'], strtotime($row[$field])) : '')."
" ?>
                                                <?php if (TRUE) break; ?><?php case 'timestamp': ?>
                                                    <?= ($row[$field] ? date($app['datetime']['format'], $row[$field]) : '')."
" ?>
                                                <?php if (TRUE) break; ?><?php case 'number': ?>
                                                    <?= (isset($col['digits']) ? number_format($row[$field], $col['digits'], ',', '.') : $row[$field])."
" ?>
                                                <?php if (TRUE) break; ?><?php default: ?>
                                                    <?php if (isset($table['raw']) && ((is_array($table['raw']) && in_array($field, $table['raw'])) || $table['raw'])): ?>
                                                        
                                                            <?= ($this->raw(isset($row[$field]) ? $row[$field] : $row->$field))."
" ?>
                                                        
                                                        <?php else: ?>
                                                            <?= (isset($row[$field]) ? $row[$field] : $row->$field)."
" ?>
                                                        
                                                    <?php endif; ?>
                                                <?php break; ?><?php endswitch; ?>
                                        </td>
                                    <?php endforeach; ?>
                                    <?php if (isset($table['rowactions'])): ?>
                                        <td class="dont-print text-center">
                                            <?php $counter=0; foreach (($table['rowactions']?:[]) as $action): $counter++; ?>
                                                <?php if (\Hwapx\Core\Library\ModuleManager::instance()->hasRole($action['role'])): ?>
                                                    
                                                        <?php if (isset($action['params'])): ?>
                                                            <?php foreach (($action['params']?:[]) as $param=>$field): ?>
                                                                <?php F3::set('PARAMS.'.$param, $row[$field]) ?>
                                                            <?php endforeach; ?>
                                                        <?php endif; ?>
                                                        <?php if ($counter < $app['table']['maxactions'] or count($table['rowactions']) <= $app['table']['maxactions']): ?>
                                                            
                                                                <a onclick="<?= ((isset($action['confirm']) and $action['confirm']) ? 'return confirm(\''.addslashes(is_string($action['confirm']) ? $action['confirm'] : 'Confirma esta ação?').'\');' : '') ?>" data-id="<?= ($PARAMS['id'] = $row['id']) ?>" href="<?= (isset($ALIASES[$action['route']]) ? $BASE.\F3::alias($action['route'], is_array($row) ? $row : $row->cast()) : F3::build($action['route'], is_array($row) ? $row : $row->cast())) ?>" <?= (isset($action['modal']) && $action['modal'] ? 'data-toggle="modal"' : '') ?> class="btn <?= (isset($action['class']) ? $action['class'] : 'btn-default') ?> btn-xs btn-flat" target="<?= (isset($action['target']) ? $action['target'] : '_self') ?>"><?= ($action['description']) ?></a>
                                                            
                                                            <?php else: ?>
                                                                <?php if ($counter == $app['table']['maxactions']): ?>
                                                                    <div class="btn-group">
                                                                        <button type="button" class="btn btn-default btn-xs btn-flat dropdown-toggle" data-toggle="dropdown">
                                                                            Mais Ações
                                                                            <span class="caret"></span>
                                                                        </button>
                                                                        <ul class="dropdown-menu pull-right" role="menu">
                                                                <?php endif; ?>
                                                                    <li>
                                                                        <?php if (is_array($action)): ?>
                                                                            
                                                                                <a href="<?php F3::set('PARAMS.id', $row['id']) ?><?= (isset($ALIASES[$action['route']]) ? $BASE.\F3::alias($action['route'], is_array($row) ? $row : $row->cast()) : $action['route']) ?>" onclick="<?= ((isset($action['confirm']) and $action['confirm']) ? 'return confirm(\''.addslashes(is_string($action['confirm']) ? $action['confirm'] : 'Confirma esta ação?').'\');' : '') ?>" <?= (isset($action['modal']) && $action['modal'] ? 'data-toggle="modal"' : '') ?> target="<?= (isset($action['target']) ? $action['target'] : '_self') ?>"><?= ($action['description']) ?></a>
                                                                            
                                                                            <?php else: ?>
                                                                                <li class="divider"></li>
                                                                            
                                                                        <?php endif; ?>
                                                                    </li>
                                                                <?php if ($counter == count($table['rowactions'])): ?>
                                                                        </ul>
                                                                    </div>
                                                                <?php endif; ?>
                                                            
                                                        <?php endif; ?>
                                                    
                                                    <?php else: ?>
                                                        <?php $counter-- ?>
                                                    
                                                <?php endif; ?>
                                            <?php endforeach; ?>
                                        </td>
                                    <?php endif; ?>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <!-- /.table-responsive -->
            </div>
            <!-- /.panel-body -->
            <div class="box-footer">
                <?php if (isset($table['legend'])): ?>
                <div class="row">
                    <div class="col-sm-12">
                        <?php foreach (($table['legend']?:[]) as $class_attr=>$legend): ?>
                            <div
                                class="text-center <?= ($class_attr != 'active' ? ' alert-' . $class_attr : '') ?>"
                                style="<?= ($class_attr == 'active' ? 'background-color: #f5f5f5;' : '') ?>float:left;width:<?= (100 / count($table['legend'])) ?>%"
                                >
                                <?= ($legend)."
" ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <br>&nbsp;
                </div>
                <?php endif; ?>
                <div class="row">
                    <div class="col-sm-6">
                        <?php if ($table['total']): ?>
                            
                                <?php if ($table['rowcount'] === true): ?>
                                <select class="form-control" style="display: inline; width: auto;" onchange="$.cookie('<?= ('table_rowcount_'.$table['route']) ?>', this.value); window.location.reload();">
                                    <?php $_rowcount = isset($COOKIE['table_rowcount_'.$table['route']]) ? $COOKIE['table_rowcount_'.$table['route']] : null ?>
                                    <option value=""<?= ($_rowcount === '' ? ' selected' : '') ?>>Todos</option>
                                    <?php foreach (($app['table']['countoptions'] ?: array(10, 20, 30, 40, 50, 100, 500, 1000)?:[]) as $value): ?>
                                        <option value="<?= ($value) ?>"<?= (($_rowcount === null && $value == $app['table']['rowcount']) || $_rowcount == $value ? ' selected' : '') ?>><?= ($value) ?></option>
                                    <?php endforeach; ?>
                                </select>
                                Itens por página.
                                <?php endif; ?>
                                Exibindo <?= ('registros') ?> <?= ($table['limit'] * $table['pos'] + 1) ?> a <?= ($table['count'] > 1 ? $table['limit'] * $table['pos'] + count($table['subset']) : $table['total']) ?> de um total de <?= ($table['total']) ?>.
                            
                            <?php else: ?>
                                Nenhum registro encontrado.
                            
                        <?php endif; ?>
                    </div>
                    <div class="col-sm-6">
                        <ul class="pagination pagination-sm no-margin pull-right">
                            <?php if ($table['count'] > 1): ?>
                                <li class="<?= ($table['pos'] ? '' : ' disabled') ?>"><a href="<?= ($BASE) ?><?= (Base::instance()->alias($table['route'])) ?>/1">«</a></li>
                                <?php $_c = 9 ?>
                                <?php $_h = max($_c - ($table['count'] - $table['pos']), floor($_c / 2)) ?>
                                <?php $_from = max($table['pos'] - $_h, 0) ?>
                                <?php $_c -= $table['pos'] - $_from ?>
                                <?php $_to = min($table['pos'] + $_c, $table['count']) ?>
                                <?php for ($i = $_from;$i < $_to;$i++): ?>
                                    <li class="<?= ($i == $table['pos'] ? ' active' : '') ?>">
                                        <a href="<?= ($BASE) ?><?= (Base::instance()->alias($table['route'])) ?>/<?= ($i + 1) ?>"><?= ($i + 1) ?></a>
                                    </li>
                                <?php endfor; ?>
                                <li class="<?= ($table['pos'] == $table['count'] - 1 ? ' disabled' : '') ?>"><a href="<?= ($BASE) ?><?= (Base::instance()->alias($table['route'])) ?>/<?= ($table['count']) ?>">»</a></li>
                            <?php endif; ?>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
<?php echo $this->render('hwapx/admin/admin/footer.html',NULL,get_defined_vars(),0); ?>