<?php

use Mtc\Shop\Assessment\Form;
use Mtc\Shop\Assessment\Question;
use Mtc\Cms\Models\AssetGalleryIcon;

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

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

$display_form = true;

$errors = [];

$form_id = false;

if(isset($_REQUEST['id'])) {
    $form_id = $_REQUEST['id'];
}

$form = (new Form())->findOrNew($form_id);

$add_edit = $form_id ? 'Update' : 'Add';

$page_meta['title'] = $add_edit . ' Assessment Form';

if (filter_input(INPUT_GET, 'action') === 'get_variations') {
    if (!empty($_REQUEST['question_id'])) {
        $variations_question = Question::query()->find($_REQUEST['question_id']);
        if ($variations_question->question_type === 'yes_no' || $variations_question->question_type === 'notify_gp') {
            $variations = ['Yes', 'No'];
        } else {
            $variations = json_decode($variations_question->variations, true);
        }
        foreach ($variations as $variation) {
            echo "<option value='{$variation}'>{$variation}</option>";
        }
    }
    exit;
}



if ($_REQUEST['action'] === 'save') {
    if (empty($_POST['icon_id'])) {
        $_POST['icon_id'] = null;
    }
    $form->fill($_POST);

    //Save update date to use for cache busting previous answers on assessments
    $form->updated_at = date('Y-m-d H:i:s');
    $form->save(['timestamps' => false]);

    if (!empty($form->questions)) {
        foreach ($form->questions as $question) {
            if (!empty($_REQUEST['alert_if'][$question->id])) {
                $question->alert_if = json_encode($_REQUEST['alert_if'][$question->id]);
            } else {
                $question->alert_if = '';
            }
            if (!empty($_REQUEST['block_if'][$question->id])) {
                $question->block_if = json_encode($_REQUEST['block_if'][$question->id]);
            } else {
                $question->block_if = '';
            }
            if (!empty($_REQUEST['okay_if'][$question->id])) {
                $question->okay_if = json_encode($_REQUEST['okay_if'][$question->id]);
            } else {
                $question->okay_if = '';
            }
            if (!empty($_REQUEST['cant_proceed_if'][$question->id])) {
                $question->cant_proceed_if = json_encode($_REQUEST['cant_proceed_if'][$question->id]);
            } else {
                $question->cant_proceed_if = '';
            }
            $question->is_active = empty($_REQUEST['q_is_active'][$question->id]) ? '0' : '1';
            $question->is_required = empty($_REQUEST['q_is_required'][$question->id]) ? '0' : '1';
            $question->show_if_question = $_REQUEST['show_if_question'][$question->id] ?? 0;
            $question->show_if_answer = $_REQUEST['show_if_answer'][$question->id] ?? '';
            $form->questions()->save($question);
        }
    }
    header('location: manage.form.php?id=' . $form->id);
    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.forms.php">Manage Assessment Forms</a> /</li>
        <li class="end"><?= clean_page($page_meta['title']) ?></li>
    </ul>

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

include __DIR__ . '/tabnav.php';

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

$available_icons = array_values(AssetGalleryIcon::getAvailable());

?>

    <style>

        tr td  p  img {
            width: 100px;
            height: auto;
            max-width: 100%;
            max-height: none;
            min-height: 1px;
        }

    </style>

    <form action="" method="post" class="style">

        <fieldset class="show js-vue-environment">

            <h1><a class="show el"><?= $page_meta['title']; ?> <i class="fa fa-caret-right"></i></a></h1>

            <div class="row">
                <label for="form_name">Form Name</label>
                <input type="text" name="name" id="form_name" value="<?= clean_page($form->name); ?>" class=""/>
                <?php if (!empty($_REQUEST['id'])) { ?>
                    <a href="/shop/admin/assessment/copy.form.php?id=<?= $form->id; ?>" title="Make a copy of this form" class="button btn"><i class="fa fa-copy"></i> Copy</a>
                <?php } ?>
            </div>




        </fieldset>


        <?php
        if (!empty($form->id)) {
            ?>
            <fieldset class="show">
                <h1><a class="show el">Questions <i class="fa fa-caret-right"></i></a></h1>
                <?php
                if ($form->questions->count()) {
                    ?>
                    <table class="manage-items">
                        <tr>
                            <th class="center">Order</th>
                            <th>Show</th>
                            <th>Required</th>
                            <th>Question</th>
                            <th>Type</th>
                            <th>Tag with<br />"Alert" if</th>
                            <th>Tag with<br />"Block" if</th>
                            <th>Tag with<br />"Okay" if</th>
                            <th>Customer can't<br />proceed if</th>
                            <th>Show question if</th>
                            <th colspan="2">Actions</th>
                        </tr>
                        <tbody class="tabular ui-sortable">
                        <?php
                        foreach ($form->questions()->orderBy('sort')->get() as $question) {
                            $variations = (array)json_decode($question->variations);
                            $alert_ifs = (array)json_decode($question->alert_if);
                            $block_ifs = (array)json_decode($question->block_if);
                            $okay_ifs = (array)json_decode($question->okay_if);
                            $cant_proceed_ifs = (array)json_decode($question->cant_proceed_if);
                            ?>
                            <tr id="rorder-<?= clean_page($question->id) ?>" <?php if($question->question_type === 'section') { ?>style="background:#d7dce4;"<?php } ?>>
                                <td class="center order">
                                    <i class="fa fa-arrows"></i>
                                </td>
                                <td><input type="checkbox"
                                           name="q_is_active[<?= $question->id; ?>]" <?= $question->is_active ? 'checked' : ''; ?> />
                                </td>
                                <td>

                                    <?php if($question->question_type === 'section' || $question->question_type === 'information' || $question->question_type === 'information_green' || $question->question_type === 'alert' || $question->question_type === 'html') { ?>
                                        <input type="hidden"
                                               name="q_is_required[<?= $question->id; ?>]"
                                               value=""
                                        />
                                    <?php }else{ ?>
                                        <input type="checkbox"
                                               name="q_is_required[<?= $question->id; ?>]" <?= $question->is_required ? 'checked' : ''; ?> />
                                    <?php } ?>

                                </td>
                                <td>
                                    <div class="containField" style="max-width:200px;">

                                        <?php
                                        $question_text = $question->question_text;
                                        if(strlen(strip_tags($question_text)) > 100) {
                                            $question_text = substr(strip_tags($question_text),0,100).'...';
                                        }
                                        ?>
                                        <?= $question->question_type === 'section' ?
                                            '<strong>' . $question_text . '</strong>' :
                                            $question_text;
                                        ?>
                                        <?php
                                        if (!empty($question->recommended) || !empty($question->excluded)) {
                                            ?>
                                            <div class="recommendedItemBubble">
                                                <strong>Recommended</strong>
                                                <div>
                                                    <table>
                                                        <?php
                                                        $items = [];
                                                        if (!empty($question->recommended)) {
                                                            $items['RECOMMENDED'] = $question->recommended;
                                                        }
                                                        if (!empty($question->excluded)) {
                                                            $items['EXCLUDED'] = $question->excluded;
                                                        }
                                                        foreach ($items as $type => $values) {
                                                            ?>
                                                            <tr>
                                                                <td colspan="2" style="background: #000; color: #FFF;">
                                                                    <strong><?= $type; ?></strong>
                                                                </td>
                                                            </tr>
                                                            <tr>
                                                                <th>Answer</th>
                                                                <th>Product</th>
                                                            </tr>
                                                            <?php
                                                            foreach ($values as $answer => $recommended) {
                                                                ?>
                                                                <tr>
                                                                    <td><?= $answer; ?></td>
                                                                    <td>
                                                                        <?php
                                                                        foreach ($recommended as $item) {
                                                                            echo '<p><strong>' . $item['item_name'] . '</strong></p>';
                                                                            if (!empty($item['sizes'])) {
                                                                                echo '<ul>';
                                                                                foreach ($item['sizes'] as $size) {
                                                                                    echo '<li>' . $size['size_name'] . '</li>';
                                                                                }
                                                                                echo '</ul>';
                                                                            }
                                                                        }
                                                                        ?>
                                                                    </td>
                                                                </tr>
                                                                <?php
                                                            }
                                                        }
                                                        ?>
                                                        <tr>
                                                            <td colspan="2">
                                                                <a href="/shop/admin/assessment/manage.recommended.php?question_id=<?= $question->id; ?>&id=<?= $form->id; ?>">
                                                                    Manage Recommended / Excluded
                                                                </a>
                                                            </td>
                                                        </tr>
                                                    </table>
                                                </div>
                                            </div>
                                            <?php
                                        }
                                        ?>
                                    </div> <!-- .containField -->

                                </td>
                                <td><?php
                                    if(array_key_exists($question->question_type, Question::$question_types)) {
                                        if ($question->question_type === 'section') { ?>
                                            <strong>
                                        <?php }
                                        echo Question::$question_types[$question->question_type];

                                        if (
                                            !empty($question->subtype) &&
                                            !empty(Question::$question_subtypes[$question->question_type][$question->subtype])
                                        ) {
                                            echo ' (';
                                            echo Question::$question_subtypes[$question->question_type][$question->subtype];
                                            echo ')';
                                        }

                                        if ($question->question_type === 'section') { ?>
                                            </strong>
                                        <?php }
                                    }
                                    ?></td>
                                <td>
                                    <?php
                                    if ($question->question_type === 'variations') {
                                        ?>
                                        <?php
                                        $i = 0;
                                        foreach ($variations as $variation) {
                                            $checked = in_array($variation, $alert_ifs, true) ? 'checked' : '';
                                            echo "<input type='checkbox' name='alert_if[{$question->id}][]' value='{$variation}' id='variation-a-{$question->id}-{$i}' $checked> <label for='variation-a-{$question->id}-{$i}'>{$variation}</label><br />";
                                            ++$i;
                                        }
                                        ?>
                                        <?php
                                    } elseif ($question->question_type === 'yes_no' || $question->question_type === 'notify_gp') {
                                        ?>
                                        <select name="alert_if[<?= $question->id; ?>]">
                                            <option value="">Don't alert</option>
                                            <option value="Yes" <?= in_array('Yes', $alert_ifs, true) ? 'selected' : ''; ?>>
                                                Yes
                                            </option>
                                            <option value="No" <?= in_array('No', $alert_ifs, true) ? 'selected' : ''; ?>>
                                                No
                                            </option>
                                        </select>
                                        <?php
                                    } elseif ($question->question_type === 'yes') {
                                        ?>
                                        <select name="alert_if[<?= $question->id; ?>]">
                                            <option value="">Don't alert</option>
                                            <option value="Yes" <?= in_array('Yes', $alert_ifs, true) ? 'selected' : ''; ?>>
                                                Confirmed
                                            </option>
                                            <option value="No" <?= in_array('No', $alert_ifs, true) ? 'selected' : ''; ?>>
                                                Not Confirmed
                                            </option>
                                        </select>
                                        <?php
                                    }
                                    ?>
                                </td>
                                <td>
                                    <?php
                                    if ($question->question_type === 'variations') {
                                        ?>
                                        <?php
                                        $i = 0;
                                        foreach ($variations as $variation) {
                                            $checked = in_array($variation, $block_ifs, true) ? 'checked' : '';
                                            echo "<input type='checkbox' name='block_if[{$question->id}][]' value=\"{$variation}\" id='variation-b-{$question->id}-{$i}' $checked> <label for='variation-b-{$question->id}-{$i}'>{$variation}</label><br />";
                                            ++$i;
                                        }
                                        ?>
                                        <?php
                                    } elseif ($question->question_type === 'yes_no' || $question->question_type === 'notify_gp') {
                                        ?>
                                        <select name="block_if[<?= $question->id; ?>]">
                                            <option value="">Don't block</option>
                                            <option value="Yes" <?= in_array('Yes', $block_ifs, true) ? 'selected' : ''; ?>>
                                                Yes
                                            </option>
                                            <option value="No" <?= in_array('No', $block_ifs, true) ? 'selected' : ''; ?>>
                                                No
                                            </option>
                                        </select>
                                        <?php
                                    } elseif ($question->question_type === 'yes') {
                                        ?>
                                        <select name="block_if[<?= $question->id; ?>]">
                                            <option value="">Don't block</option>
                                            <option value="Yes" <?= in_array('Yes', $block_ifs, true) ? 'selected' : ''; ?>>
                                                Confirmed
                                            </option>
                                            <option value="No" <?= in_array('No', $block_ifs, true) ? 'selected' : ''; ?>>
                                                Not Confirmed
                                            </option>
                                        </select>
                                        <?php
                                    }
                                    ?>
                                </td>
                                <td>
                                    <?php
                                    if ($question->question_type === 'variations') {
                                        ?>
                                        <?php
                                        $i = 0;
                                        foreach ($variations as $variation) {
                                            $checked = in_array($variation, $okay_ifs, true) ? 'checked' : '';
                                            echo "<input type='checkbox' name='okay_if[{$question->id}][]' value=\"{$variation}\" id='variation-o-{$question->id}-{$i}' $checked> <label for='variation-o-{$question->id}-{$i}'>{$variation}</label><br />";
                                            ++$i;
                                        }
                                        ?>
                                        <?php
                                    } elseif ($question->question_type === 'yes_no' || $question->question_type === 'notify_gp') {
                                        ?>
                                        <select name="okay_if[<?= $question->id; ?>]">
                                            <option value="">-</option>
                                            <option value="Yes" <?= in_array('Yes', $okay_ifs, true) ? 'selected' : ''; ?>>
                                                Yes
                                            </option>
                                            <option value="No" <?= in_array('No', $okay_ifs, true) ? 'selected' : ''; ?>>
                                                No
                                            </option>
                                        </select>
                                        <?php
                                    } elseif ($question->question_type === 'yes') {
                                        ?>
                                        <select name="okay_if[<?= $question->id; ?>]">
                                            <option value="">-</option>
                                            <option value="Yes" <?= in_array('Yes', $okay_ifs, true) ? 'selected' : ''; ?>>
                                                Confirmed
                                            </option>
                                            <option value="No" <?= in_array('No', $okay_ifs, true) ? 'selected' : ''; ?>>
                                                Not Confirmed
                                            </option>
                                        </select>
                                        <?php
                                    }
                                    ?>
                                </td>
                                <td>
                                    <?php
                                    if ($question->question_type === 'variations') {
                                        ?>
                                        <?php
                                        $i = 0;
                                        foreach ($variations as $variation) {
                                            $checked = in_array($variation, $cant_proceed_ifs, true) ? 'checked' : '';
                                            echo "<input type='checkbox' name='cant_proceed_if[{$question->id}][]' value=\"{$variation}\" id='variation-c-{$question->id}-{$i}' $checked> <label for='variation-c-{$question->id}-{$i}'>{$variation}</label><br />";
                                            ++$i;
                                        }
                                        ?>
                                        <?php
                                    } elseif ($question->question_type === 'yes_no' || $question->question_type === 'notify_gp') {
                                        ?>
                                        <select name="cant_proceed_if[<?= $question->id; ?>]">
                                            <option value="">Don't block</option>
                                            <option value="Yes" <?= in_array('Yes', $cant_proceed_ifs, true) ? 'selected' : ''; ?>>
                                                Yes
                                            </option>
                                            <option value="No" <?= in_array('No', $cant_proceed_ifs, true) ? 'selected' : ''; ?>>
                                                No
                                            </option>
                                        </select>
                                        <?php
                                    } elseif ($question->question_type === 'yes') {
                                        ?>
                                        <select name="cant_proceed_if[<?= $question->id; ?>]">
                                            <option value="">Don't block</option>
                                            <option value="Yes" <?= in_array('Yes', $cant_proceed_ifs, true) ? 'selected' : ''; ?>>
                                                Confirmed
                                            </option>
                                            <option value="No" <?= in_array('No', $cant_proceed_ifs, true) ? 'selected' : ''; ?>>
                                                Not Confirmed
                                            </option>
                                        </select>
                                        <?php
                                    }
                                    ?>
                                </td>
                                <td>
                                    <div class="containField" style="max-width:180px">
                                        <select name="show_if_question[<?= $question->id; ?>]" class="showIfQuestion" style="max-width:100%;"
                                                data-question_id="<?= $question->id; ?>">
                                            <option value="">No condition</option>
                                            <?php
                                            $other_questions = $form
                                                ->questions()
                                                ->where('id', '<>', $question->id)
                                                ->whereIn('question_type', ['variations', 'yes_no', 'notify_gp'])
                                                ->get();

                                            foreach ($other_questions as $other_question) {
                                                // List all the other questions
                                                $selected = ($question->show_if_question == $other_question->id) ? 'selected' : '';
                                                echo "<option value='{$other_question->id}' {$selected}>{$other_question->question_text}</option>";
                                            }
                                            ?>
                                        </select><br/>
                                        <select name="show_if_answer[<?= $question->id; ?>]"
                                                style="max-width:100%;min-width: 100%;margin-top: 4px;"
                                                id="show_if_variation-<?= $question->id; ?>">
                                            <?php
                                            if (!empty($question->show_if_question)) {
                                                $variations_question = Question::query()->find($question->show_if_question);

                                                if(!empty($variations_question->question_type)) {
                                                    if ($variations_question->question_type
                                                        === 'yes_no'
                                                        || $variations_question->question_type
                                                        === 'notify_gp') {
                                                        $variations = [
                                                            'Yes',
                                                            'No'
                                                        ];
                                                    } else {
                                                        $variations = json_decode($variations_question->variations, true);
                                                    }
                                                    if (!empty($variations)) {
                                                        foreach ($variations as $variation) {
                                                            // List all the variations of the question
                                                            $selected = $question->show_if_answer
                                                            === $variation ? 'selected' : '';
                                                            echo "<option value='{$variation}' {$selected}>{$variation}</option>";
                                                        }
                                                    }
                                                }

                                            }
                                            ?>
                                        </select>
                                    </div> <!-- .containField -->
                                </td>
                                <td class="center"><a
                                            href="manage.question.php?question_id=<?= $question->id; ?>&id=<?= $form->id; ?>"
                                            class="edit"><i class="fa fa-pencil"></i></a></td>
                                <td class="center">
                                    <a href="manage.question.php?id=<?= (int)$form->id ?>&action=delete&delete_id=<?= $question->id; ?>"
                                       class="alert picto error"
                                       title="Are you sure you want to delete the Question?">
                                        <i class="fa fa-times-circle"></i>
                                    </a>
                                </td>
                            </tr>
                            <?php
                        }
                        ?>
                        </tbody>
                    </table>

                    <input type="hidden" id="orderbytable" value="assessment_questions"/>
                    <input type="hidden" id="orderbyfield" value="sort"/>
                    <?php
                } else {
                    ?>
                    <p>No questions have been added yet.</p>
                    <?php
                }
                ?>
            </fieldset>
            <fieldset>
                <div class="addQuestion">
                    <a href="manage.question.php?id=<?= $form->id; ?>"><h4><i class="fa fa-plus"></i> Add question</h4>
                    </a>
                </div>
            </fieldset>
            <?php
        }
        ?>
        <fieldset>
            <div class="save-button">
                <input type="hidden" name="action" value="save"/>
                <input type="submit" value="Save"/>
            </div>
        </fieldset>
    </form>

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