<?php

use dokuwiki\Extension\AdminPlugin;
use dokuwiki\Form\Form;

/**
 * Popularity Feedback Plugin
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Andreas Gohr <andi@splitbrain.org>
 */
class admin_plugin_popularity extends AdminPlugin
{
    /** @var helper_plugin_popularity */
    protected $helper;
    protected $sentStatus;

    /**
     * admin_plugin_popularity constructor.
     */
    public function __construct()
    {
        $this->helper = $this->loadHelper('popularity', false);
    }

    /**
     * return prompt for admin menu
     * @param $language
     * @return string
     */
    public function getMenuText($language)
    {
        return $this->getLang('name');
    }

    /**
     * return sort order for position in admin menu
     */
    public function getMenuSort()
    {
        return 2000;
    }

    /**
     * Accessible for managers
     */
    public function forAdminOnly()
    {
        return false;
    }


    /**
     * handle user request
     */
    public function handle()
    {
        global $INPUT;

        //Send the data
        if ($INPUT->has('data')) {
            if (!checkSecurityToken()) return;
            $this->sentStatus = $this->helper->sendData($INPUT->str('data'));
            if ($this->sentStatus === '') {
                //Update the last time we sent the data
                touch($this->helper->popularityLastSubmitFile);
            }
            //Deal with the autosubmit option
            $this->enableAutosubmit($INPUT->has('autosubmit'));
        }
    }

    /**
     * Enable or disable autosubmit
     * @param bool $enable If TRUE, it will enable autosubmit. Else, it will disable it.
     */
    protected function enableAutosubmit($enable)
    {
        if ($enable) {
            io_saveFile($this->helper->autosubmitFile, ' ');
        } else {
            @unlink($this->helper->autosubmitFile);
        }
    }

    /**
     * Output HTML form
     */
    public function html()
    {
        global $INPUT;

        if (! $INPUT->has('data')) {
            echo $this->locale_xhtml('intro');
            //If there was an error the last time we tried to autosubmit, warn the user
            if ($this->helper->isAutoSubmitEnabled()) {
                if (file_exists($this->helper->autosubmitErrorFile)) {
                    echo $this->getLang('autosubmitError');
                    echo io_readFile($this->helper->autosubmitErrorFile);
                }
            }
            flush();
            echo $this->buildForm('server');
            //Print the last time the data was sent
            $lastSent = $this->helper->lastSentTime();
            if ($lastSent !== 0) {
                echo $this->getLang('lastSent') . ' ' . datetime_h($lastSent);
            }
        } elseif ($this->sentStatus === '') {
            //If we successfully send the data
            echo $this->locale_xhtml('submitted');
        } else {
            //If we failed to submit the data, try directly with the browser
            echo $this->getLang('submissionFailed') . $this->sentStatus . '<br />';
            echo $this->getLang('submitDirectly');
            echo $this->buildForm('browser', $INPUT->str('data'));
        }
    }


    /**
     * Build the form which presents the data to be sent
     * @param string $submissionMode How is the data supposed to be sent? (may be: 'browser' or 'server')
     * @param string $data   The popularity data, if it has already been computed. NULL otherwise.
     * @return string The form, as an html string
     */
    protected function buildForm($submissionMode, $data = null)
    {
        $url = ($submissionMode === 'browser' ? $this->helper->submitUrl : script());
        if (is_null($data)) {
            $data = $this->helper->gatherAsString();
        }

        // The browser-submission form posts to an external server, so it must not carry
        // our CSRF token; the server-submission form posts back to the wiki and gets one.
        $form = new Form(['action' => $url], $submissionMode === 'browser');
        $form->addFieldsetOpen()->attr('style', 'width: 60%;');

        $form->addTextarea('data')
            ->val($data)
            ->useInput(false)
            ->attrs(['readonly' => 'readonly', 'rows' => 10, 'cols' => 80])
            ->addClass('edit');

        //If we submit via the server, we give the opportunity to subscribe to the autosubmission option
        if ($submissionMode !== 'browser') {
            $autosubmit = $form->addCheckbox('autosubmit', $this->getLang('autosubmit'))->useInput(false);
            if ($this->helper->isAutosubmitEnabled()) {
                $autosubmit->attr('checked', 'checked');
            }
            $form->setHiddenField('do', 'admin');
            $form->setHiddenField('page', 'popularity');
        }

        $form->addButton('submit', $this->getLang('submit'))->attr('type', 'submit');
        $form->addFieldsetClose();

        return $form->toHTML();
    }
}
