<?php

/*
 * @component UserPoints
 * @copyright Copyright (C) 2015-2022 Bernard Gilly - Adrien Roussel - Martin Brampton
 * @license : GNU/GPL
 * @Website : https://remository.com
 */

namespace BlackSheepResearch\Component\UserPoints\Administrator\Controllers;

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();

use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\CMS\Session\Session;
use Joomla\CMS\Component\ComponentHelper;
use BlackSheepResearch\Component\UserPoints\Administrator\AdminController;
use BlackSheepResearch\Component\UserPoints\Site\Problems\RaffleData;
use BlackSheepResearch\Component\UserPoints\Site\Problems\RaffleInscription;
use BlackSheepResearch\Component\UserPoints\Site\Problems\Rule;

class RaffleControl extends AdminController {

    public function raffle() {
        // Get the pagination request variables
        list($this->viewdata['limitstart'], $this->viewdata['limit']) = RaffleData::getLimitsFromRequest();
        $filter_category_id = $this->app->input->get('filter_category_id', 0, 'int');
        $this->viewdata['total'] = $filter_category_id ? RaffleData::countByFieldvalue('category', $filter_category_id) : RaffleData::countAll();
        $this->viewdata['raffle'] = RaffleData::getRangeWithInscriptions($this->viewdata['limitstart'], $this->viewdata['limit'], $filter_category_id);
        foreach ($this->viewdata['raffle'] as $raffle) {
            $raffle->drawRaffleIfDue();
        }
        // message if rule disabled
        if (!Rule::getIDFromRuleNamePublished('sysplgup_raffle')) {
            $this->app->enqueueMessage(Text::_('AUP_THIS_RULE_IS_DISABLED'));
        }
        $lists['filter_category_id'] = $filter_category_id;
        $this->viewdata['lists'] = $lists;

        // Display
        $this->getView('RaffleHTML', 'html')->displaylist();
    }

    private function getRaffleFromInputArray() {
        $cid = $this->getFirstCID();
        if ($cid) {
            return new RaffleData($cid);
        } else {
            return new RaffleData();
        }
        throw new \Exception(Text::_('AUP_INVALID_SELECTION_FROM_LIST'));
    }

    /**
     * Edit Raffle
     */
    public function editraffle() {
        $raffle = $this->getRaffleFromInputArray();
        $lists['filter_category_id'] = $raffle->category;
        $view = $this->getView('RaffleHTML', 'html');
        $this->viewdata['row'] = $raffle;
        $this->viewdata['lists'] = $lists;
        // Display
        $view->edit_raffle();
    }

    private function doSaveRaffle () : int {
        Session::checkToken() or jexit(Text::_('JINVALID_TOKEN'));
        // initialize variables
        $post = $this->app->input->post->getArray();
        $raffle = new RaffleData($this->app->input->get('id', 0, 'int'));
        $raffle->save($post);
        return $raffle->id;
    }

    /**
     * Save Raffle
     */
    public function saveraffle() {
        $this->doSaveRaffle();
        $msg = Text::_('AUP_DETAILSSAVED');
        $this->redirect('index.php?option=com_userpoints&task=raffle', $msg);
    }

    public function applyraffle() {
        $id = $this->doSaveRaffle();
        $msg = Text::_('AUP_DETAILSSAVED');
        $this->redirect('index.php?option=com_userpoints&task=editraffle&cid[]=' . $id, $msg);
    }

    /**
     * Delete Raffle
     */
    public function deleteraffle() {
        $cids = $this->getArrayCID();
        if (count($cids)) {
            RaffleData::deleteMany($cids);
            RaffleInscription::deleteMany($cids, 'raffleid');
        }
        $this->redirect('index.php?option=com_userpoints&task=raffle');
    }

    public function cancelraffle() {
        $this->redirect("index.php?option=com_userpoints&task=raffle");
    }

    public function makeraffle() {
        $raffle = new RaffleData($this->app->input->get('id', 0, 'int'));
        // load external plugins
        PluginHelper::importPlugin('userpoints');
        $this->app->triggerEvent('onBeforeMakeRaffleUserPoints', array(&$raffle, RaffleData::datetimeSQL()));
        if (!$raffle->drawRaffle()) {
            $msg = Text::_('AUP_RAFFLE_NOT_DRAWN_NO_ENTRIES');
            $this->redirect('index.php?option=com_userpoints&task=raffle', $msg);
        }
        $this->app->triggerEvent('onAfterMakeRaffleUserPoints', array(&$this, RaffleData::datetimeSQL()));
        $this->app->redirect("index.php?option=com_userpoints&task=raffle");
    }

