<?php

use CCDN\Helpers\DB\SettingsSave;
use CCDN\Helpers\Exception\CCDNRuntimeException;
use CCDN\Helpers\Facade\Cache;
use CCDN\Helpers\Facade\DB\Model;
use CCDN\Helpers\Facade\Http\Request;
use CCDN\Helpers\Facade\Http\Response;
use CCDN\Helpers\Facade\Session\Session;

@ini_set('display_errors', '1');
@error_reporting(E_ALL);

define('DATALIFEENGINE', true);
define('ROOT_DIR', substr(dirname(__FILE__), 0, -12));
define('ENGINE_DIR', ROOT_DIR . '/engine');

$action = filter_input(INPUT_POST, 'action');
$commit_sha = filter_input(INPUT_POST, 'sha');

if ($action !== 'updatefromurl') {
    header("HTTP/1.1 403 Forbidden");
    header('Location: ../../');
    die("Hacking attempt!");
}

require_once(ENGINE_DIR . '/data/config.php');
require_once(ENGINE_DIR . '/inc/CCDN/vendor/autoload.php');

if (!Request::isMethod('POST')) {
    die(Response::make("Hacking attempt!", 405));
}

/**
 * For DLE >= 13.1
 */
if ((float)$config['version_id'] >= 13.1) {
    require_once(ENGINE_DIR . '/classes/plugins.class.php');
    include_once(DLEPlugins::Check(ENGINE_DIR . '/inc/include/functions.inc.php'));

    dle_session();

    if (!Session::csrfVerify(Request::post('csrf'))) {
        die(Response::make("Hacking attempt!", 419));
    }

    $plugin = Model::select("SELECT `id` FROM `" . PREFIX . "_plugins` WHERE `name`='CCDN'");
    if (!$plugin['id']) {
        die(Response::json(['status' => 'error', 'text' => 'Plugin not found!']));
    }

    $_POST['id'] = $plugin['id'];
    $_POST['url'] = "https://github.com/dev-dle/dle-balance/raw/{$commit_sha}/CCDN.zip";
    $_REQUEST['mod'] = "plugins";
    $_SERVER['HTTP_REFERER'] = $config['http_home_url'] . $config['admin_path'] . "?mod=plugins";

    ob_start();
    require_once("controller.php");
    $result = ob_get_clean();

    if ($result === '{"status": "succes"}') {
        Cache::clear();
        $settings = new SettingsSave(['git_commit_sha' => $commit_sha]);
        $settings->saveAll();

        die(Response::json(['status' => 'success', 'plugin_id' => $plugin['id']]));
    }

    die($result);
}

/**
 * For DLE <= 13.0
 */
require_once(ENGINE_DIR . '/classes/mysql.php');
require_once(ENGINE_DIR . '/data/dbconfig.php');
require_once(ENGINE_DIR . '/inc/include/functions.inc.php');

dle_session();

if (!Session::csrfVerify(Request::post('csrf'))) {
    die(Response::make("Hacking attempt!", 419));
}

$is_logged = false;
require_once(ENGINE_DIR . '/modules/sitelogin.php');
if (!$is_logged) $member_id['user_group'] = 5;
if ($is_logged and $member_id['banned'] == "yes") die("User banned");

if ($member_id['user_group'] != 1 or $_REQUEST['user_hash'] == "" or $_REQUEST['user_hash'] != $dle_login_hash) {
    die(Response::json(['status' => 'error', 'text' => 'Ваша пользовательская сессия истекла, перезагрузите страницу в браузере и при необходимости войдите на сайт повторно.']));
}

if (!class_exists(ZipArchive::class)) {
    throw new CCDNRuntimeException('ZipArchive::class not exists');
}

$moduleUlr = @file_get_contents("https://github.com/dev-dle/dle-balance/raw/{$commit_sha}/CCDN_DLE_12.zip");

if ($moduleUlr === false) {
    throw new CCDNRuntimeException('Failed to download archive CCDN.zip');
}

if (@file_put_contents(ENGINE_DIR . '/cache/system/CCDN.zip', $moduleUlr) === false) {
    throw new CCDNRuntimeException('Failed to save archive CCDN.zip');
}

$zip = new ZipArchive;
$open = $zip->open(ENGINE_DIR . '/cache/system/CCDN.zip');
if ($open !== true) {
    throw new CCDNRuntimeException('Failed to open archive file. CCDN.zip. Code: ' . $open);
}

if (!$zip->extractTo(ROOT_DIR)) {
    throw new CCDNRuntimeException('Failed to unzip the archive CCDN.zip');
}

$zip->close();

@unlink(ENGINE_DIR . '/cache/system/CCDN.zip');
@unlink(ROOT_DIR . '/README.txt');
@unlink(ROOT_DIR . '/ccdn.xml');
@unlink(ROOT_DIR . '/ccdn-install.php');

Cache::clear();
$settings = new SettingsSave(['git_commit_sha' => $commit_sha]);
$settings->saveAll();

die(Response::json(['status' => 'success']));
