<?php

namespace Autogedal\Extend\Block\Adminhtml\Answer;

use Magento\Backend\Block\Widget\Form\Container;

class Add extends Container
{
    /**
     * Initialize add answer
     *
     * @return void
     */
    protected function _construct()
    {
        Container::_construct();

        $this->_blockGroup = 'Magediary_ProductQuestion';
        $this->_controller = 'adminhtml_answer';
        $this->_mode = 'add';

        $this->buttonList->update('save', 'label', __('Save Answer'));
        $this->buttonList->update('save', 'id', 'save_button');

        $this->buttonList->update('reset', 'id', 'reset_button');
$this->buttonList->update('back', 'onclick', 'history.back();');
        $this->_formScripts[] = '
            require(["prototype"], function(){
                toggleParentVis("add_answer_form");
                toggleVis("save_button");
                toggleVis("reset_button");
            });
        ';

        // Check if we have a direct question_id
        $questionId = $this->getRequest()->getParam('question_id');

        $this->_formInitScripts[] = '
            require(["jquery","prototype"], function(jQuery){
            window.answer = function() {
                return {
                    questionInfoUrl : null,
                    formHidden : true,
                    directQuestionId : ' . ($questionId ? $questionId : 'null') . ',
                    
                    init: function() {
                        // If we have a direct question ID, load it immediately
                        if (answer.directQuestionId) {
                            answer.questionInfoUrl = "' . $this->getUrl('magediary_productquestion/answer/jsonQuestionInfo') . 'question_id/" + answer.directQuestionId;
                            answer.loadProductData();
                            answer.showForm();
                            answer.formHidden = false;
                        }
                    },
                    
                    gridRowClick : function(data, click) {
                        if(Event.findElement(click,\'TR\').title){
                            answer.questionInfoUrl = Event.findElement(click,\'TR\').title;
                            answer.loadProductData();
                            answer.showForm();
                            answer.formHidden = false;
                        }
                    },
                    
                    loadProductData : function() {
                        jQuery.ajax({
                            type: "POST",
                            url: answer.questionInfoUrl,
                            data: {
                                form_key: FORM_KEY
                            },
                            showLoader: true,
                            success: answer.reqSuccess,
                            error: answer.reqFailure
                        });
                    },
                    
                    showForm : function() {
                        toggleParentVis("add_answer_form");
                        // Only hide grid if it exists (for direct question access, grid might not be rendered)
                        if ($("questionGrid")) {
                            toggleVis("questionGrid");
                        }
                        toggleVis("save_button");
                        toggleVis("reset_button");
                    },

                    reqSuccess :function(response) {
                        if( response.error ) {
                            alert(response.message);
                        } else if( response.id ){
                            $("question_id").value = response.id;

                            $("question_detail").innerHTML = \'<a href="' .
            $this->getUrl(
                'magediary_productquestion/question/edit'
            ) .
            'id/\' + response.question_id + \'" target="_blank">\' + response.detail + \'</a>\';
                        } else if ( response.message ) {
                            alert(response.message);
                        }
                    },
                    
                    reqFailure: function() {
                        alert("Failed to load question data");
                    }
                }
            }();
            
            document.observe("dom:loaded", function() {
                answer.init();
            });
            
            });
        //]]>
        ';
    }

    /**
     * Get question ID from request (for direct question access)
     *
     * @return int|null
     */
    public function getQuestionId()
    {
        $questionId = $this->getData('question_id');
        
        if (!$questionId) {
            $questionId = $this->getRequest()->getParam('question_id');
        }
        
        return $questionId;
    }

    /**
     * Check if we have a direct question ID
     *
     * @return bool
     */
    public function hasDirectQuestionId()
    {
        return (bool) $this->getQuestionId();
    }

    /**
     * Get add new answer header text
     *
     * @return \Magento\Framework\Phrase
     */
    public function getHeaderText()
    {
        return __('Add Answer');
    }
}