    public function exportListUsersRaffle() {
        $_row = RaffleInscription::selectedUsers(Factory::getApplication()->input->get('id', 0, 'int'));

        $fileName = "users_registration_" . uniqid(rand(), true) . ".csv";
        $filepath = JPATH_COMPONENT_ADMINISTRATOR . '/assets/csv/' . $fileName;

        $handler = fopen($filepath, "a");
        fwrite($handler, "#;USER ID;TICKET;NAME;USERNAME\n");
        $j = 0;
        $total = count($_row);

        for ($i = 0; $i < $total; $i++) {
            $j++;
            fwrite($handler, $j . ";" . $_row[$i]->uid . ";" . $_row[$i]->ticket . ";" . $_row[$i]->name . ";" . $_row[$i]->username . ";" . $_row[$i]->email . "\n");
        }

        header("Expires: Mon, 26 Nov 1962 00:00:00 GMT");
        header("Last-Modified: " . gmdate('D,d M Y H:i:s') . ' GMT');
        header("Cache-Control: no-cache, must-revalidate");
        header("Pragma: no-cache");
        header("Content-Type: text/x-comma-separated-values");
        header("Content-Disposition: attachment; filename=$fileName");

        readfile($filepath);

        exit;
    }

    private function Text_($name): string {
        return Text::_($name);
    }

    //----------------------- plg_editor-xtd_raffle integration start -----------------------//

    public function editorInsertRaffle() {
        //$app = Factory::getApplication();
        $doc = Factory::getDocument();
        $lang = Factory::getLanguage();
        $lang->load('plg_editors-xtd_raffle', JPATH_ADMINISTRATOR);

        // build raffles listbox
        $raffles_list = array();
        $raffles = RaffleData::current();
        foreach ($raffles as $raffle) {
            $raffles_list[] = HTMLHelper::_('select.option', $raffle->id, $raffle->description);
        }
        $raffles_listbox = HTMLHelper::_('select.genericlist', $raffles_list, 'id', 'class="inputbox raffle-select" size="10"', 'value', 'text', '');

        // build display modes listbox
        $display_modes = array(
            HTMLHelper::_('select.option', 'ALL', $this->Text_('PLG_RAFFLE_BUTTON_DISPLAY_ALL')),
            HTMLHelper::_('select.option', 'STATUS', $this->Text_('PLG_RAFFLE_BUTTON_DISPLAY_STATUS')),
            HTMLHelper::_('select.option', 'HISTORY', $this->Text_('PLG_RAFFLE_BUTTON_DISPLAY_HISTORY')),
            HTMLHelper::_('select.option', 'BUTTON', $this->Text_('PLG_RAFFLE_BUTTON_DISPLAY_BUTTON')),
            HTMLHelper::_('select.option', 'COUNT', $this->Text_('PLG_RAFFLE_BUTTON_DISPLAY_COUNT'))
        );
        $display_modes_listbox = HTMLHelper::_('select.genericlist', $display_modes, 'display_mode', 'class="inputbox raffle-select"', 'value', 'text', 'ALL');

        $eName = Factory::getApplication()->input->get('e_name', '');
        echo <<<RAFFLE_POPUP
<style>
    #id, #display_mode, .raffle-select {
        width: 100%;
    }
</style>
<script type="text/javascript">
function insertRaffleId() {
    var id = document.getElementById("id").value;
    var displayMode = document.getElementById("display_mode").value;
    var tag;
    if (id > 0) {
        if (displayMode && displayMode !== 'ALL') {
            tag = "{AUP::RAFFLE=" + id + "::" + displayMode + "}";
        } else {
            tag = "{AUP::RAFFLE=" + id + "}";
        }

        if (window.parent.Joomla && window.parent.Joomla.editors && window.parent.Joomla.editors.instances) {
            // Modern Joomla 4.x approach
            window.parent.Joomla.editors.instances['$eName'].replaceSelection(tag);
            window.parent.Joomla.Modal.getCurrent().close();
        } else {
            // Fallback for older methods
            window.parent.jInsertEditorText(tag, '$eName');
            if (window.parent.SqueezeBox) {
                window.parent.SqueezeBox.close();
            }
        }
    }
    return false;
}
</script>
<div class="container-fluid">
    <form id="insertRaffle" class="p-3">
        <div class="row mb-3">
            <div class="col-12">
                <div class="d-flex align-items-center mb-2">
                    <img src="components/com_userpoints/assets/images/up_logo.png" width="48" height="48" class="me-2" alt="Logo"/>
                    <div>
                        <strong>{$this->Text_('PLG_RAFFLE_BUTTON_TITLE')}</strong><br />
                        <span class="small">{$this->Text_('PLG_RAFFLE_BUTTON_TITLE_DESC')}</span>
                    </div>
                </div>
            </div>
        </div>
        <div class="row mb-3">
            <label for="id" class="col-sm-4 col-form-label">
                {$this->Text_('PLG_RAFFLE_BUTTON_ID_TITLE')}
            </label>
            <div class="col-sm-8">
                $raffles_listbox
            </div>
        </div>
        <div class="row mb-3">
            <label for="display_mode" class="col-sm-4 col-form-label">
                {$this->Text_('PLG_RAFFLE_BUTTON_DISPLAY_MODE')}
            </label>
            <div class="col-sm-8">
                $display_modes_listbox
            </div>
        </div>
        <div class="row mb-3">
            <div class="col-12">
                <span class="text-danger">{$this->Text_('PLG_RAFFLE_BUTTON_NOTE')}</span>
            </div>
        </div>
        <hr class="mb-3">
        <div class="row mb-3">
            <div class="col-sm-8 offset-sm-4">
                <button type="button" class="btn btn-primary" onclick="insertRaffleId();return false;">
                    {$this->Text_('PLG_RAFFLE_BUTTON_INSERT')}
                </button>
            </div>
        </div>
        <div class="row">
            <div class="col-12 small">
                {$this->Text_('PLG_RAFFLE_BUTTON_INFO')}
            </div>
        </div>
    </form>
</div>

RAFFLE_POPUP;
    }

    //------------------------ plg_editor-xtd_raffle integration end ------------------------//

    public function editorInsertRaffleBefore() {
        //$app = Factory::getApplication();
        $doc = Factory::getDocument();
        $lang = Factory::getLanguage();
        $lang->load('plg_editors-xtd_raffle', JPATH_ADMINISTRATOR);

        // build raffles listbox
        $raffles_list = array();
        $raffles = RaffleData::current();
        foreach ($raffles as $raffle) {
            $raffles_list[] = HTMLHelper::_('select.option', $raffle->id, $raffle->description);
        }
        $raffles_listbox = HTMLHelper::_('select.genericlist', $raffles_list, 'id', 'class="inputbox" size="10"', 'value', 'text', '');
        $eName = Factory::getApplication()->input->get('e_name', '');
        echo <<<RAFFLE_POPUP

<style>
    #id, .raffle-select {
        width: 50%;
    }
