<?php
/** 
 * @package     VikRestaurants
 * @subpackage  core
 * @author      E4J s.r.l.
 * @copyright   Copyright (C) 2023 E4J s.r.l. All Rights Reserved.
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 * @link        https://vikwp.com
 */

// No direct access
defined('ABSPATH') or die('No script kiddies please!');

?>

<!-- INSTRUCTIONS -->

<div class="cron-instructions">

    <p>To properly configure a cron job you have to follow the instructions below:</p>
        
    <ol>
        <li>Create at least a cron job by clicking the <b>See Cron Jobs List</b> button under the settings tab.</li>
        <li>Pick the right cron job from the apposite dropdown and copy the generated URL.</li>
        <li>Visit the page to schedule a <a href="index.php?option=com_scheduler" target="_blank">new task <i class="fas fa-external-link-square-alt"></i></a> and click the "New" button.</li>
        <li>Pick the <b>GET Request</b> task type from the grid.</li>
        <li>Set up the task by pasting the copied URL within the <b>Request URL</b> field.</li>
        <li>Save &amp; close and hit the button to run a test.</li>
        <li>Go back to the cron jobs list and make sure the process has been properly executed.</li>
    </ol>

</div>

<!-- CRON JOB FILE - Select -->

<?php 
$jobs = JHtml::fetch('vrehtml.admin.cronjobs', $blank = '', $group = true);

// make sure the list contains more than 1 element because the placeholder is always included
if (count($jobs) > 1)
{
    echo $this->formFactory->createField()
        ->type('groupedlist')
        ->label('Cron Job')
        ->id('vre-cron-select')
        ->options($jobs);
}
else
{
    echo $this->formFactory->createField()
        ->type('alert')
        ->style('warning')
        ->hiddenLabel(true)
        ->text(JText::translate('VRECONFIGCRONMISSING'));
}

$cron_url_map = [];

// generate secure key hash
$securekey = md5($this->params['cron_secure_key']);

$uriHandler = VREFactory::getPlatform()->getUri();

foreach ($jobs as $group => $list)
{
    foreach ($list as $cron)
    {
        if ($cron->value)
        {
            $url = 'index.php?option=com_vikrestaurants&task=cronjob_listener_rq&id_cron=' . $cron->value . '&secure_key=' . $securekey;
            $url = $uriHandler->route($url, false);

            $cron_url_map[$cron->value] = $url;
        }
    }
}
?>

<!-- CRON JOB EXECUTION URL - Text -->

<?php
$copyUrlInput = $this->formFactory->createField()
    ->type('text')
    ->readonly(true)
    ->id('cron-url-exec')
    ->hidden(true);

$copyUrlButton = $this->formFactory->createField()
    ->type('button')
    ->id('cron-url-copy')
    ->text(JText::translate('VRECOPY'))
    ->hidden(true);

echo $this->formFactory->createField()
    ->control([
        'class' => 'cron-file-child',
        'visible' => false,
    ])
    ->render(function($data, $input) use ($copyUrlInput, $copyUrlButton) {
        ?>
        <div class="multi-field first-flex">
            <?php echo $copyUrlInput; ?>
            <?php echo $copyUrlButton; ?>
        </div>
        <?php
    });
?>

<?php
JText::script('VRECOPIED');
?>

<script>
    (function($, w) {
        'use strict';

        const cronUrlMap = <?php echo json_encode($cron_url_map); ?>;

        $(function() {
            // exclude download select from observer
            w.configObserver.exclude('#vre-cron-select');
            
            $('#vre-cron-select').select2({
                placeholder: '--',
                allowClear: false,
                width: 300,
            }).on('change', function() {
                let id = $(this).select2('val');

                if (cronUrlMap.hasOwnProperty(id)) {
                    $('#cron-url-exec').val(cronUrlMap[id]);
                    $('.cron-file-child').show();
                } else {
                    $('.cron-file-child').hide();
                    $('#cron-url-exec').val('');
                }
            });

            $('#cron-url-copy').on('click', () => {
                copyToClipboard($('#cron-url-exec')[0]).then(() => {
                    VREToast.enqueue(new VREToastMessageOS({
                        body: Joomla.JText._('VRECOPIED'),
                        status: VREToast.SUCCESS_STATUS,
                        delay: 2500,
                    }));
                });
            });
        });
    })(jQuery, window);
</script>