<?php
/**
 * @package    Proxim
 * @author     Davison Pro <davis@davisonpro.dev | https://davisonpro.dev>
 * @copyright  2019 Proxim
 * @version    1.5.0
 * @since      File available since Release 1.0.0
 * 
 ____  ____   __  _  _  __  _  _ 
(  _ \(  _ \ /  \( \/ )(  )( \/ )
 ) __/ )   /(  O ))  (  )( / \/ \
(__)  (__\_) \__/(_/\_)(__)\_)(_/
*/

require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'prox-bootstrap.php';

use Proxim\Application;
use Proxim\Configuration;
use Proxim\Util\DateUtils;
use \VisualAppeal\AutoUpdate;

$update = new AutoUpdate(
    PROX_DIR_ROOT . 'updater' . PROX_DS . 'temp', 
    PROX_DIR_ROOT
);

// remove assets
$app->unregisterStylesheet('main-css');
$app->unregisterStylesheet('components-css');
$app->unregisterStylesheet('app-css');
$app->unregisterJavascript('components-js');
$app->unregisterJavascript('app-js');

$update->setCurrentVersion( Configuration::get('PROX_VERSION') );
$update->setUpdateUrl( PROX_UPDATES_URL );
$update->addLogHandler(new Monolog\Handler\StreamHandler(PROX_DIR_ROOT . 'updater' . PROX_DS . 'update.log'));

if ($update->checkUpdate() === false) {
    $app->setVars([
        'page' => [
            'title' => "Update unsuccessful"
        ]
    ]);
    $smarty->assign('update_message', 'Sorry, there was a problem updating Proxim. No changes were made.');
    $app->setTemplate('updates/error');
    $app->display(); 
}

Configuration::updateValue('PROX_NEW_VERSION', false);

if ($update->newVersionAvailable()) {
    $result = $update->update(false);
    if ($result === true) {
        $new_version = $update->getLatestVersion();
        Configuration::updateValue('PROX_VERSION', $new_version);
        Configuration::updateValue('PROX_LAST_UPDATE', DateUtils::now());

        $smarty->assign('system_version', $new_version);

        $app->setVars([
            'page' => [
                'title' => "Notify Update"
            ]
        ]);
        $app->setTemplate('updates/success');
        $app->display(); 
    } else {
        $app->setVars([
            'page' => [
                'title' => "Update unsuccessful"
            ]
        ]);
        $smarty->assign('update_message', 'Sorry, there was a problem updating Proxim. No changes were made.');
        $app->setTemplate('updates/error');
        $app->display(); 
    }

} else {
    $app->setVars([
        'page' => [
            'title' => "Notify Update"
        ]
    ]);

    $smarty->assign('update_message', sprintf('You have the latest version of Proxim: %s. No changes were made.', Configuration::get('PROX_VERSION')) );
    $app->setTemplate('updates/error');
    $app->display(); 
}