<?php
/**
 * APP Base API
 * 修改版的BaseAPI，支持通过构造函数传入用户信息
 */

require_once __DIR__ . '/../MPHX/common.php';

class AppBaseAPI {
    protected $user;
    protected $bt_api;
    protected $bt_info;
    protected $site_name;
    protected $DB;
    protected $conf;
    
    /**
     * 构造函数 - 支持传入用户信息
     * @param array $user 用户信息
     * @param object $bt_api 宝塔API对象
     * @param array $bt_info 宝塔服务器信息
     */
    public function __construct($user = null, $bt_api = null, $bt_info = null) {
        global $DB, $conf;
        $this->DB = $DB;
        $this->conf = $conf;
        
        // 如果传入了用户信息，直接使用
        if ($user !== null) {
            $this->user = $user;
        } else {
            // 否则尝试从session获取（兼容前端）
            $this->user = $this->isUserLogin();
            if (!$this->user) {
                $this->error('请先登录');
            }
        }
        
        // 如果传入了宝塔API，直接使用
        if ($bt_api !== null) {
            $this->bt_api = $bt_api;
            $this->bt_info = $bt_info;
        } else {
            // 否则初始化宝塔API
            $this->initBtApi();
        }
        
        // 获取网站名称
        $webid = $this->getWebId();
        $this->site_name = $this->bt_api->GetSiteName($webid);
        
        if (empty($this->site_name)) {
            $this->error('无法获取网站名称，请检查网站ID是否正确');
        }
    }
    
    /**
     * 检查用户登录状态（兼容前端）
     */
    protected function isUserLogin() {
        if (isset($_SESSION['user_id'])) {
            $user_id = intval($_SESSION['user_id']);
            return $this->DB->get_row("SELECT * FROM `zj` WHERE `id`={$user_id}");
        }
        return false;
    }
    
    /**
     * 获取解析地址
     */
    protected function getParseAddress() {
        // 获取用户所在的服务器ID
        $bt_id = isset($this->user['btid']) ? intval($this->user['btid']) : 0;
        
        if ($bt_id > 0) {
            // 查询该服务器的解析域名设置
            $domain_row = $this->DB->get_row("SELECT parse_domain FROM `server_parse_domain` WHERE `bt_id`={$bt_id}");
            if ($domain_row && !empty($domain_row['parse_domain'])) {
                return $domain_row['parse_domain'];
            }
        }
        
        // 如果没有设置，返回服务器IP
        return isset($this->bt_info['ip']) ? $this->bt_info['ip'] : '';
    }
    
    /**
     * 检查是否为系统赠送域名
     */
    protected function isSystemGiftDomain($domain) {
        $domain = strtolower(trim((string)$domain));
        if ($domain === '') return false;
        $gift = strtolower(trim((string)$this->site_name));
        
        if ($gift !== '' && $domain === $gift) {
            return true;
        }
        if ($gift !== '' && $domain === 'www.' . $gift) {
            return true;
        }
        
        // 额外检查：如果域名包含用户名和主域名，也认为是系统赠送的
        $main_domain = isset($this->conf['main_domain']) && !empty($this->conf['main_domain']) ? $this->conf['main_domain'] : 'a116.vip';
        $username = isset($this->user['user']) ? strtolower(trim($this->user['user'])) : '';
        if ($username !== '' && $domain === $username . '.' . $main_domain) {
            return true;
        }
        if ($username !== '' && $domain === 'www.' . $username . '.' . $main_domain) {
            return true;
        }
        
        return false;
    }
    
    protected function initBtApi() {
        $btid = isset($this->user['btid']) ? intval($this->user['btid']) : 0;
        
        if (!$btid) {
            $this->error('宝塔服务器ID不存在');
        }
        
        $this->bt_info = $this->DB->get_row("SELECT * FROM `bt` WHERE `id`={$btid}");
        
        if (!$this->bt_info) {
            $this->error('宝塔服务器不存在');
        }
        
        $this->bt_api = new bt_api();
        
        // 根据安全访问开关动态设置协议
        $protocol = isset($this->bt_info['aqfw']) && $this->bt_info['aqfw'] == 'true' ? 'https' : 'http';
        $this->bt_api->BT_PANEL = $protocol . '://' . $this->bt_info['ip'] . ':' . $this->bt_info['dk'];
        $this->bt_api->BT_KEY = $this->bt_info['key'];
    }
    
    protected function success($data = array()) {
        $response = array('status' => true, 'code' => 'success');
        if (!empty($data)) {
            $response = array_merge($response, $data);
        }
        return $response;
    }
    
    protected function error($message) {
        return array('status' => false, 'code' => $message, 'msg' => $message);
    }
    
    protected function log($action, $message) {
        $username = isset($this->user['user']) ? $this->user['user'] : null;
        if (!$username) {
            return;
        }
        logjl($username, $action, $message, '成功');
    }
    
    protected function getWebId() {
        // 首先尝试使用主域名获取网站ID
        $primary_domain = isset($this->user['primary_domain']) ? $this->user['primary_domain'] : '';
        
        if (!empty($primary_domain)) {
            $webid = $this->bt_api->GetSiteIdByDomain($primary_domain);
            if ($webid > 0) {
                return $webid;
            }
        }
        
        // 如果主域名找不到，使用数据库记录的webid
        $webid = isset($this->user['webid']) ? $this->user['webid'] : null;
        if (empty($webid)) {
            $this->error('网站ID不存在');
        }
        return $webid;
    }
    
    protected function getConfigPath() {
        return '/www/server/panel/vhost/nginx/' . $this->site_name . '.conf';
    }
    
    /**
     * 重载Nginx配置
     */
    protected function reloadNginx() {
        // 尝试使用宝塔的重载API
        $reload_result = $this->bt_api->HttpPostCookie(
            $this->bt_api->BT_PANEL . '/site?action=ReloadServer',
            array_merge($this->bt_api->GetKeyData(), array('type' => 'nginx'))
        );
        
        $decoded = json_decode($reload_result, true);
        
        // 如果第一个方法失败，尝试第二个方法
        if (!$decoded || !isset($decoded['status']) || $decoded['status'] !== true) {
            $this->bt_api->HttpPostCookie(
                $this->bt_api->BT_PANEL . '/system?action=ServiceAdmin',
                array_merge($this->bt_api->GetKeyData(), array(
                    'name' => 'nginx',
                    'type' => 'reload'
                ))
            );
        }
    }
    
    protected function getFileContent($path) {
        $result = $this->bt_api->GetFileContent($path);
        if (!$result || !isset($result['status']) || ($result['status'] !== true && $result['status'] !== 'true' && $result['status'] !== 1)) {
            $this->error('获取文件内容失败');
        }
        return isset($result['data']) ? $result['data'] : '';
    }
    
    protected function saveFile($content, $path) {
        $result = $this->bt_api->setwj($content, $path);
        if (!$result || !isset($result['status']) || ($result['status'] !== true && $result['status'] !== 'true' && $result['status'] !== 1)) {
            $this->error('保存文件失败');
        }
        return true;
    }
}
