
<?php
/**
 * Manage page for any main model relation models
 * @author Rihards Silins <rihards.silins@mtcmedia.co.uk>
 * @version 1 27/05/2016
 * @copyright MTC media Ltd.
 */
$path = '../../../';
require_once $path.'core/includes/header.inc.php';
require_once 'includes/settings.php'; // MODEL SETTINGS

use Mtc\Modules\DoctorPolicy\Classes\ModuleHelper;
use Mtc\Modules\DoctorPolicy\Classes\ModuleActions;
use Mtc\Modules\ModuleBuilder\Classes\Builders\ManageListBuilder;

if (empty($_GET['parent_id']) || !is_numeric($_GET['parent_id']) ||
    empty($_GET['relation_key']) || !preg_match("/^[a-zA-Z_]+$/", $_GET['relation_key']) ||
    !isset($module['relations'][$_GET['relation_key']])) {
    header("Location: manage.php");
    exit();
}
$relation_key = $_GET['relation_key'];

$model_class_name = MODEL_CLASS_NAMESPACE_PREFIX.MODEL_CLASS_NAME;
$module['object'] = $model_class_name::find($_GET['parent_id']);
if ($module['object'] == null) {
    header("Location: manage.php");
    exit();
}

$page_meta['title'] = "Manage ".ucwords(MODEL_SINGULAR)." '".$module['object']->{MODEL_NAME_ATTRIBUTE}."' ".$module['relations'][$relation_key]['name_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
*************************************************************************************************************************************/

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 $module["relations"]["'.$relation_key.'"]["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 $module['relations'][$relation_key]['class_name'](),
    $module['relations'][$relation_key]['form'],
    $image_folders,
    $module['relations'][$relation_key]['name_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><a href="manage.php">Manage <?=clean_page(ucwords(MODEL_SINGULAR))?></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 $module['relations'][$relation_key]['module_description'];

$form_messages = ModuleHelper::mergeSessionMessages($form_messages);

// Alerts, Errors, Success Messages
ModuleHelper::printMessages($form_messages);

// 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">
        <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)." ".$module['relations'][$relation_key]['name_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['relations'][$relation_key]['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['relations'][$relation_key]['advanced_filter'] as $attribute => $model_form_row) {
            echo $form->input(array(
                $attribute => $model_form_row,
            ));
        }

        echo $form->input(array(
            'relation_key' => array(
                "scoped_name" => false,
                'value' => $relation_key,
                'type' => 'hidden'
            )
        ));

        echo $form->input(array(
            'parent_id' => array(
                "scoped_name" => false,
                'value' => $module['object']->id,
                'type' => 'hidden'
            )
        ));

        echo $form->input(array(
            'parent_key' => array(
                "scoped_name" => false,
                'value' => $module['relations'][$relation_key]['parent_key'],
                'type' => 'hidden'
            )
        ));

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

        ?>
    </fieldset>
    <?php

    echo $form->end();
}
// end of adv filter
// group by filter
if (!empty($module['relations'][$relation_key]['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['relations'][$relation_key]['group_by'] as $attribute => $model_form_row) {
            echo $form->input(array(
                $attribute => $model_form_row,
            ));
        }

        echo $form->input(array(
            'relation_key' => array(
                "scoped_name" => false,
                'value' => $relation_key,
                'type' => 'hidden'
            )
        ));

        echo $form->input(array(
            'parent_id' => array(
                "scoped_name" => false,
                'value' => $module['object']->id,
                'type' => 'hidden'
            )
        ));
        echo $form->input(array(
            'parent_key' => array(
                "scoped_name" => false,
                'value' => $module['relations'][$relation_key]['parent_key'],
                'type' => 'hidden'
            )
        ));

        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(
        $module['relations'][$relation_key]['class_name'],
        $module['relations'][$relation_key],
        $_GET,
        $model_manage_limit,
        $module['relations'][$relation_key]['parent_key'],
        $module['object']->id
    )
);

if (count($model_list) > 0) {
    $manage_list = new ManageListBuilder($twig);
    $manage_list->start();
    ?><form action="" method="post" class="moduleBuilder">
        <input type="hidden" id="parent_id" name="parent_id" value="<?=$module['object']->id?>" />
        <input type="hidden" id="parent_key" name="parent_key" value="<?=$module['relations'][$relation_key]['parent_key']?>" />
        <input type="hidden" id="relation_key" name="relation_key" value="<?=$relation_key?>" />
        <table class="manage-items">
            <tr>
                <?php
                foreach ($module['relations'][$relation_key]['columns'] as $attribute_name => $column) {
                    echo $manage_list->header(
                        array(
                            $attribute_name => $column
                        )
                    );
                }
                ?>
            </tr>
            <tbody class="tabular listTBody dragAndDropOrder">
                <?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
                    // loop through columns in row
                    foreach ($module['relations'][$relation_key]['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';
