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

use Mtc\Modules\BlackList\Classes\ModuleHelper;
use Mtc\Modules\BlackList\Classes\ModuleActions;
use Illuminate\Support\Facades\Event;

$model_class_name = MODEL_CLASS_NAMESPACE_PREFIX.MODEL_CLASS_NAME;
$page_meta['title'] = 'Manage '.ucwords(MODEL_PLURAL);

$model_manage_limit = $model_manage_limit_rows_per_page[0];
if (isset($_GET['limit']) && is_numeric($_GET['limit'])) {
    $model_manage_limit = $_GET['limit'];
}

$form_messages = array(
    'success' => array(),
    'error' => array(),
    'alert' => array(),
);


/*************************************************************************************************************************************
 *                                                         POSTBACK
*************************************************************************************************************************************/

Event::dispatch(
    MODEL_CLASS_NAMESPACE_PREFIX . MODEL_CLASS_NAME . " on admin manage panel load",
    [
        $_GET
    ]
);

if (defined('MODEL_TABLE_CREATION_MODE') && MODEL_TABLE_CREATION_MODE === true) {
    $_SESSION['model_form']['alert'][] = 'MODEL_TABLE_CREATION_MODE is set to true! Changes you make to $model_form shall make the database table change with it.';
}

if (isset($_POST['limit']) && is_numeric($_POST['limit'])) {
    header('Location: '.ModuleHelper::generateNondestructiveUrl(
        [
            'limit' => $_POST['limit']
        ],
        [
            'page'
        ]
    ));
    exit();
}

// potential delete action
ModuleActions::resolveManage(
    $_POST,
    $_GET,
    $_FILES,
    new $model_class_name(),
    $model_form,
    $image_folders,
    MODEL_SINGULAR
);

/*************************************************************************************************************************************
 *                                                         OUTPUT
*************************************************************************************************************************************/

require $path.'core/admin/templates/adminheader.html.php';

?>

<!-- MODULE CSS FILES -->
<link rel="stylesheet" href="css/style.css" />
<!-- end of MODULE CSS FILES -->

<ul class="breadcrumbs el">
    <li><a href="/admin/">Home</a> /</li>
    <li class="end"><?=clean_page($page_meta['title'])?></li>
</ul>

<h1><?=clean_page($page_meta['title'])?></h1>

<?php

include("templates/tabs.php");

// module description (raw html)
echo MODEL_MODULE_DESCRIPTION;

/* ALERTS */
if (isset($_SESSION['model_form']['success']) && !empty($_SESSION['model_form']['success'])) {
    $form_messages['success'] = array_merge($form_messages['success'], $_SESSION['model_form']['success']);
    unset($_SESSION['model_form']['success']);
}
if (isset($_SESSION['model_form']['error']) && !empty($_SESSION['model_form']['error'])) {
    $form_messages['error'] = array_merge($form_messages['error'], $_SESSION['model_form']['error']);
    unset($_SESSION['model_form']['error']);
}
if (isset($_SESSION['model_form']['alert']) && !empty($_SESSION['model_form']['alert'])) {
    $form_messages['alert'] = array_merge($form_messages['alert'], $_SESSION['model_form']['alert']);
    unset($_SESSION['model_form']['alert']);
}

foreach ($form_messages as $class => $messages) {
    if (empty($messages)) {
        continue;
    }
    echo '<div class="el msg '.clean_page($class).'">';
    $already_displayed_messages = array();
    foreach ($messages as $key => $message) {
        if (in_array($message, $already_displayed_messages)) {
            continue;
        }
        echo '<p>'.clean_page($message).'</p>';
        $already_displayed_messages[] = $message;
    }
    echo '</div>';
}

