<?php

use Mtc\Shop\CustomField;
use Mtc\Shop\CustomFieldSet;
use Mtc\Shop\CustomFieldSetField;

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

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

$display_form    = true;
$errors          = array();
$customfield_set = array();
$set_field       = array(
    'id' => null,
    'custom_field_id' => null,
    'required' => null,
    'filter' => null,
    'variations' => null,
);
$errors = [];

if (!empty($_REQUEST['id'])) {
    $customfield_set = CustomFieldSet::query()
        ->findOrNew($_REQUEST['id'])
        ->toArray();
}

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


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

    $customfield_set['default'] = 0;
    if (!empty($_REQUEST['default'])) {
        $customfield_set['default'] = 1;
    }

    if (count($errors) === 0) {
        $params = array(
            ':name'    => $customfield_set['name'],
            ':default' => $customfield_set['default']
        );

        if ($customfield_set['id'] > 0) {
            CustomFieldSet::query()
                ->where('id', $customfield_set['id'])
                ->update([
                    'name' => $customfield_set['name'],
                    'default' => $customfield_set['default']
                ]);
        } else {
            $customfield_set = CustomFieldSet::query()
                ->create([
                    'name' => $customfield_set['name'],
                    'default' => $customfield_set['default']
                ])
                ->toArray();
        }
    }
}

if ($_REQUEST['edit_id'] > 0) {
    $set_field = CustomFieldSetField::query()
        ->where('id', $_REQUEST['edit_id'])
        ->firstOrNew()
        ->toArray();
}

if ($_REQUEST['action'] === 'updatefield') {
    $set_field['custom_field_id'] = $_REQUEST['custom_field_id'];
    if ($_REQUEST['custom_field_id'] === '') {
        $errors['custom_field_id'] = 'Please select Custom Field.';
    }
    $set_field['required'] = 0;
    if (!empty($_REQUEST['required'])) {
        $set_field['required'] = 1;
    }

    $set_field['filter'] = 0;
    if (!empty($_REQUEST['filter'])) {
        $set_field['filter'] = 1;
    }

    $set_field['items'] = 0;
    if (!empty($_REQUEST['items'])) {
        $set_field['items'] = 1;
    }

    $set_field['variations'] = 0;
    if (!empty($_REQUEST['variations'])) {
        $set_field['variations'] = 1;
    }

    if (empty($errors)) {
        $params = array(
            'set_id'          => $customfield_set['id'],
            'custom_field_id' => $set_field['custom_field_id'],
            'required'        => $set_field['required'],
            'items'           => $set_field['items'],
            'variations'      => $set_field['variations'],
            'filter'          => $set_field['filter'],
        );
        if ($set_field['id'] > 0) {
            CustomFieldSetField::query()
                ->where('id', $set_field['id'])
                ->update($params);
        } else {
            CustomFieldSetField::query()
                ->create($params);
        }
        $set_field = [];
    }

}

if ($_REQUEST['action'] === 'remove' && is_numeric($_REQUEST['remove_id'])) {
    CustomFieldSetField::query()
        ->where('id', $_REQUEST['remove_id'])
        ->delete();
}

$addedit = 'Add';
if ($_REQUEST['id'] > 0) {
    $addedit = 'Update';
}
$page_meta['title'] = $addedit . ' Custom Field Set';

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.sets.php">Manage Custom Fields</a> /</li>

        <li class="end"><?= $addedit ?> Custom Field</li>
    </ul>

    <h1><?= $addedit ?> Custom Field</h1>
<?php

include __DIR__ . '/tabnav.sets.php';

if (isset($updated) && count($errors) === 0 && isset($_REQUEST['action'])) {
    echo showmsg('Set Updated', 'success', $path);
}

if (count($errors) > 0) {
    showerrors($errors);
}

