<?php

use Mtc\Shop\Assessment\Form;
use Mtc\Shop\Assessment\Question;

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

$display_form = true;

$errors = [];

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

if (!empty($_REQUEST['action']) && $_REQUEST['action'] === 'delete' && is_numeric($_REQUEST['delete_id'] ?? null)) {
    $question = (new Question())->find($_REQUEST['delete_id']);
    $form_id = $question->form_id;
    // Delete the question
    $question->delete();
    header('location: manage.form.php?id=' . $form_id);
    exit;
}

$question = (new Question())->findOrNew($_REQUEST['question_id']);
if (!$form = (new Form())->find($_REQUEST['id'])) {
    header('location: manage.forms.php');
    exit;
}

$addedit = $_REQUEST['question_id'] ? 'Update' : 'Add';

$page_meta['title'] = $addedit . ' Assessment Question';

if ($_REQUEST['action'] === 'save') {
    $request = $_POST;
    if ($request['question_type'] === 'variations') {
        $variations = explode("\r\n", $request['variations']);
        $variations = array_map('trim', $variations);
        $variations = array_map('clean_page', $variations);
        $request['variations'] = json_encode($variations);
        $request['is_multiple'] = $request['is_multiple'] ?? 0;
    } else {
        $request['variations'] = '';
        $request['is_multiple'] = 0;
    }

    $request['question_text'] = $request['question_text_html'];

    $request['is_active'] = empty($request['is_active']) ? '0' : '1';
    $request['is_required'] = empty($request['is_required']) ? '0' : '1';

    $question->fill($request);

    $question->subtype = null;

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

    $question->alert_if = '';
    $question->block_if = '';
    $question->okay_if = '';
    $question->cant_proceed_if = '';

    if (in_array($question->question_type, ['variations', 'yes_no', 'notify_gp', 'yes'], true)) {
        if (!empty($_REQUEST['alert_if'])) {
            $question->alert_if = json_encode($_REQUEST['alert_if']);
        }
        if (!empty($_REQUEST['block_if'])) {
            $question->block_if = json_encode($_REQUEST['block_if']);
        }
        if (!empty($_REQUEST['okay_if'])) {
            $question->okay_if = json_encode($_REQUEST['okay_if']);
        }
        if (!empty($_REQUEST['cant_proceed_if'])) {
            $question->cant_proceed_if = json_encode($_REQUEST['cant_proceed_if']);
        }
    }

    $question->show_if_question = $_REQUEST['show_if_question'] ?? 0;
    $question->show_if_answer = $_REQUEST['show_if_answer'] ?? '';

    $question->save();

    if (empty($_REQUEST['question_id'])) {
        $question->sort = $question->id;
        $question->save();
    }

    if (!empty($_REQUEST['save_and_back'])) {
        header('location: manage.form.php?id=' . $form->id);
    } elseif (!empty($_REQUEST['save_and_add'])) {
        header('location: manage.question.php?id=' . $form->id);
    } else {
        header('location: manage.question.php?question_id=' . $question->id . '&id=' . $form->id);
    }
    exit;
}