// Below is a place for any filters manage page should need
?>
<form action="<?=ModuleHelper::generateNondestructiveUrl()?>" method="post" class="moduleBuilder">
   <fieldset class="show">
    <div class="row">

        <?php
        if (empty($module['advanced_filter'])) {
            ?>
            <input
                type="search"
                class="modelAutoSearch"
                value=""
                name="search"
                placeholder="quick search by <?=clean_page(MODEL_NAME_ATTRIBUTE)?>"
            />
            <?php
        }
        ?>

        <select name="limit" class="modelAutoSearchLimit onChangeThisFormSubmit">
            <?php
            foreach ($model_manage_limit_rows_per_page as $key => $value) {
                $selected = "";
                if ($value == $model_manage_limit) {
                    $selected = "selected";
                }

                $option_label = "Display all";
                if ($value > 0) {
                    $option_label = "Display ".clean_page($value)." ".MODEL_PLURAL." per page";
                }
                ?><option value="<?=clean_page($value)?>" <?=$selected?>><?=clean_page($option_label)?></option><?php
            }
            ?>
        </select>
    </div>
    </fieldset>
</form>
<?php

// adv filter
$form = new \Mtc\Modules\ModuleBuilder\Classes\Builders\FormBuilder($twig);
if (!empty($module['advanced_filter'])) {
    echo $form->start(
        'filter',
        array(
            'class' => 'style moduleBuilder',
            'method' => 'get'
        )
    );

    ?>
    <fieldset class="show" id="<?= Util::slugify(MODEL_SINGULAR . " Advanced Filter") ?>">
        <h1><a class="show el">Filter <i class="fa fa-caret-down"></i></a></h1>
        <?php

        foreach ($module['advanced_filter'] as $attribute => $model_form_row) {
            echo $form->input(array(
                $attribute => $model_form_row,
            ));
        }

        echo $form->input(array(
            'submit' => array(
                'value' => 'Filter',
                'type' => 'submit',
                'label' => "",
            ),
        ));

        ?>
    </fieldset>
    <?php

    echo $form->end();
}
// end of adv filter
// group by filter
$form = new \Mtc\Modules\ModuleBuilder\Classes\Builders\FormBuilder($twig);
if (!empty($module['group_by'])) {
    echo $form->start(
        'group_by',
        array(
            'class' => 'style moduleBuilder',
            'method' => 'get'
        )
    );

    ?>
    <fieldset class="show" id="<?= Util::slugify(MODEL_SINGULAR . " Group By") ?>">
        <h1><a class="show el">Group By <i class="fa fa-caret-down"></i></a></h1>
        <?php

        foreach ($module['group_by'] as $attribute => $model_form_row) {
            echo $form->input(array(
                $attribute => $model_form_row,
            ));
        }

        echo $form->input(array(
            'submit' => array(
                'value' => 'Group By',
                'type' => 'submit',
                'label' => "",
            ),
        ));
        ?>
    </fieldset>
    <?php

    echo $form->end();
}
// end of group by filter

// Code for fetching the list and necessary data to display
extract(ModuleHelper::getList($model_class_name, $module, $_GET, $model_manage_limit));

if (count($model_list) > 0) {
    $manage_list = new \Mtc\Modules\ModuleBuilder\Classes\Builders\ManageListBuilder($twig);
    $manage_list->start();
    ?><form action="" method="post" class="moduleBuilder">
        <table class="manage-items">
            <tr>
                <?php
                foreach ($model_list_columns as $attribute_name => $column) {
                    echo $manage_list->header(
                        array(
                            $attribute_name => $column
                        )
                    );
                }
                ?>
            </tr>
            <tbody class="tabular listTBody dragAndDropOrder black-list">
                <?php
                // loop through the list of objects in this pagination
                foreach ($model_list as $key => $model_list_item) {
                    ?><tr id="rorder-<?=$model_list_item->id;?>"<?php if($model_list_item->hard_blacklist == 1){ ?> class="hard-blacklist"<?php } ?>><?php
                    // loop through columns in row
                    foreach ($model_list_columns as $attribute_name => $column) {
                        echo $manage_list->cell(
                            array(
                                $attribute_name => $column
                            ),
                            $model_list_item
                        );
                    }
                    ?>
                    </tr>
                    <?php
                }
                ?>
            </tbody>
        </table>
    </form>
    <?php

} else {
    ?><p>No results to display.</p><?php
}

echo ModuleHelper::generatePagination(
    ceil($model_list_count / $model_manage_limit),
    $model_list_page_no
);

require $path.'core/admin/templates/adminfooter.html.php';