if ($display_form) { ?>
    <form action="edit.customfields.set.php" method="POST" enctype="multipart/form-data" class="style">
        <fieldset class="show">
            <h1><a class="show el">Set 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($customfield_set['name']); ?>"
                       class="INPUT1"/>
            </div>

            <div class="row">
                <label for="default">Use as Default on products</label>
                <input type="checkbox" name="default" id="default" value="1"
                       class="INPUT1"
                    <?= ($customfield_set['default'] == 1) ? 'checked' : ''; ?>
                />
            </div>
        </fieldset>

        <input type="hidden" name="action" value="updateproperty"/>
        <input type="hidden" name="id" value="<?= clean_page($customfield_set['id']); ?>"/>
        <div class="row"><input type="submit" value="Save"/></div>
    </form>

    <?php if ($customfield_set['id'] > 0) { ?>
        <h1>Set Fields</h1>
        <?php
        $fields = CustomFieldSetField::query()
            ->where('set_id', $customfield_set['id'])
            ->get();

        if ($fields->count() === 0) { ?>
            <p>You have not yet added any fields to the set.</p>
        <?php } else { ?>
            <table class="manage-items">
                <tr>
                    <th>Custom Field Name</th>
                    <th>Required</th>
                    <th>In Filter</th>
                    <th>Applies to Items</th>
                    <th>Applies to Variations</th>
                </tr>
                <?php
                foreach ($fields as $field) {
                    $set_field_data = $field->toArray();
                    ?>
                    <tr>
                        <td><?= clean_page(CustomFieldsHelper::getCustomFieldName($set_field_data['custom_field_id'])); ?></td>
                        <td><?= ((int)$set_field_data['required'] === 1) ? 'Yes' : ''; ?></td>
                        <td><?= ((int)$set_field_data['filter'] === 1) ? 'Yes' : ''; ?></td>
                        <td><?= ((int)$set_field_data['items'] === 1) ? 'Yes' : ''; ?></td>
                        <td><?= ((int)$set_field_data['variations'] === 1) ? 'Yes' : ''; ?></td>
                        <td>
                            <a href="edit.customfields.set.php?id=<?= $customfield_set['id']; ?>&edit_id=<?= $set_field_data['id']; ?>">Edit</a>
                        </td>
                        <td>
                            <a href="edit.customfields.set.php?id=<?= $customfield_set['id']; ?>&remove_id=<?= $set_field_data['id']; ?>&action=remove"
                               class="alert error" title="Are you sure you want to delete this custom field?">
                                <i class="fa fa-times-circle"></i>
                            </a>
                        </td>
                    </tr>
                <?php } ?>
            </table>
        <?php } ?>

        <form action="edit.customfields.set.php" method="POST" enctype="multipart/form-data" class="style">
            <fieldset class="show">
                <h1><a class="show el">
                        <?= (isset($set_field['id']) && $set_field['id'] > 0) ? 'Edit' : 'Add'; ?> Field <i class="fa fa-caret-right"></i>
                    </a>
                </h1>
                <div class="row">
                    <label for="select_field">Custom Field</label>
                    <select id="select_field" name="custom_field_id">
                        <option value="">Select Field</option>
                        <?php
                        $customFields = CustomField::all();
                        $tpl = '<option value="%d"%s>%s</option>';
                        foreach ($customFields as $customField) {
                            $data = $customField->toArray();
                            $sel = '';
                            if ($data['id'] == $set_field['custom_field_id']) {
                                $sel = ' selected="selected"';
                            }

                            printf($tpl, $data['id'], $sel, clean_page($data['name'] . '(' . $data['type'] . ')'));
                        }

                        ?>
                    </select>
                </div>

                <div class="row">
                    <label for="required">Required Field</label>
                    <input id="required" type="checkbox" name="required" value="1"
                        <?= ($set_field['required'] == 1) ? 'checked' : ''; ?> />
                </div>

                <div class="row">
                    <label for="filter">In Filter</label>
                    <input id="filter" type="checkbox" name="filter" value="1"
                        <?= ($set_field['filter'] == 1) ? 'checked' : ''; ?> />
                </div>

                <div class="row">
                    <label for="items">Applies to Items</label>
                    <input id="items" type="checkbox" name="items" value="1"
                        <?= (!isset($set_field['items']) || $set_field['items'] === 1) ? 'checked' : ''; ?>/>
                </div>

                <div class="row">
                    <label for="variations">Applies to Variations</label>
                    <input id="variations" type="checkbox" name="variations" value="1"
                        <?= ($set_field['variations'] == 1) ? 'checked' : ''; ?> />
                </div>

            </fieldset>

            <input type="hidden" name="action" value="updatefield"/>
            <input type="hidden" name="id" value="<?= clean_page($customfield_set['id']); ?>"/>
            <input type="hidden" name="edit_id" value="<?= clean_page($set_field['id']); ?>"/>
            <div class="row"><input type="submit" value="Save"/></div>

            <?php if ($set_field['id'] > 0) { ?>
                <a href="edit.customfields.set.php?id=<?= $customfield_set['id']; ?>">Cancel Edit</a>
            <?php } ?>

        </form>

        <?php
    }
}

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