<?php

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

use Mtc\Modules\ModuleBuilder\Classes as ModuleBuilder;

$model_class_name = MODEL_CLASS_NAME;

$page_meta['title'] = 'Add '.ucwords(MODEL_SINGULAR)."";

$model_object = new $model_class_name();

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

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

// Process and update action request.
if (!empty($_REQUEST[MODEL_CLASS_NAME]['action']) && $_REQUEST[MODEL_CLASS_NAME]['action'] == 'update') {
    // validation
    $errors = array();

    foreach ($model_form as $attribute => $attribute_row) {
        if (!empty($attribute_row['rules'])) {
            $attribute_rules = $attribute_row['rules'];

            if (isset($attribute_rules['required']) && $attribute_rules['required'] === true) {
                if (!isset($_REQUEST[MODEL_CLASS_NAME][$attribute])) {
                    if (isset($attribute_rules['error_message']) && !empty($attribute_rules['error_message'])) {
                        $errors[] = $attribute_rules['error_message'];
                    } else {
                        $errors[] = $attribute_row['label'].' is required!';
                    }
                    continue;
                }
            }
            if (isset($attribute_rules['notEmpty']) && $attribute_rules['notEmpty'] === true) {
                if (empty($_REQUEST[MODEL_CLASS_NAME][$attribute])) {
                    if (isset($attribute_rules['error_message']) && !empty($attribute_rules['error_message'])) {
                        $errors[] = $attribute_rules['error_message'];
                    } else {
                        $errors[] = $attribute_row['label'].' must not be empty!';
                    }
                    continue;
                }
            }
            if (isset($attribute_rules['regex'])) {
                if (!preg_match($attribute_rules['regex'], $_REQUEST[MODEL_CLASS_NAME][$attribute])) {
                    if (isset($attribute_rules['error_message']) && !empty($attribute_rules['error_message'])) {
                        $errors[] = $attribute_rules['error_message'];
                    } else {
                        $errors[] = $attribute_row['label'].' is invalid ('.$attribute_rules['regex'].')!';
                    }
                    continue;
                }
            }
        }
    }

    if (!empty($_REQUEST[MODEL_CLASS_NAME]['module_helper_class_namespace']) && !class_exists($_REQUEST[MODEL_CLASS_NAME]['module_helper_class_namespace']."ModuleHelper")) {
        $errors[] = 'Entered ModuleHelper class namespace is invalid. Class '.$_REQUEST[MODEL_CLASS_NAME]['module_helper_class_namespace'].'ModuleHelper doesn\'t exist';
    }

    if (!empty($_REQUEST[MODEL_CLASS_NAME]['module_actions_class_namespace']) && !class_exists($_REQUEST[MODEL_CLASS_NAME]['module_actions_class_namespace']."ModuleHelper")) {
        $errors[] = 'Entered ModuleActions class namespace is invalid. Class '.$_REQUEST[MODEL_CLASS_NAME]['module_actions_class_namespace'].'ModuleHelper doesn\'t exist';
    }

    if (empty($errors)) {
        // Create module variables
        $namespace = '';
        $class_namespace_prefix = '';

        if (!preg_match('/^[a-z_A-Z]+$/', $_REQUEST[MODEL_CLASS_NAME]['class_name'])) {
            $_SESSION['model_form']['error'][] = 'Please provide valid class name!';
        }

        $namespace = 'namespace Mtc\\Modules\\'.$_REQUEST[MODEL_CLASS_NAME]['class_name'].'\\Classes;';
        $class_namespace_prefix = 'Mtc\\\\Modules\\\\'.$_REQUEST[MODEL_CLASS_NAME]['class_name'].'\\\\Classes\\\\';
        $folder_name = $_REQUEST[MODEL_CLASS_NAME]['class_name'];

        // Create the module table
        $database_table_builder = new ModuleBuilder\Builders\DatabaseTableBuilder();
        $database_table_builder->setTableName($_REQUEST[MODEL_CLASS_NAME]['table_name']);
        if ($database_table_builder->build() === false) {
            $_SESSION['model_form']['error'][] = 'There was an error with creating tables! They might already exist!';
        }

        // Create module menu entry
        if (!empty($_REQUEST[MODEL_CLASS_NAME]['create_menu_entry'])) {
            $menu_entry_builder = new ModuleBuilder\Builders\MenuEntryBuilder();
            $menu_entry_builder->setFolderName($folder_name);
            $menu_entry_builder->setModuleNameSingular(ucwords($_REQUEST[MODEL_CLASS_NAME]['module_folder_name_singular']));
            $menu_entry_builder->setModuleNamePlural(ucwords($_REQUEST[MODEL_CLASS_NAME]['module_folder_name_plural']));
            if ($menu_entry_builder->build() === false) {
                $_SESSION['model_form']['error'][] = 'There was an error with creating menu entries!';
            }
        }

        // Create module folder and files
        $file_builder = new ModuleBuilder\Builders\FileBuilder();

        if (!empty($_REQUEST[MODEL_CLASS_NAME]['admin_panel_root'])) {
            $file_builder->admin_panel_root = $_REQUEST[MODEL_CLASS_NAME]['admin_panel_root'];
        }

        if (!empty($_REQUEST[MODEL_CLASS_NAME]['model_class_location'])) {
            $file_builder->model_class_location = $_REQUEST[MODEL_CLASS_NAME]['model_class_location'];
        }

        if (!empty($_REQUEST[MODEL_CLASS_NAME]['model_namespace'])) {
            $file_builder->model_namespace = $_REQUEST[MODEL_CLASS_NAME]['model_namespace'];
        }

        if (!empty($_REQUEST[MODEL_CLASS_NAME]['module_helper_class_namespace'])) {
            if (class_exists($_REQUEST[MODEL_CLASS_NAME]['module_helper_class_namespace']."ModuleHelper")) {

            }
            $file_builder->module_helper_class_namespace = $_REQUEST[MODEL_CLASS_NAME]['module_helper_class_namespace'];
        }

        if (!empty($_REQUEST[MODEL_CLASS_NAME]['module_actions_class_namespace'])) {
            $file_builder->module_actions_class_namespace = $_REQUEST[MODEL_CLASS_NAME]['module_actions_class_namespace'];
        }

        $file_builder->setFolderName($folder_name);
        $file_builder->setClassName($_REQUEST[MODEL_CLASS_NAME]['class_name']);
        $file_builder->setNamespacePrefix($class_namespace_prefix);
        $file_builder->setNamespace($namespace);
        $file_builder->setTableName($_REQUEST[MODEL_CLASS_NAME]['table_name']);
        $file_builder->setModuleNameSingular($_REQUEST[MODEL_CLASS_NAME]['module_folder_name_singular']);
        $file_builder->setModuleNamePlural($_REQUEST[MODEL_CLASS_NAME]['module_folder_name_plural']);
        $file_builder->setSettingsTemplate('templates/code.tpl.settings.php');
        $file_builder->setEloquentClassTemplate('templates/code.tpl.eloquentclass.php');

        $result = $file_builder->build();

        if ($result !== false) {
            if (!empty($_SESSION['model_form']['alert'])) {
                $_SESSION['model_form']['alert'] = array_merge($_SESSION['model_form']['alert'], $result);
            }
            header('Location: ' . $file_builder->admin_panel_root . '/manage.php');
            exit();
        } else {
            $_SESSION['model_form']['error'][] = 'Something went wrong with building the files!';
        }
    } else {
        $form_messages['error'] = array_merge($form_messages['error'], $errors);
    }
}

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

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

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

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

<ul class="tabnav el">
    <li class="selected">
        <a href="/" title="Add">Add</a>
    </li>
</ul>

<?php
// module description (raw html)
echo MODEL_MODULE_DESCRIPTION;

// process session stored messages, alerts, errros
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;
    }
    ?>
    <div class="el msg <?=clean_page($class)?>">
    <?php
    $already_displayed_messages = array();
    foreach ($messages as $key => $message) {
        if (in_array($message, $already_displayed_messages)) {
            continue;
        }
        ?>
        <p>
            <?=clean_page($message)?>
        </p>
        <?php
        $already_displayed_messages[] = $message;
    }
    ?>
    </div>
    <?php

}

$form = new ModuleBuilder\Builders\FormBuilder($twig);

echo $form->start(
    $model_object,
    array(
        'class' => 'style moduleBuilder',
    )
);

echo $form->buildForm($model_form);

echo $form->end();


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