<?php
/**
 * 用户面板 API 层
 * 提供统一的数据接口，供模板调用
 */

if (!defined('IN_CRONLITE')) {
    require_once __DIR__ . '/../common.php';
}

class UserApi {
    private $user;
    private $bt_api;
    private $user_info;
    
    public function __construct($user = null) {
        if ($user) {
            $this->user = $user;
        } else {
            $this->user = check_user();
        }
        
        if ($this->user) {
            global $DB;
            $this->user_info = $DB->get_row("SELECT * FROM `zj` WHERE `user`='{$this->user['user']}'");
            $this->initBtApi();
        }
    }
    
    /**
     * 初始化宝塔 API
     */
    private function initBtApi() {
        if (!$this->user_info || !$this->user_info['btid']) {
            return false;
        }
        
        global $DB;
        $bt = $DB->get_row("SELECT * FROM `bt` WHERE `id`='{$this->user_info['btid']}'");
        if (!$bt) {
            return false;
        }
        
        require_once __DIR__ . '/../class.php';
        $this->bt_api = new bt_api();
        
        $protocol = isset($bt['aqfw']) && $bt['aqfw'] == 'true' ? 'https' : 'http';
        $this->bt_api->BT_PANEL = $protocol . '://' . $bt['ip'] . ':' . $bt['dk'];
        $this->bt_api->BT_KEY = $bt['key'];
        
        return true;
    }
    
    /**
     * 获取用户信息
     */
    public function getUserInfo() {
        return [
            'user' => $this->user,
            'info' => $this->user_info,
            'bt' => $this->getBtInfo()
        ];
    }
    
    /**
     * 获取宝塔信息
     */
    public function getBtInfo() {
        if (!$this->user_info || !$this->user_info['btid']) {
            return null;
        }
        
        global $DB;
        return $DB->get_row("SELECT * FROM `bt` WHERE `id`='{$this->user_info['btid']}'");
    }
    
    /**
     * 获取统计数据
     */
    public function getStats() {
        $web_count = 1;
        $db_count = $this->user_info && !empty($this->user_info['sqluser']) && $this->user_info['sqluser'] != '0' ? 1 : 0;
        $ftp_count = $this->user_info && !empty($this->user_info['ftpuser']) && $this->user_info['ftpuser'] != '0' ? 1 : 0;
        $backup_count = $this->getBackupCount();
        
        return [
            'web_count' => $web_count,
            'db_count' => $db_count,
            'ftp_count' => $ftp_count,
            'backup_count' => $backup_count
        ];
    }
    
    /**
     * 获取备份数量
     */
    public function getBackupCount() {
        if (!$this->bt_api || !$this->user_info || !$this->user_info['webid']) {
            return 0;
        }
        
        $count = 0;
        
        // 获取网站备份
        $site_backups = $this->bt_api->GetBackupList(0, $this->user_info['webid']);
        if (isset($site_backups['data']) && is_array($site_backups['data'])) {
            $count += count($site_backups['data']);
        }
        
        // 获取数据库备份
        if (!empty($this->user_info['sqldb'])) {
            $url = $this->bt_api->BT_PANEL . '/data?action=getData';
            $p_data = $this->bt_api->GetKeyData();
            $p_data['table'] = 'databases';
            $p_data['search'] = $this->user_info['sqldb'];
            $p_data['limit'] = 10;
            $p_data['p'] = 1;
            
            $result = $this->bt_api->HttpPostCookie($url, $p_data);
            $db_list = json_decode($result, true);
            
            if (isset($db_list['data']) && is_array($db_list['data'])) {
                foreach ($db_list['data'] as $db_item) {
                    if (isset($db_item['name']) && $db_item['name'] == $this->user_info['sqldb'] && isset($db_item['id'])) {
                        $db_backups = $this->bt_api->GetBackupList(1, $db_item['id']);
                        if (isset($db_backups['data']) && is_array($db_backups['data'])) {
                            $count += count($db_backups['data']);
                        }
                        break;
                    }
                }
            }
        }
        
        return $count;
    }
    
