<?php
/**
 * templates
 * @package EMLOG
 * @link https://www.emlog.net
 */

/**
 * @var string $action
 * @var object $CACHE
 */

require_once 'globals.php';

$Template_Model = new Template_Model();

if ($action === '') {
    $nonce_template = Option::get('nonce_templet');
    $nonce_template_data = @file(TPLS_PATH . $nonce_template . '/header.php');

    $templates = $Template_Model->getTemplates();



    $br = '<a href="./">控制台</a><a href="./template.php">外观设置</a><a><cite>模板主题</cite></a>';

    include View::getAdmView('header');
    require_once View::getAdmView('templates/default/template/index');
    include View::getAdmView('footer');
    View::output();
}

if($action == 'index'){
    $list = $Template_Model->getTemplates();

    $nonce_template = Option::get('nonce_templet');
    $nonce_template_data = @file(TPLS_PATH . $nonce_template . '/header.php');

    $db = Database::getInstance();
    $db_prefix = DB_PREFIX;
    $domain = getDomain();
    $sql = "select * from {$db_prefix}authorization where domain='{$domain}'";
    $res = $db->once_fetch_array($sql);
    $emkey =  empty($res) ? false : $res['emkey'];

    $post_data = [
        'emkey' => $emkey,
        'apps'  => [],
    ];

    foreach($list as $key => $val){
        if($nonce_template == $val['tplfile']){
            $list[$key]['switch'] = 'y';
        }else{
            $list[$key]['switch'] = 'n';
        }
        $post_data['apps'][] = [
            'name' => $val['tplfile'],
            'version' => $val['version']
        ];
    }
    $post_data['apps'] = json_encode($post_data['apps']);


    $emcurl = new EmCurl();
    $emcurl->setPost($post_data);
    $emcurl->request(SERVICE_HOST . '/api/template/upgrade');
    $retStatus = $emcurl->getHttpStatus();
    $update_data = [];
    if ($retStatus !== MSGCODE_SUCCESS) {
//        Output::error('请求更新失败，可能是网络问题');
    }
    $response = $emcurl->getRespone();
    $ret = json_decode($response, 1);
    if (empty($ret)) {
//        Output::error('请求更新失败，可能是网络问题');
    }
    if ($ret['code'] === MSGCODE_EMKEY_INVALID) {
//        Output::error('未注册的pro版本');
    }
    if($ret['code'] == 200){
        $update_data = $ret['data'];
    }
//    d($ret);die;

    foreach($list as $key => $val){
        $list[$key]['update'] = 'n';
        foreach($update_data as $k => $v){
            if($v['name'] == $val['tplfile']){
                $list[$key]['update'] = 'y';
            }
        }
    }


    output::data($list, count($list));
}

if ($action === 'use') {
    LoginAuth::checkToken();

    $tplName = Input::postStrVar('tpl');

    Option::updateOption('nonce_templet', $tplName);
    $CACHE->updateCache('options');
    $Template_Model->initCallback($tplName);

    output::ok();
}

if ($action === 'del') {
    LoginAuth::checkToken();

    $tpls = Input::postStrVar('ids');
    $tpls = explode(',', $tpls);

    foreach($tpls as $val){
        $Template_Model->rmCallback($val);
        $path = preg_replace("/^([\w-]+)$/i", "$1", $val);
        emDeleteFile(TPLS_PATH . $path);
    }

    output::ok();
}

if($action == 'setting_page'){
    $tpl = Input::getStrVar('tpl');
    include View::getAdmView('open_head');
    require_once "../content/templates/$tpl/setting.php";
    plugin_setting_view();
    include View::getAdmView('open_foot');
}
if($action == 'setting_ajax'){
    $tpl = Input::getStrVar('tpl');

    require_once "../content/templates/$tpl/setting.php";

    plugin_setting($tpl);


}

if ($action === 'install') {
    include View::getAdmView('header');
    require_once View::getAdmView('template_install');
    include View::getAdmView('footer');
    View::output();
}

if ($action === 'upload_zip') {
    if (defined('APP_UPLOAD_FORBID') && APP_UPLOAD_FORBID === true) {
        emMsg('系统禁止上传安装应用');
    }
    LoginAuth::checkToken();
    $zipfile = isset($_FILES['tplzip']) ? $_FILES['tplzip'] : '';

    if ($zipfile['error'] == 4) {
        emDirect("./template.php?error_d=1");
    }
    if ($zipfile['error'] == 1) {
        emDirect("./template.php?error_f=1");
    }
    if (!$zipfile || $zipfile['error'] > 0 || empty($zipfile['tmp_name'])) {
        emMsg('模板上传失败， 错误码：' . $zipfile['error']);
    }
    if (getFileSuffix($zipfile['name']) != 'zip') {
        emDirect("./template.php?error_a=1");
    }

    $ret = emUnZip($zipfile['tmp_name'], '../content/templates/', 'tpl');
    switch ($ret) {
        case 0:
            emDirect("./template.php?activate_install=1");
            break;
        case -2:
            emDirect("./template.php?error_e=1");
            break;
        case 1:
        case 2:
            emDirect("./template.php?error_b=1");
            break;
        case 3:
            emDirect("./template.php?error_c=1");
            break;
    }
}

if ($action === 'check_update') {
    $templates = isset($_POST['templates']) ? $_POST['templates'] : [];

    $db = Database::getInstance();
    $db_prefix = DB_PREFIX;
    $domain = getDomain();
    $sql = "select * from {$db_prefix}authorization where domain='{$domain}'";
    $res = $db->once_fetch_array($sql);
    $emkey =  empty($res) ? false : $res['emkey'];

    $emcurl = new EmCurl();
    $post_data = [
        'emkey' => $emkey,
        'apps'  => json_encode($templates),
    ];
    $emcurl->setPost($post_data);
    $emcurl->request(SERVICE_HOST . '/api/template/upgrade');
    $retStatus = $emcurl->getHttpStatus();
    if ($retStatus !== MSGCODE_SUCCESS) {
        Output::error('请求更新失败，可能是网络问题');
    }
    $response = $emcurl->getRespone();
    $ret = json_decode($response, 1);
    if (empty($ret)) {
        Output::error('请求更新失败，可能是网络问题');
    }
    if ($ret['code'] === MSGCODE_EMKEY_INVALID) {
        Output::error('未注册的pro版本');
    }

    Output::ok($ret['data']);
}

if ($action === 'upgrade') {
    $alias = isset($_GET['alias']) ? trim($_GET['alias']) : '';

    $alias = Input::postStrVar('alias');

    if (!Register::isRegLocal()) {
        output::error('未授权版本无法更新');
    }


    $temp_file = emFetchFile(SERVICE_HOST . '/api/template/down?plugin=' . $alias);
//    echo SERVICE_HOST . '/api/template/down?plugin=' . $alias;die;
    if (!$temp_file) {
        emDirect("./template.php?error_h=1");
    }
    $unzip_path = '../content/templates/';
    $ret = emUnZip($temp_file, $unzip_path, 'tpl');
    @unlink($temp_file);
    switch ($ret) {
        case 0:
            $Template_Model->upCallback($alias);
            output::ok();
            break;
        case 1:
        case 2:
        output::error('更新失败');
            break;
        case 3:
            output::error('更新失败');
            break;
        default:
            output::error('更新失败');
    }
}
