<?php

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

use Mtc\Modules\BlackList\Classes\ModuleActions;
use Mtc\Modules\BlackList\Classes\ModuleHelper;
use Mtc\Modules\ModuleBuilder\Classes\Builders\DatabaseTableBuilder;
use Mtc\Modules\ModuleBuilder\Classes\Builders\FormBuilder;

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();
}

$new_object = true;
$page_meta['title'] =
    'Add '
    .ucwords(MODEL_SINGULAR)
    ." '"
    .$module['object']->{MODEL_NAME_ATTRIBUTE}
    ."' "
    .ucwords($module['relations'][$relation_key]['name_singular']);

if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $module['relation_object'] = $module['relations'][$relation_key]['class_name']::find($_GET['id']);

    if ($module['relation_object'] !== null) {
        $module['title'] =
            'Edit '
            .ucwords(MODEL_SINGULAR)
            ." '"
            .$module['object']->{MODEL_NAME_ATTRIBUTE}
            ."' "
            .ucwords($module['relations'][$relation_key]['name_singular']);
        $new_object = false;
    } else {
        $module['relation_object'] = new $module['relations'][$relation_key]['class_name'];
        unset($_GET['id']);
    }
} else {
    $module['relation_object'] = new $module['relations'][$relation_key]['class_name'];
    unset($_GET['id']);
}

if ($new_object) {
    $module['relation_object']->{$module['relations'][$relation_key]['parent_key']} = $module['object']->id;
}

require_once 'includes/edit__after-model_object-init.php';

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

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

if (defined('MODEL_TABLE_CREATION_MODE') && MODEL_TABLE_CREATION_MODE === true) {
    // Alert user that this is turned on
    $_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.';
    // Init DatabaseTableBuilder that can action any changes
    $database_table_builder = new DatabaseTableBuilder;
    $database_table_builder->setModel($module['relation_object']);
    // Make the parent_key a special column so it doesn't get deleted in case it's not mentioned in the relation form
    $database_table_builder->special_columns[] = $module['relations'][$relation_key]['parent_key'];
    // Build relation table if required
    $result = $database_table_builder->buildRelationTable($module['relations'][$relation_key]);
    // Alert user about results
    $_SESSION['model_form']['alert'] = array_merge($_SESSION['model_form']['alert'], $result);
    // Change relation table if required by form
    $result = $database_table_builder->change($module['relations'][$relation_key]['form']);
    // Alert user about results
    $_SESSION['model_form']['alert'] = array_merge($_SESSION['model_form']['alert'], $result);
}

// RESOLVE RELATION
$errors = ModuleActions::resolveEdit(
    $_POST,
    $_GET,
    $_FILES,
    $module['relation_object'],
    $module['relations'][$relation_key]['form'],
    $image_folders,
    $module['relations'][$relation_key]['name_singular'],
);

$form_messages['error'] = array_merge($form_messages['error'], $errors);

require_once 'includes/edit__before-output.php';

/*************************************************************************************************************************************
 *                                                      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_PLURAL)); ?></a> /</li>
    <li class="end"><?= clean_page($page_meta['title']) ?></li>
</ul>

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

<?php

include 'templates/tabs.php';

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

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

$form = new FormBuilder($twig);

$action = 'edit_relation.php?parent_id='.$module['object']->id.'&relation_key='.$relation_key;
if (! $new_object) {
    $action .= '&id='.$module['relation_object']->id;
}

$end_form_button_models = array(
    'action' => array(
        'scoped_name' => false,
        'value' => 'update',
        'type' => 'hidden',
        'fieldset' => 'buttons',
    ),
    'id' => array(
        'value' => $module['relation_object']->id,
        'type' => 'hidden',
    ),
    'submit' => array(
        'value' => 'Save',
        'type' => 'submit',
        'label' => '',
        'fieldset' => 'buttons',
    ),
    'buttons' => [
        'type' => 'fieldset',
        'hide_label' => true,
    ],
    'parent_id' => [
        'scoped_name' => false,
        'value' => $module['object']->id,
        'type' => 'hidden',
    ],
    'parent_key' => [
        'scoped_name' => false,
        'value' => $module['relations'][$relation_key]['parent_key'],
        'type' => 'hidden',
    ],
    'relation_key' => [
        'scoped_name' => false,
        'value' => $relation_key,
        'type' => 'hidden',
    ],
);

$model_form = array_merge(
    $module['relations'][$relation_key]['form'],
    $end_form_button_models,
);

echo
    $form->start(
        $module['relation_object'],
        [
            'action' => $action,
            'class' => 'style moduleBuilder',
        ],
    )
;

echo $form->buildForm($model_form);

echo $form->end();

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