    /**
     * 获取资源使用情况
     */
    public function getResourceUsage() {
        $web_space = ['used' => '0M', 'total' => '0M', 'percent' => 0];
        $db_space = ['used' => '0M', 'total' => '0M', 'percent' => 0];
        $traffic = ['used' => '0G', 'total' => '0G', 'percent' => 0];
        
        if ($this->user_info) {
            // 网页空间
            if (!empty($this->user_info['wypj'])) {
                $web_space = $this->parseResource($this->user_info['wypj']);
            }
            
            // 数据库空间
            if (!empty($this->user_info['sypj'])) {
                $db_space = $this->parseResource($this->user_info['sypj']);
            }
            
            // 流量
            if (!empty($this->user_info['llxz'])) {
                $traffic = $this->parseResource($this->user_info['llxz']);
            }
        }
        
        return [
            'web_space' => $web_space,
            'db_space' => $db_space,
            'traffic' => $traffic
        ];
    }
    
    /**
     * 解析资源字符串
     */
    private function parseResource($str) {
        $result = ['used' => '0M', 'total' => '0M', 'percent' => 0];
        
        if (strpos($str, '/') !== false) {
            list($used, $total) = explode('/', $str);
            $result['used'] = trim($used);
            $result['total'] = trim($total);
            
            $used_val = $this->extractValue($used);
            $total_val = $this->extractValue($total);
            
            if ($total_val > 0) {
                $result['percent'] = round(($used_val / $total_val) * 100);
            }
        } else {
            $result['total'] = trim($str);
        }
        
        return $result;
    }
    
    /**
     * 提取数值
     */
    private function extractValue($str) {
        $str = trim($str);
        if (preg_match('/^([0-9.]+)\s*([KMGT]?B?)$/i', $str, $matches)) {
            $value = floatval($matches[1]);
            $unit = strtoupper($matches[2]);
            if (empty($unit) || $unit == 'B') $unit = 'M';
            
            switch ($unit) {
                case 'KB': return $value * 1024;
                case 'MB': return $value * 1024 * 1024;
                case 'GB': return $value * 1024 * 1024 * 1024;
                case 'TB': return $value * 1024 * 1024 * 1024 * 1024;
                default: return $value;
            }
        }
        return floatval(preg_replace('/[^0-9.]/', '', $str));
    }
    
    /**
     * 获取最近操作日志
     */
    public function getRecentLogs($limit = 5) {
        global $DB;
        $user_escaped = $DB->escape($this->user['user']);
        $limit_escaped = intval($limit);
        $logs = $DB->get_all("SELECT * FROM `log` WHERE `user`='{$user_escaped}' ORDER BY `id` DESC LIMIT {$limit_escaped}");
        return $logs ?: [];
    }
    
    /**
     * 获取系统公告
     */
    public function getAnnouncements($limit = 4) {
        global $DB;
        $limit_escaped = intval($limit);
        $announcements = $DB->get_all("SELECT * FROM `notifications` WHERE `target_type`='all' ORDER BY `create_time` DESC LIMIT {$limit_escaped}");
        return $announcements ?: [];
    }
    
    /**
     * 获取域名列表
     */
    public function getDomains() {
        if (!$this->user_info || empty($this->user_info['yms'])) {
            return [];
        }
        
        $domains = explode(',', $this->user_info['yms']);
        $result = [];
        foreach ($domains as $domain) {
            $domain = trim($domain);
            if (!empty($domain)) {
                $result[] = [
                    'name' => $domain,
                    'port' => 80
                ];
            }
        }
        return $result;
    }
    
    /**
     * 获取数据库列表
     */
    public function getDatabases() {
        if (!$this->user_info || empty($this->user_info['sqldb'])) {
            return [];
        }
        
        return [
            [
                'name' => $this->user_info['sqldb'],
                'username' => $this->user_info['sqluser'],
                'password' => $this->user_info['sqlpass']
            ]
        ];
    }
    
    /**
     * 获取FTP账户
     */
    public function getFtpAccounts() {
        if (!$this->user_info || empty($this->user_info['ftpuser'])) {
            return [];
        }
        
        return [
            [
                'username' => $this->user_info['ftpuser'],
                'password' => $this->user_info['ftppass'],
                'path' => $this->user_info['ftppath'] ?? '/'
            ]
        ];
    }
    
    /**
     * 获取网站设置
     */
    public function getSiteSettings() {
        if (!$this->user_info) {
            return null;
        }
        
        return [
            'php_version' => $this->user_info['php'] ?? '74',
            'domains' => $this->user_info['yms'] ?? '',
            'default_doc' => $this->user_info['mrwd'] ?? 'index.php,index.html',
            'run_dir' => $this->user_info['yxml'] ?? '/',
            'rewrite' => $this->user_info['wjt'] ?? '',
            'sub_dir' => $this->user_info['zml'] ?? ''
        ];
    }
}
