<?php
/**
 * Mageplaza
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Mageplaza.com license that is
 * available through the world-wide-web at this URL:
 * https://www.mageplaza.com/LICENSE.txt
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade this extension to newer
 * version in the future.
 *
 * @category    Mageplaza
 * @package     Mageplaza_Osc
 * @copyright   Copyright (c) Mageplaza (https://www.mageplaza.com/)
 * @license     https://www.mageplaza.com/LICENSE.txt
 */

/** @var \Mageplaza\Osc\Block\Survey $block */
/** @var \Magento\Framework\Escaper $escaper */

if ($block->isEnableSurvey() && !empty($block->getSurveyQuestion()) && count($block->getAllSurveyAnswer()) > 0):
    $surveyAnswers     = $block->getAllSurveyAnswer();
    $allowCustomOption = $block->isAllowCustomerAddOtherOption();
    $saveUrl           = $block->getUrl('onestepcheckout/survey/save/');
    ?>
    <div id="osc-survey"
         x-data="oscSurvey()"
         class="my-6 p-4 bg-white border border-gray-200 rounded-lg shadow-sm">
        <div x-show="message.text"
             x-transition:enter="transition ease-out duration-300"
             x-transition:enter-start="opacity-0 transform -translate-y-2"
             x-transition:enter-end="opacity-100 transform translate-y-0"
             :class="{
             'bg-green-100 border-green-400 text-green-700': message.type === 'success',
             'bg-red-100 border-red-400 text-red-700': message.type === 'error',
             'bg-yellow-100 border-yellow-400 text-yellow-700': message.type === 'notice'
         }"
             class="px-4 py-3 rounded mb-4 border"
             x-text="message.text">
        </div>
        <div x-show="!isSubmitted" x-transition class="survey-content">
            <div class="mb-4">
                <strong class="text-gray-700"><?= $escaper->escapeHtml(__('Question')) ?>: </strong>
                <span class="text-gray-600"><?= $escaper->escapeHtml($block->getSurveyQuestion()) ?></span>
            </div>
            <div class="space-y-3">
                <?php foreach ($surveyAnswers as $option): ?>
                    <label class="flex items-center p-3 border border-gray-200 rounded-md cursor-pointer hover:bg-gray-50 transition-colors duration-200">
                        <input type="checkbox"
                               value="<?= $escaper->escapeHtmlAttr($option['value']) ?>"
                               x-model="selectedAnswers"
                               class="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500">
                        <span class="ml-3 text-gray-700"><?= $escaper->escapeHtml($option['value']) ?></span>
                    </label>
                <?php endforeach; ?>
                <?php if ($allowCustomOption): ?>
                    <div x-show="!customAnswer.added" class="mt-3">
                        <label for="osc-custom-answer"
                               class="sr-only"><?= $escaper->escapeHtml(__('Add your own answer')) ?></label>
                        <div class="flex items-center gap-2">
                            <input type="text"
                                   id="osc-custom-answer"
                                   x-model="customAnswer.text"
                                   @keydown.enter.prevent="addCustomAnswer()"
                                   @blur="addCustomAnswer()"
                                   placeholder="<?= $escaper->escapeHtmlAttr(__('Add an option...')) ?>"
                                   class="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            <button type="button"
                                    @click="addCustomAnswer()"
                                    class="px-4 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 transition-colors duration-200">
                                <?= $escaper->escapeHtml(__('Add')) ?>
                            </button>
                        </div>
                    </div>
                    <div x-show="customAnswer.added" x-transition
                         class="flex items-center justify-between p-3 border border-green-200 bg-green-50 rounded-md">
                        <label class="flex items-center cursor-pointer">
                            <input type="checkbox"
                                   :value="customAnswer.text"
                                   x-model="selectedAnswers"
                                   checked
                                   class="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500">
                            <span class="ml-3 text-gray-700" x-text="customAnswer.text"></span>
                        </label>
                        <button type="button"
                                @click="removeCustomAnswer()"
                                class="ml-2 w-6 h-6 flex items-center justify-center bg-gray-200 hover:bg-red-500 hover:text-white text-gray-600 rounded transition-colors duration-200"
                                title="<?= $escaper->escapeHtmlAttr(__('Remove')) ?>">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20"
                                 fill="currentColor">
                                <path fill-rule="evenodd"
                                      d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
                                      clip-rule="evenodd"/>
                            </svg>
                        </button>
                    </div>
                <?php endif; ?>
            </div>
            <div class="mt-6 flex justify-end">
                <button type="button"
                        @click="submitAnswers()"
                        :disabled="isLoading || selectedAnswers.length === 0"
                        :class="{'opacity-50 cursor-not-allowed': isLoading || selectedAnswers.length === 0}"
                        class="px-6 py-2 bg-blue-600 text-white font-medium rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors duration-200 flex items-center">
                    <svg x-show="isLoading" class="animate-spin -ml-1 mr-2 h-4 w-4 text-white"
                         xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor"
                                stroke-width="4"></circle>
                        <path class="opacity-75" fill="currentColor"
                              d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    <span x-text="isLoading ? '<?= $escaper->escapeJs(__('Submitting...')) ?>' : '<?= $escaper->escapeJs(__('Submit Answers')) ?>'"></span>
                </button>
            </div>
        </div>
    </div>

    <script>
        function oscSurvey () {
            return {
                selectedAnswers: [],
                customAnswer: {
                    text: '',
                    added: false
                },
                message: {
                    type: '',
                    text: ''
                },
                isLoading: false,
                isSubmitted: false,
                saveUrl: '<?= $escaper->escapeJs($saveUrl) ?>',

                addCustomAnswer () {
                    if (this.customAnswer.text.trim().length > 0) {
                        this.customAnswer.added = true;
                        if (!this.selectedAnswers.includes(this.customAnswer.text)) {
                            this.selectedAnswers.push(this.customAnswer.text);
                        }
                    }
                },

                removeCustomAnswer () {
                    const index = this.selectedAnswers.indexOf(this.customAnswer.text);
                    if (index > -1) {
                        this.selectedAnswers.splice(index, 1);
                    }
                    this.customAnswer.text  = '';
                    this.customAnswer.added = false;
                },

                showMessage (type, text) {
                    this.message.type = type;
                    this.message.text = text;
                },

                async submitAnswers () {
                    if (this.selectedAnswers.length === 0) {
                        this.showMessage('notice', '<?= $escaper->escapeJs(__('You need to choose at least one answer.')) ?>');
                        return;
                    }

                    this.isLoading = true;

                    try {
                        const formKey  = typeof FORM_KEY !== 'undefined' ? FORM_KEY : '';
                        const formData = new URLSearchParams();
                        formData.append('form_key', formKey);
                        this.selectedAnswers.forEach(answer => {
                            formData.append('answerChecked[]', answer);
                        });

                        const response = await fetch(this.saveUrl, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded',
                                'X-Requested-With': 'XMLHttpRequest'
                            },
                            body: formData
                        });

                        const data = await response.json();

                        if (data.status === 'success') {
                            this.isSubmitted = true;
                            this.showMessage('success', data.message || '<?= $escaper->escapeJs(__('Thank you for your feedback!')) ?>');
                        } else {
                            this.showMessage('error', data.message || '<?= $escaper->escapeJs(__('Something went wrong. Please try again.')) ?>');
                        }
                    } catch (error) {
                        console.error('Survey submission error:', error);
                        this.showMessage('error', '<?= $escaper->escapeJs(__('Something went wrong. Please try again.')) ?>');
                    } finally {
                        this.isLoading = false;
                    }
                }
            };
        }
    </script>
<?php endif; ?>

