<?php
$cms_root_path = "../../";
require_once($cms_root_path."includes/compatibility_includer.php");

require('classes/class.simplemodelmodulebuilder.php'); // MODEL SETTINGS
require('includes/settings.php'); // MODEL SETTINGS

$model_class_name = MODEL_CLASS_NAME;
$new_object = true;
$page_meta['title'] = 'Add '.ucwords(MODEL_SINGULAR);
if ( isset($_GET['id']) && is_numeric($_GET['id']) ) {
    $model_object = $model_class_name::find($_GET['id']);

    if ( $model_object !== null ) {
        $page_meta['title'] = 'Edit '.ucwords(MODEL_SINGULAR);
        $new_object = false;
    } else {
        $model_object = new $model_class_name();
        unset($_GET['id']);
    }
} else {
    $model_object = new $model_class_name();
    unset($_GET['id']);
}

include("includes/edit__after-model_object-init.php");

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

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

/*
	Add
*/
if( !empty($_REQUEST['action']) && $_REQUEST['action']=='update') {
    // validation
    $errors = array();

    foreach ($model_form as $attribute => $attribute_row) {

        $attribute_rules = array();
        if ( !empty($attribute_row['rules']) ) {

            $attribute_rules = $attribute_row['rules'];

            if (!empty($attribute_rules['required'])) {
                if ( !isset( $_REQUEST['data'][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 (!empty($attribute_rules['notEmpty'])) {
                if ( empty( $_REQUEST['data'][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 (!empty($attribute_rules['regex'])) {
                if ( !preg_match($attribute_rules['regex'], $_REQUEST['data'][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;
                }
            }
        }
    }

	// do add/edit
    if (sizeof($errors)==0) {

        include("includes/edit__before-data-loop.php");

        // data
        foreach ($_REQUEST['data'][MODEL_CLASS_NAME] as $key => $value) {

            include("includes/edit__before-validation.php");

            // custom data transform before insert into db. is there a better way?
            // datetime
            if ( isset($model_form[$key]['type']) && $model_form[$key]['type'] === 'datetime' ) {

                if ( !isset($model_form[$key]['datetime_db_format']) || empty($model_form[$key]['datetime_db_format']) ) {
                    $model_form[$key]['datetime_db_format'] = "Y-m-d H:i:s";
                }

                if ( !isset($model_form[$key]['datetime_frontend_format']) || empty($model_form[$key]['datetime_frontend_format']) ) {
                    $model_form[$key]['datetime_frontend_format'] = "d/m/Y H:i";
                }

                $datetime = date_create_from_format($model_form[$key]['datetime_frontend_format'], $value);
                if ( $datetime === false ) {
                    $datetime = new DateTime();
                    $value = $datetime->format($model_form[$key]['datetime_db_format']);
                } else {
                    $value = $datetime->format($model_form[$key]['datetime_db_format']);
                }
            }

            require("includes/edit__before-setting-attribute.php");

            $model_object->{$key} = $value;
        }
        // files
        if ( isset($_FILES['data']['tmp_name']) ) {
            foreach ($_FILES['data']['tmp_name'] as $model_name => $model) {
                foreach ($model as $attr_name => $attr) {

                    if ( $model_form[$attr_name]['type'] == "image" ) {
                        $file = add_fullcms_image(
                            $image_folders['cms_images'],
                            $_FILES['data']['size'][$model_name][$attr_name],
                            $_FILES['data']['name'][$model_name][$attr_name],
                            $_FILES['data']['tmp_name'][$model_name][$attr_name]
                        );
                    } else {
                         $file = add_fullcms_file(
                            $_FILES['data']['size'][$model_name][$attr_name],
                            $_FILES['data']['name'][$model_name][$attr_name],
                            $_FILES['data']['tmp_name'][$model_name][$attr_name]
                        );
                    }

                    if ( $file !== false ) {

                        $model_object->{$attr_name} = $file;

                    }
                }
            }
        }

        if ( MODEL_ORDER_COLUMN && empty($model_object->id)) {
            $model_object->order = 0;
            $top_order_item = $model_class_name::orderBy('order','desc')->first();
            if ( $top_order_item !== null ) {
                $model_object->order = $top_order_item->order + 1;
            }
        }

        include("includes/edit__before-model-save.php");

        if ( $model_object->save() ) {
            unset($_REQUEST['data']);
            if ( !isset($_GET['id']) || empty($_GET['id']) ) {
                $_SESSION['model_form']['success'][] =  ucwords(MODEL_SINGULAR)." created!";
                header("Location: edit.php?id=".$model_object->id); exit();
            }
            $_SESSION['model_form']['success'][] =  ucwords(MODEL_SINGULAR)." updated!";
        }
    } else {
        $form_messages['error'] = array_merge($form_messages['error'], $errors);
    }
}

include("includes/edit__before-output.php");

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

include($core_root_path.'admin/templates/adminheader.html.php');

?>

<!-- MODULE JS FILES -->
<script type="text/javascript" src="js/script.js"></script>
<!-- end of MODULE JS FILES -->


<ul class="breadcrumbs el">
    <li><a href="/admin/">Home</a> /</li>
    <?php /* ANY PARENT PAGES */ ?>
    <li><a href="manage.php"><?='Manage '.ucwords(MODEL_PRULAR);?></a> /</li>
    <li class="end"><?= $page_meta['title'] ?></li>
</ul>

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

<ul class="tabnav el">
    <li><a href="/cms/admin/<?=MODEL_FOLDER?>/manage.php">Manage</a></li>
    <li class="selected"><a href="/cms/admin/<?=MODEL_FOLDER?>/edit.php<?=$new_object ? '' : '?id='.clean_page($_GET['id'])?>"><?=$new_object ? 'Add' : 'Edit'?></a></li>
</ul>

<?php

/* 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 '.$class.'">';
    foreach ($messages as $key => $message) {
        echo "<p>".$message."</p>";
    }
    echo '</div>';
}

?>
<form action="edit.php<?=(!$new_object?'?id='.$_GET['id']:'')?>" method="POST" enctype="multipart/form-data" class="style moduleBuilder">
    <fieldset class="show">
        <h1><a class="show el">Information <i class="fa fa-caret-right"></i></a></h1>

        <?php

        foreach ($model_form as $attribute => $model_form_row) {

            $additional_attributes = array();
            foreach ($model_form_row as $attribute_name => $attribute_value) {
                if (is_array($attribute_value)) continue;
                if (in_array($attribute_name, ['type','class','options','datetime_db_format','datetime_frontend_format','label','rules','rules','info'])) continue;
                $additional_attributes[$attribute_name] = $attribute_value;
            }

            // default type is text
            if (!isset($model_form_row['type']) || empty($model_form_row['type'])) {
                $model_form_row['type'] = "text";
            }
            // options for select
            if (!isset($model_form_row['options']) || empty($model_form_row['options'])) {
                $model_form_row['options'] = array();
            }
            // required
            // default class
            if (!isset($model_form_row['class'])) {
                $model_form_row['class'] = '';
            }

            if ( $model_form_row['type'] == "coordinates" ) {
                $model_form_row['type'] = "text";
                $model_form_row['class'] = "coordinates";
            }

            if ( $model_form_row['type'] == "datetime" ) {

                if ( !isset($model_form_row['datetime_db_format']) || empty($model_form_row['datetime_db_format']) ) {
                    $model_form_row['datetime_db_format'] = "Y-m-d H:i:s";
                }

                if ( !isset($model_form_row['datetime_frontend_format']) || empty($model_form_row['datetime_frontend_format']) ) {
                    $model_form_row['datetime_frontend_format'] = "d/m/Y H:i";
                }

                if ( isset($_REQUEST['data'][MODEL_CLASS_NAME][$attribute]) ) {
                    $value = $_REQUEST['data'][MODEL_CLASS_NAME][$attribute];
                } else {
                    $value = $model_object->{$attribute};
                }

                if ( !empty($model_object->{$attribute}) ) {
                    $datetime = date_create_from_format($model_form_row['datetime_db_format'], $model_object->{$attribute});
                    $value = $datetime->format($model_form_row['datetime_frontend_format']);
                }

                ?>
                <div class="row">
                    <label for="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"><?=$model_form_row['label']?></label>
                    <input
                        type="text"
                        name="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"
                        id="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"
                        value="<?=clean_page($value)?>"
                        class="INPUT1 datetime <?=$model_form_row['class']?>"
                        data-datetime-frontend-format="<?=$model_form_row['datetime_frontend_format']?>"

                        <?php foreach ($additional_attributes as $additional_attributes_name => $additional_attributes_value) {
                            echo $additional_attributes_name.'="'.clean_page($additional_attributes_value).'"';
                        }
                        ?>
                    />
                    <?php
                    if ( isset($model_form_row['info']) ) {
                        ?><div class="hint el"><i class="fa fa-info-circle"></i><div class="text" style="display: none;"><?=$model_form_row['info']?></div></div><?php
                    }
                    ?>
                </div>
                <?php
            } elseif ( $model_form_row['type'] == "image" ) {
                ?>
                <div class="row">
                    <label for="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"><?=$model_form_row['label']?></label>
                    <div style="display:inline-block">
                        <?php
                        if ( !empty($model_object->{$attribute}) ) {
                            ?>
                            <img style="float: left" src="/<?= $image_folders['cms_images']['small']['path']?>/<?=$model_object->{$attribute}?>" alt="" />
                            <input style="margin-left: 5px" type="checkbox" value="" id="data_<?=MODEL_CLASS_NAME?>_<?=$attribute?>_delete" name="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]" />
                            <label for="data_<?=MODEL_CLASS_NAME?>_<?=$attribute?>_delete"><i class="fa fa-trash"></i></label>
                            <br/>
                            <?php
                        }
                        ?>
                        <input
                            type="file"
                            name="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"
                            id="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"
                            <?php foreach ($additional_attributes as $additional_attributes_name => $additional_attributes_value) {
                                echo $additional_attributes_name.'="'.clean_page($additional_attributes_value).'"';
                            }
                            ?>
                        />
                        <?php
                        if ( isset($model_form_row['info']) ) {
                            ?><div class="hint el"><i class="fa fa-info-circle"></i><div class="text" style="display: none;"><?=$model_form_row['info']?></div></div><?php
                        }
                        ?>
                    </div>

                </div>
                <?php
            } elseif ( $model_form_row['type'] == "file" ) {
                ?>
                <div class="row">
                    <label for="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"><?=$model_form_row['label']?></label>
                    <div style="display:inline-block">
                        <?php
                        if ( !empty($model_object->{$attribute}) ) {
                            ?>
                            <a href="/uploads/files/<?=$model_object->{$attribute}?>" alt="" target="_blank" />
                                    <img style="float: left" src="/admin/images/file.png" alt="">
                            </a>
                            <?php/*<img style="float: left" src="/<?= $image_folders['cms_images']['small']['path']?>/<?=$model_object->{$attribute}?>" alt="" />*/?>
                            <input style="margin-left: 5px" type="checkbox" value="" id="data_<?=MODEL_CLASS_NAME?>_<?=$attribute?>_delete" name="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]" />
                            <label for="data_<?=MODEL_CLASS_NAME?>_<?=$attribute?>_delete"><i class="fa fa-trash"></i></label>
                            <br/>
                            <?php
                        }
                        ?>
                        <input
                            type="file"
                            name="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"
                            id="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"
                            <?php foreach ($additional_attributes as $additional_attributes_name => $additional_attributes_value) {
                                echo $additional_attributes_name.'="'.clean_page($additional_attributes_value).'"';
                            }
                            ?>
                        />
                    </div>
                </div>
                <?php
            } elseif ( $model_form_row['type'] == "number" ) {

                if ( isset($_REQUEST['data'][MODEL_CLASS_NAME][$attribute]) ) {
                    $value = $_REQUEST['data'][MODEL_CLASS_NAME][$attribute];
                } else {
                    $value = $model_object->{$attribute};
                }

                ?>
                <div class="row">
                    <label for="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"><?=$model_form_row['label']?></label>
                    <input
                        type="number"
                        name="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"
                        id="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"
                        value="<?=clean_page($value)?>"
                        class="INPUT1 <?=$model_form_row['class']?>"
                        <?php foreach ($additional_attributes as $additional_attributes_name => $additional_attributes_value) {
                            echo $additional_attributes_name.'="'.clean_page($additional_attributes_value).'"';
                        }
                        ?>
                    />
                    <?php
                    if ( isset($model_form_row['info']) ) {
                        ?><div class="hint el"><i class="fa fa-info-circle"></i><div class="text" style="display: none;"><?=$model_form_row['info']?></div></div><?php
                    }
                    ?>
                </div>
                <?php
            } elseif ( $model_form_row['type'] == "textarea" ) {

                if ( isset($_REQUEST['data'][MODEL_CLASS_NAME][$attribute]) ) {
                    $value = $_REQUEST['data'][MODEL_CLASS_NAME][$attribute];
                } else {
                    $value = $model_object->{$attribute};
                }

                ?>
                <div class="row">
                    <label for="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"><?=$model_form_row['label']?></label>
                    <textarea
                        name="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"
                        id="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"
                        class="INPUT1 <?=$model_form_row['class']?>"
                        <?php foreach ($additional_attributes as $additional_attributes_name => $additional_attributes_value) {
                            echo $additional_attributes_name.'="'.clean_page($additional_attributes_value).'"';
                        }
                        ?>
                    ><?=clean_page($value)?></textarea>
                    <?php
                    if ( isset($model_form_row['info']) ) {
                        ?><div class="hint el"><i class="fa fa-info-circle"></i><div class="text" style="display: none;"><?=$model_form_row['info']?></div></div><?php
                    }
                    ?>
                </div>
                <?php
            } elseif ( $model_form_row['type'] == "select" ) {

                if ( isset($_REQUEST['data'][MODEL_CLASS_NAME][$attribute]) ) {
                    $value = $_REQUEST['data'][MODEL_CLASS_NAME][$attribute];
                } else {
                    $value = $model_object->{$attribute};
                }

                ?>
                <div class="row">
                    <label for="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"><?=$model_form_row['label']?></label>
                    <select
                        name="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"
                        id="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"
                        class="INPUT1 <?=$model_form_row['class']?>"
                        <?php foreach ($additional_attributes as $additional_attributes_name => $additional_attributes_value) {
                            echo $additional_attributes_name.'="'.clean_page($additional_attributes_value).'"';
                        }
                        ?>
                    >
                        <?php
                        if ( isset($model_form_row['options']) && !is_array($model_form_row['options']) ) {
                            $options = array();
                            $options_object_name = $model_form_row['options'];
                            $options_object_raw_list = $options_object_name::where('active', '=', 1)->get();
                            foreach ($options_object_raw_list as $key => $options_object_raw_item) {
                                $options[$options_object_raw_item->id] = $options_object_raw_item->title." ".$options_object_raw_item->name." ".$options_object_raw_item->surname;
                            }
                        } else {
                            $options = $model_form_row['options'];
                        }
                        foreach ($options as $key => $option) {
                            ?>
                            <option <?=isset($value) && $value == $key ? 'selected' : ''?> value="<?=clean_page($key)?>"><?=clean_page($option)?></option>
                            <?php
                        }
                        ?>
                    </select>
                    <?php
                    if ( isset($model_form_row['info']) ) {
                        ?><div class="hint el"><i class="fa fa-info-circle"></i><div class="text" style="display: none;"><?=$model_form_row['info']?></div></div><?php
                    }
                    ?>
                </div>
                <?php
            } elseif ( $model_form_row['type'] == "checkbox" ) {

                if ( isset($_REQUEST['data'][MODEL_CLASS_NAME][$attribute]) ) {
                    $value = $_REQUEST['data'][MODEL_CLASS_NAME][$attribute];
                } else {
                    $value = $model_object->{$attribute};
                }

                ?>
                <div class="row">
                    <label for="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"><?=$model_form_row['label']?></label>
                    <input
                        type="hidden"
                        name="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"
                        value="0"
                    />
                    <input
                        type="checkbox"
                        name="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"
                        value="1"
                        id="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"
                        class="INPUT1 <?=$model_form_row['class']?>"
                        <?php foreach ($additional_attributes as $additional_attributes_name => $additional_attributes_value) {
                            echo $additional_attributes_name.'="'.clean_page($additional_attributes_value).'"';
                        }
                        ?>
                        <?php
                        if ( $value ) {
                            echo 'checked';
                        }
                        ?>
                    />
                    <?php
                    if ( isset($model_form_row['info']) ) {
                        ?><div class="hint el"><i class="fa fa-info-circle"></i><div class="text" style="display: none;"><?=$model_form_row['info']?></div></div><?php
                    }
                    ?>
                </div>
                <?php
            } elseif ( $model_form_row['type'] == "hidden" ) {

                if ( isset($_REQUEST['data'][MODEL_CLASS_NAME][$attribute]) ) {
                    $value = $_REQUEST['data'][MODEL_CLASS_NAME][$attribute];
                } else {
                    $value = $model_object->{$attribute};
                }

                ?>
                <input
                    type="hidden"
                    name="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"
                    id="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"
                    value="<?=clean_page($value)?>"
                    class="INPUT1 <?=$model_form_row['class']?>"
                    <?php foreach ($additional_attributes as $additional_attributes_name => $additional_attributes_value) {
                        echo $additional_attributes_name.'="'.clean_page($additional_attributes_value).'"';
                    }
                    ?>
                />
                <?php
            } else { // ( $model_form_row['type'] == "text" )

                if ( isset($_REQUEST['data'][MODEL_CLASS_NAME][$attribute]) ) {
                    $value = $_REQUEST['data'][MODEL_CLASS_NAME][$attribute];
                } else {
                    $value = $model_object->{$attribute};
                }

                ?>
                <div class="row">
                    <label for="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"><?=$model_form_row['label']?></label>
                    <input
                        type="text"
                        name="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"
                        id="data[<?=MODEL_CLASS_NAME?>][<?=$attribute?>]"
                        value="<?=clean_page($value)?>"
                        class="INPUT1 <?=$model_form_row['class']?>"
                        <?php foreach ($additional_attributes as $additional_attributes_name => $additional_attributes_value) {
                            echo $additional_attributes_name.'="'.clean_page($additional_attributes_value).'"';
                        }
                        ?>
                    />
                    <?php
                    if ( isset($model_form_row['info']) ) {
                        ?><div class="hint el"><i class="fa fa-info-circle"></i><div class="text" style="display: none;"><?=$model_form_row['info']?></div></div><?php
                    }
                    ?>
                </div>
                <?php
            }
        }

        ?>
    	<input type="hidden" name="action" value="update"/>
    	<input type="hidden" name="data[<?=MODEL_CLASS_NAME?>][id]" value="<?=$_GET['id']?>"/>

    	<div class="row">
            <input type="submit" value="Save"/>
        </div>
	</fieldset>
</form>

<?php
include($core_root_path.'admin/templates/adminfooter.html.php');
