<?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,
]);

if ($_REQUEST['action'] === 'delete' && is_numeric($_REQUEST['delete_id'])) {
    $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') {
        $labels = $_POST['variations_labels'] ?? [];
        $existing_images = $_POST['variations_existing_images'] ?? [];
        $delete_images = $_POST['variations_delete_images'] ?? [];
        $option_folders = $image_folders['assessment_option_images'];

        $new_variations = [];
        foreach ($labels as $index => $label) {
            $label = trim((string) $label);
            if ($label === '') {
                continue;
            }

            $image = $existing_images[$index] ?? null;

            if (!empty($delete_images[$index]) && !empty($image)) {
                foreach ($option_folders as $folder) {
                    @unlink(SITE_PATH . '/' . $folder['path'] . '/' . $image);
                }
                $image = null;
            }

            $file_field = 'variations_image_file_' . $index;
            if (!empty($_FILES[$file_field]['size'])) {
                $file_data = upload_image($file_field, $option_folders);
                if ($file_data === false) {
                    $errors[] = 'Option "' . $label . '": image upload failed. Allowed types: JPG, JPEG, PNG, GIF.';
                } elseif (!empty($file_data['error'])) {
                    $errors[] = 'Option "' . $label . '": ' . $file_data['error'];
                } elseif (!empty($file_data['name'])) {
                    if (!empty($image)) {
                        foreach ($option_folders as $folder) {
                            @unlink(SITE_PATH . '/' . $folder['path'] . '/' . $image);
                        }
                    }
                    $image = $file_data['name'];
                }
            }

            $new_variations[] = [
                'label' => clean_page($label),
                'image' => $image,
            ];
        }
        $request['variations'] = json_encode($new_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'] ?? '';

    if (count($errors) === 0) {
        $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 = Question::normalizeVariations($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);
$option_thumb_path = $image_folders['assessment_option_images']['thumb']['path'];

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" enctype="multipart/form-data" 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</label>
                <div class="variationsRepeater" id="variationsRepeater">
                    <?php foreach ($variations as $i => $variation) { ?>
                        <div class="variationsRepeater__row" data-index="<?= $i ?>">
                            <div class="variationsRepeater__label">
                                <input type="text"
                                       name="variations_labels[<?= $i ?>]"
                                       value="<?= clean_page($variation['label']) ?>"
                                       placeholder="Option label"/>
                            </div>
                            <div class="variationsRepeater__image">
                                <?php if (!empty($variation['image'])) { ?>
                                    <img src="/<?= $option_thumb_path ?>/<?= clean_page($variation['image']) ?>"
                                         alt=""
                                         class="variationsRepeater__thumb"/>
                                    <input type="hidden"
                                           name="variations_existing_images[<?= $i ?>]"
                                           value="<?= clean_page($variation['image']) ?>"/>
                                    <label class="variationsRepeater__deleteLabel">
                                        <input type="checkbox" name="variations_delete_images[<?= $i ?>]" value="1"/>
                                        Delete image
                                    </label>
                                <?php } ?>
                                <input type="file"
                                       name="variations_image_file_<?= $i ?>"
                                       accept="image/*"/>
                            </div>
                            <button type="button" class="variationsRepeater__remove" aria-label="Remove option">&times;</button>
                        </div>
                    <?php } ?>
                </div>
                <button type="button" class="btn" id="variationsRepeaterAdd">Add option</button>

                <template id="variationsRepeaterTemplate">
                    <div class="variationsRepeater__row" data-index="__INDEX__">
                        <div class="variationsRepeater__label">
                            <input type="text" name="variations_labels[__INDEX__]" placeholder="Option label"/>
                        </div>
                        <div class="variationsRepeater__image">
                            <input type="file" name="variations_image_file___INDEX__" accept="image/*"/>
                        </div>
                        <button type="button" class="variationsRepeater__remove" aria-label="Remove option">&times;</button>
                    </div>
                </template>
            </div>
            <div class="row" id="variations_clearall_row">
                <label for="">Clear-all answer</label>
                <select name="clearall_answer">
                    <option value="">--- select ---</option>
                    <?php foreach ($variations as $variation) { ?>
                        <option value="<?= clean_page($variation['label']) ?>"
                                <?= $variation['label'] == $question->clearall_answer ? 'selected' : '' ?>>
                            <?= clean_page($variation['label']) ?>
                        </option>
                    <?php } ?>
                </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) {
                                $label = $variation['label'];
                                $checked = in_array($label, $alert_ifs, true) ? 'checked' : '';
                                $safe_label = clean_page($label);
                                echo "<input type='checkbox' name='alert_if[]' value=\"{$safe_label}\" id='variation-a-{$i}' $checked> <label for='variation-a-{$i}'>{$safe_label}</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) {
                                $label = $variation['label'];
                                $checked = in_array($label, $block_ifs, true) ? 'checked' : '';
                                $safe_label = clean_page($label);
                                echo "<input type='checkbox' name='block_if[]' value=\"{$safe_label}\" id='variation-b-{$i}' $checked> <label for='variation-b-{$i}'>{$safe_label}</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) {
                                $label = $variation['label'];
                                $checked = in_array($label, $okay_ifs, true) ? 'checked' : '';
                                $safe_label = clean_page($label);
                                echo "<input type='checkbox' name='okay_if[]' value=\"{$safe_label}\" id='variation-o-{$i}' $checked> <label for='variation-o-{$i}'>{$safe_label}</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) {
                                $label = $variation['label'];
                                $checked = in_array($label, $cant_proceed_ifs, true) ? 'checked' : '';
                                $safe_label = clean_page($label);
                                echo "<input type='checkbox' name='cant_proceed_if[]' value=\"{$safe_label}\" id='variation-c-{$i}' $checked> <label for='variation-c-{$i}'>{$safe_label}</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') {
                            $other_variations = ['Yes', 'No'];
                        } else {
                            $other_variations = array_column(
                                Question::normalizeVariations($variations_question->variations),
                                'label'
                            );
                        }
                        if (!empty($other_variations)) {
                            foreach ($other_variations as $variation) {
                                // List all the variations of the question
                                $selected = $question->show_if_answer === $variation ? 'selected' : '';
                                $safe_variation = clean_page($variation);
                                echo "<option value=\"{$safe_variation}\" {$selected}>{$safe_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';