$variations = (array)json_decode((string)$question->variations);
$alert_ifs = (array)json_decode((string)$question->alert_if);
$block_ifs = (array)json_decode((string)$question->block_if);
$okay_ifs = (array)json_decode((string)$question->okay_if);
$cant_proceed_ifs = (array)json_decode((string)$question->cant_proceed_if);

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><a href="manage.form.php?id=<?= $form->id; ?>"><?= $form->name; ?></a> /</li>
        <li class="end"><?= clean_page($page_meta['title']) ?></li>
    </ul>

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

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

    <form action="" method="post" class="style">
        <fieldset class="show">
            <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</label>
                <?= clean_page($form->name); ?>
            </div>
            <div class="row">
                <label for="question_type_select">Type</label>

                <select name="question_type" id="question_type_select">
                    <?php
                    foreach (Question::$question_types as $question_type => $type_name) {
                        $selected = $question_type === $question->question_type ? 'selected' : '';
                        echo "<option value='{$question_type}' {$selected}>{$type_name}</option>";
                    }
                    ?>
                </select>
            </div>
            <?php
            foreach (Question::$question_subtypes as $type => $subtypes) {
                ?>
                <div class="row question_subtypes"
                     id="subtypes_<?= $type; ?>"
                >
                    <label for="question_subtype_select">
                        Sub Type
                    </label>

                    <select name="subtype_<?= $type; ?>" id="question_subtype_select">
                        <?php
                        foreach ($subtypes as $subtype => $subtype_name) {
                            $selected = $subtype === $question->subtype ? 'selected' : '';
                            echo "<option value='{$subtype}' {$selected}>{$subtype_name}</option>";
                        }
                        ?>
                    </select>
                </div>
                <?php
            }
            ?>
            <div class="row" id="question_text_html_row">
                <label for="question_text_html">HTML</label>
                <textarea
                        name="question_text_html"
                        class="tinymce"
                        id="question_text_html"
                ><?= clean_page($question->question_text) ?></textarea>
            </div>
            <div class="row" id="variations_row">
                <label for="variations">Variations (one per row)</label>
                <textarea name="variations"
                          id="variations"><?= empty($question->variations) ? '' : clean_page(implode("\n", json_decode((string)$question->variations))); ?></textarea>
            </div>
            <div class="row" id="variations_clearall_row">
                <label for="">Clear-all answer</label>
                <select name="clearall_answer">
                    <option value="">--- select ---</option>
                    <?php foreach ((array)json_decode((string)$question->variations) as $v): ?>
                        <option <?= $v == $question->clearall_answer ? 'selected' : '' ?>><?= $v ?></option>
                    <?php endforeach ?>
                </select>
            </div>
            <div class="row" id="allow_multiple">
                <label for="is_multiple">Allow multiple</label>
                <input type="checkbox" name="is_multiple" id="is_multiple" value="1"
                       class="" <?= $question->is_multiple ? 'checked' : ''; ?> />
            </div>
            <div class="row">
                <label for="is_required">Required</label>
                <input type="checkbox" name="is_required" id="is_required" value="1"
                       class="" <?= $question->is_required ? 'checked' : ''; ?> />
            </div>
            <div class="row">
                <label for="is_active">Active</label>
                <input type="checkbox" name="is_active" id="is_active" value="1"
                       class="" <?= $question->is_active ? 'checked' : ''; ?> />
            </div>
            <?php
            if ($question->question_type === 'variations') {
                ?>
                <table class="questionAttributesTable">
                    <tr>
                        <td width="16%"><label for="alert_if"><strong>Alert If</strong></label></td>
                        <td>
                            <?php
                            $i = 0;
                            foreach ($variations as $variation) {
                                $checked = in_array($variation, $alert_ifs, true) ? 'checked' : '';
                                echo "<input type='checkbox' name='alert_if[]' value='{$variation}' id='variation-a-{$i}' $checked> <label for='variation-a-{$i}'>{$variation}</label><br />";
                                ++$i;
                            }
                            ?>
                        </td>
                    </tr>
                    <tr>
                        <td><label for="block_if"><strong>Block If</strong></label></td>
                        <td>
                            <?php
                            $i = 0;
                            foreach ($variations as $variation) {
                                $checked = in_array($variation, $block_ifs, true) ? 'checked' : '';
                                echo "<input type='checkbox' name='block_if[]' value=\"{$variation}\" id='variation-b-{$i}' $checked> <label for='variation-b-{$i}'>{$variation}</label><br />";
                                ++$i;
                            }
                            ?>
                        </td>
                    </tr>
                    <tr>
                        <td><label for="okay_if"><strong>Okay If</strong></label></td>
                        <td>
                            <?php
                            $i = 0;
                            foreach ($variations as $variation) {
                                $checked = in_array($variation, $okay_ifs, true) ? 'checked' : '';
                                echo "<input type='checkbox' name='okay_if[]' value=\"{$variation}\" id='variation-o-{$i}' $checked> <label for='variation-o-{$i}'>{$variation}</label><br />";
                                ++$i;
                            }
                            ?>
                        </td>
                    </tr>
                    <tr>
                        <td><label for="cant_proceed_if"><strong>Can't Proceed If</strong></label></td>
                        <td>
                            <?php
                            $i = 0;
                            foreach ($variations as $variation) {
                                $checked = in_array($variation, $cant_proceed_ifs, true) ? 'checked' : '';
                                echo "<input type='checkbox' name='cant_proceed_if[]' value=\"{$variation}\" id='variation-c-{$i}' $checked> <label for='variation-c-{$i}'>{$variation}</label><br />";
                                ++$i;
                            }
                            ?>
                        </td>
                    </tr>
                </table>
                <?php
            } elseif (in_array($question->question_type, ['yes_no', 'notify_gp', 'yes'], true)) {
                ?>
                <div class="row">
                    <label for="alert_if">Alert If</label>
                    <?php
                    if ($question->question_type === 'yes_no' || $question->question_type === 'notify_gp') {
                        ?>
                        <select name="alert_if">
                            <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">
                            <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
                    }
                    ?>
                </div>
                <div class="row">
                    <label for="block_if">Block If</label>
                    <?php
                    if ($question->question_type === 'yes_no' || $question->question_type === 'notify_gp') {
                        ?>
                        <select name="block_if">
                            <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">
                            <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
                    }
                    ?>
                </div>
                <div class="row">
                    <label for="okay_if">Okay If</label>
                    <?php
                    if ($question->question_type === 'yes_no' || $question->question_type === 'notify_gp') {
                        ?>
                        <select name="okay_if">
                            <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">
                            <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
                    }
                    ?>
                </div>
                <div class="row">
                    <label for="cant_proceed_if">Can't Proceed If</label>
                    <?php
                    if ($question->question_type === 'yes_no' || $question->question_type === 'notify_gp') {
                        ?>
                        <select name="cant_proceed_if">
                            <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">
                            <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
                    }
                    ?>
                </div>
                <?php
            }
            ?>
            <div class="row">
                <label for="is_required">Show if</label>
                <select name="show_if_question" class="showIfQuestion"
                        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>
                <select name="show_if_answer"
                        id="show_if_variation-<?= $question->id; ?>">
                    <?php
                    if (!empty($question->show_if_question)) {
                        $variations_question = Question::query()->find($question->show_if_question);
                        if ($variations_question->question_type === 'yes_no' || $variations_question->question_type === 'notify_gp') {
                            $variations = ['Yes', 'No'];
                        } else {
                            $variations = json_decode((string)$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>

            <div class="row" id="answer_expires_after_days_row">
                <label for="">Answer expires after</label>
                <input name="answer_expires_after_days" value="<?= $question->answer_expires_after_days ?>" type="number" />
                <div class="defaultValue">
                    <span>number of days (0 = never)</span>
                </div>
            </div>

        </fieldset>
        <fieldset>
            <div class="save-button">
                <input type="hidden" name="form_id" value="<?= $_REQUEST['id']; ?>"/>
                <input type="hidden" name="action" value="save"/>
                <input type="submit" name="save" value="Save"/>
                <input type="submit" name="save_and_back" class="saveAndAdd" value="Save &amp; Back"/>
                <input type="submit" name="save_and_add" class="saveAndAdd" value="Save &amp; Add Next"/>
                <a href="/shop/admin/assessment/manage.recommended.php?<?= http_build_query($_GET) ?>"
                   class="button btn"
                >
                    Manage Recommended
                </a>
                <a href="/shop/admin/assessment/manage.form.php?id=<?= $_REQUEST['id']; ?>"
                   class="button btn btn-grey saveAndAdd"
                >
                    Cancel
                </a>
            </div>
        </fieldset>
    </form>

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