<?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
 */

namespace E4J\VikRestaurants\Cron\Jobs;

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

use E4J\VikRestaurants\Cron\CronJob;
use E4J\VikRestaurants\Cron\Status;

/**
 * This cron job can be used to create a backup of the contents created through VikRestaurants.
 * 
 * @since 1.10
 */
class BackupCreator extends CronJob
{
    /**
     * @inheritDoc
     * 
     * @see CronJob
     */
    protected function execute(\JRegistry $args, Status $status)
    {
        // create backup model
        $model = \JModelVRE::getInstance('backup');

        try
        {
            // create back-up
            $archive = $model->save([
                'action' => 'create',
                'prefix' => 'cron_',
            ]);

            if (!$archive)
            {
                // an error occurred while creating the backup archive
                throw new \Exception($model->getError($index = null, $string = true), 500);
            }

            // register response
            $status->setContent("Back-up <span style=\"color:#090;\">created</span> successfully!\n")->appendContent('<b>' . $archive . '</b>');

            // register log metadata
            $status->addMetadata(new \E4J\VikRestaurants\Metadata\Addon\BackupDetails($archive));
        }
        catch (\Exception $error)
        {
            // an error occurred while creating the back-up
            return $status->setStatus(false)->setNotify(true)->setContent($error->getMessage());
        }

        // get list of created archives
        $files = \JFolder::files(dirname($archive), '^cron_backup_', $recursive = false, $fullpath = true);

        // check whether the number of created backups exceeded the maximum threshold
        $diff = count($files) - max([1, abs($args->get('maxbackup'))]);
        
        if ($diff > 0)
        {
            $status->appendContent("\n<hr>");

            // sort the files by ascending creation date
            usort($files, function($a, $b)
            {
                return filemtime($a) - filemtime($b);
            });

            // take the first N archives to delete
            foreach (array_splice($files, 0, $diff) as $file)
            {
                // delete the files
                if (\JFile::delete($file))
                {
                    $status->appendContent("<span style=\"color:#900;\">Deleted</span> old archive: <b>" . basename($file) . '</b>');
                }
            }
        }
    }

    /**
     * @inheritDoc
     * 
     * @see Configurable
     */
    public function getForm()
    {
        return [
            'maxbackup' => [
                'type' => 'number',
                'label' => \JText::translate('VRE_CRONJOB_SETTING_BACKUP_MAX_ARCHIVES'),
                'description' => \JText::translate('VRE_CRONJOB_SETTING_BACKUP_MAX_ARCHIVES_HELP'),
                'required' => true,
                'default' => 5,
                'min' => 1,
                'step' => 1,
            ],
            'seeconfig' => [
                'type' => 'link',
                'href' => 'index.php?option=com_vikrestaurants&view=editconfigapp#backuptype',
                'target' => '_blank',
                'text' => \JText::translate('VRE_CRONJOB_SETTING_BACKUP_SEE_CONFIG_BTN'),
                'description' => \JText::translate('VRE_CRONJOB_SETTING_BACKUP_SEE_CONFIG_BTN_HELP'),
                'hiddenLabel' => true,
            ],
        ];
    }
}
