<?php
use Mtc\Shop\CustomField;

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

init_request_values([
    'id' => null,
]);

use Illuminate\Database\Capsule\Manager as Capsule;
use Mtc\Shop\PropertyType;

if ($_REQUEST['id'] > 0) {
    $add_edit = 'Update';
} else {
    $add_edit = 'Add';
}

$page_meta['title'] = $add_edit . ' Property';

$display_form = true;
$custom_field = null;

$custom_field_original = [
        'database_field' => false
];

if (!empty($_REQUEST['id'])) {

    $custom_field = CustomField::query()
        ->find($_REQUEST['id'])
        ->toArray();
    $custom_field_original = $custom_field;

}

/*
  Add A New Property
 */
if ($_REQUEST['action'] == 'updateproperty') {

    $custom_field['name'] = $_REQUEST['name'];

    if (empty($custom_field['name'])) {
        $errors['name'] = 'Please enter the custom field name.';
    }

    $custom_field['database_field'] = trim($_REQUEST['database_field']);

    if (empty($custom_field['database_field'])) {
        $errors['database_field'] = 'Please enter the custom field name.';
    }

    /*
     * checks if custom field name is according to MySQL reference to Schema Object Names
     * (custom database field is not a number, does not start or end with an integer, has no more than 64 characters
     * and has the format of [a-z, A-Z, 0-9, $, _])
     * http://dev.mysql.com/doc/refman/5.7/en/identifiers.html
     */
    if (!preg_match('/^(?![0-9])([a-zA-Z0-9$_]{1,64}+)(?<![0-9])$/', $custom_field['database_field'])) {
        $errors['database_field_reg'] = 'Custom field name cannot start/end with numbers and can contain only A-Z,a-z,0-9,_,$.';
    }

    $custom_field['type'] = $_REQUEST['type'];

    if (empty($custom_field['type'])) {
        $errors['type'] = 'Please enter the custom field type.';
    }

    $custom_field['custom_field_list_id'] = (int)$_REQUEST['custom_field_list_id'];

    $custom_field['multiple'] = 0;

    if (!empty($_REQUEST['multiple'])) {
        $custom_field['multiple'] = 1;
    }

    $custom_field['quantity'] = (int)$_REQUEST['quantity'];

    if (empty($errors)) {

        /*
         * Update Table Structure
         */
        if ($custom_field['database_field'] != $custom_field_original['database_field'] && !empty($custom_field_original['database_field'])) {
            //Database field name has changed

            $from = $custom_field_original['database_field'];
            $to = $custom_field['database_field'];

            Capsule::schema()->table('items_custom', function($table) use($from, $to) {
                $table->renameColumn($from, $to);
            });

            Capsule::schema()->table('items_sizes_custom', function($table) use($from, $to) {
                $table->renameColumn($from, $to);
            });


        } else {

      
           
            if(!empty($custom_field['database_field'])) {
                
                //Create the column
                $field = $custom_field['database_field'];
                
                
                if (!Capsule::schema()
                            ->hasColumn('items_custom', $field)) {
                    Capsule::schema()
                           ->table('items_custom', function ($table) use ($field,$custom_field) {
                               if ($custom_field['type'] == 'textarea') {
                                   $table->text($field);
                               } else {
                                   $table->string($field);
                                   $table->index($field);
                               }
                           })
                    ;
                }

                if (!Capsule::schema()
                            ->hasColumn('items_sizes_custom', $field)) {
                    Capsule::schema()
                           ->table('items_sizes_custom', function ($table) use ($field, $custom_field) {
                               if ($custom_field['type'] == 'textarea') {
                                   $table->text($field);
                               } else {
                                   $table->string($field);
                                   $table->index($field);
                               }
                           })
                    ;
                }

            }
        }
        
        if(empty($custom_field)) {
            header('Location: manage.customfields.php?message=error');
            exit();
        }
        
        $params = [
            'name' => $custom_field['name'],
            'database_field' => $custom_field['database_field'],
            'type' => $custom_field['type'],
            'custom_field_list_id' => $custom_field['custom_field_list_id'],
            'multiple' => $custom_field['multiple'],
            'quantity' => $custom_field['quantity']
        ];

        if (!empty($custom_field['id'])) {
            CustomField::query()
                ->where('id', $_REQUEST['id'])
                ->update($params);
            header('Location: manage.customfields.php?message=update');
        } else {
            CustomField::query()
                ->create($params);
            header('Location: manage.customfields.php?message=added');
        }
        exit();
    }
}

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

?>
<ul class="breadcrumbs el">
    <li><a href="/admin/">Home</a> /</li>
    <li><a href="manage.customfields.php">Manage Custom Fields</a> /</li>
    <li class="end"><?= clean_page($add_edit) ?> Custom Field</li>
</ul>

<h1><?= clean_page($add_edit) ?> Custom Field</h1>

<?php
include 'tabnav.php';

if (isset($updated)) {

    if (empty($errors) && isset($_REQUEST['action'])) {
        echo showmsg("Property updated", "success", $path);
    }

}

if (!empty($errors)) {
    showerrors($errors);
}

if ($display_form === true) {

    ?>

    <form action="edit.customfield.php" method="POST" enctype="multipart/form-data" class="style">
        <fieldset class="show">
            <h1>
                <a class="show el">
                    Custom Field Information <i class="fa fa-caret-right"></i>
                </a>
            </h1>

            <div class="row">
                <label for="name">Name</label>
                <input type="text" name="name" id="name" value="<?= clean_page($custom_field['name'] ?? null) ?>" class="INPUT1">
            </div>

            <div class="row">
                <label for="name">Database Field Name</label>
                <input type="text" name="database_field" id="database_field" value="<?= clean_page($custom_field['database_field'] ?? null) ?>" class="INPUT1">
            </div>

            <div class="row">
                <label for="name">Type</label>
                <select name="type">
                    <option value="">Please Select</option>
                    <?php
                    foreach (CustomField::$field_types as $field_type => $field_name) {
                        $selected = (isset($custom_field) && $custom_field['type'] == $field_type) ? ' selected="selected"' : null;
                        echo '<option value="'.$field_type.'"'.$selected.'>'.clean_page($field_name).'</option>';
                    }
                    ?>
                </select>

            </div>

            <div class="row">
                <label for="name">Dropdown List</label>
                <select name="custom_field_list_id">
                    <option value="">Please Select</option>
                    <?php
                        $propertyTypes = PropertyType::query()
                            ->orderBy('order')
                            ->get();

                        foreach ($propertyTypes as $propertyType) {
                            $data = $propertyType->toArray();
                        ?>
                            <option value="<?= clean_page($data['id']) ?>"<?= (isset($custom_field) && $custom_field['custom_field_list_id'] == $data['id']) ? ' selected' : '' ?>><?= clean_page($data['name']) ?></option>
                        <?php
                        }

                    ?>
                </select>

            </div>

            <div class="row">
                <label for="name">Multiple Allowed</label>
                <input type="checkbox" name="multiple" id="multiple"<?= (isset($custom_field) && $custom_field['multiple'] == 1) ? ' checked' : '' ?> />
            </div>
            <div class="row">
                <label for="name">Quantity</label>
                <input type="text" name="quantity" id="quantity" value="<?= clean_page(isset($custom_field) && $custom_field['quantity']) ?>" class="INPUT1" />
            </div>
        </fieldset>

        <input type="hidden" name="action" value="updateproperty"/>
        <input type="hidden" name="id" value="<?= clean_page($_REQUEST['id']) ?>"/>

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

    </form>

<?php
}

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