</style>
<script type="text/javascript">
function insertRaffleId() {
    var id = document.getElementById("id").value;
    var tag;
    if (id > 0) {
        tag = "{AUP::RAFFLE=" + id + "}";
        if (window.parent.Joomla && window.parent.Joomla.editors && window.parent.Joomla.editors.instances) {
            // Modern Joomla 4.x approach
            window.parent.Joomla.editors.instances['$eName'].replaceSelection(tag);
            window.parent.Joomla.Modal.getCurrent().close();
        } else {
            // Fallback for older methods
            window.parent.jInsertEditorText(tag, '$eName');
            if (window.parent.SqueezeBox) {
                window.parent.SqueezeBox.close();
            }
        }
    }
    return false;
}
        </script>

<div class="container-fluid">
    <form id="insertRaffle" class="p-3">
        <div class="row mb-3">
            <div class="col-12">
                <div class="d-flex align-items-center mb-2">
                    <img src="components/com_userpoints/assets/images/up_logo.png" width="48" height="48" class="me-2" alt="Logo"/>
                    <div>
                        <strong>{$this->Text_('PLG_RAFFLE_BUTTON_TITLE')}</strong><br />
                        <span class="small">{$this->Text_('PLG_RAFFLE_BUTTON_TITLE_DESC')}</span>
                    </div>
                </div>
            </div>
        </div>

        <div class="row mb-3">
            <label for="id" class="col-sm-4 col-form-label">
                {$this->Text_('PLG_RAFFLE_BUTTON_ID_TITLE')}
            </label>
            <div class="col-sm-8">
                $raffles_listbox
            </div>
        </div>

        <div class="row mb-3">
            <div class="col-12">
                <span class="text-danger">{$this->Text_('PLG_RAFFLE_BUTTON_NOTE')}</span>
            </div>
        </div>

        <hr class="mb-3">

        <div class="row mb-3">
            <div class="col-sm-8 offset-sm-4">
                <button type="button" class="btn btn-primary" onclick="insertRaffleId();return false;">
                    {$this->Text_('PLG_RAFFLE_BUTTON_INSERT')}
                </button>
            </div>
        </div>

        <div class="row">
            <div class="col-12 small">
                {$this->Text_('PLG_RAFFLE_BUTTON_INFO')}
            </div>
        </div>
    </form>
</div>

RAFFLE_POPUP;
    }
}
