<?php

$path = '../../../';
require_once $path.'core/includes/header.inc.php';
require_once './includes/settings.php'; // MODEL SETTINGS

$model_class_name = MODEL_CLASS_NAMESPACE_PREFIX.MODEL_CLASS_NAME;

$lister = $model_class_name::where('id', '>', '0');

if (! empty($_GET['term'])) {
    if (defined('MODULE_QUICK_SEARCH_MATCH_MODE') && MODULE_QUICK_SEARCH_MATCH_MODE === 'beginning') {
        $lister = $lister->where(MODEL_NAME_ATTRIBUTE, 'LIKE', $_GET['term'].'%');
    } else {
        $elements = explode(' ', MODEL_NAME_ATTRIBUTE);
        $lister = $lister->where(function ($query) use ($elements, $lister): void {
            foreach ($elements as $element) {
                $query->orWhere($element, 'LIKE', '%'.$_GET['term'].'%');
            }
        });
    }
}
if (isset($_GET['limit']) && is_numeric($_GET['limit'])) {
    $lister = $lister->take($_GET['limit']);
}

if (! empty($module['list_order'])) {
    foreach ($module['list_order'] as $order) {
        $lister = $lister->orderBy($order[0], $order[1]);
    }
}

$model_list = $lister->get();

$result = array();

// loop through the returned list with row
$manage_list = new \Mtc\Modules\ModuleBuilder\Classes\Builders\ManageListBuilder($twig);
$manage_list->start();
foreach ($model_list as $model_list_item) {
    ob_start();
    ?>
    <tr id="rorder-<?= $model_list_item->id; ?>" >
        <?php

        // loop through all columns of a row
        foreach ($model_list_columns as $attribute_name => $column) {
            echo
                $manage_list->cell(
                    array(
                        $attribute_name => $column,
                    ),
                    $model_list_item,
                )
            ;
        }

        ?>
    </tr>
    <?php

    $result[]['data'] = ob_get_contents();
    ob_end_clean();
}

echo json_encode($result);
