<?php
/**
 * APP 域名API
 * 复用前端域名API的实现
 */

require_once __DIR__ . '/app_base_api.php';

class AppDomainAPI extends AppBaseAPI {
    
    /**
     * 获取域名列表
     */
    public function getDomainList() {
        $webid = $this->getWebId();
        
        // 1) 获取子目录绑定
        $dirs = array('/');
        $binding_domains = array();
        $binding_names = array();
        $bind_res = $this->bt_api->GetDirBinding($webid);
        
        if ($bind_res && isset($bind_res['status']) && ($bind_res['status'] === true || $bind_res['status'] === 'true' || $bind_res['status'] === 1)) {
            if (isset($bind_res['dirs']) && is_array($bind_res['dirs'])) {
                $dirs = array();
                foreach ($bind_res['dirs'] as $d) {
                    $d = is_string($d) ? trim($d) : '';
                    if ($d === '') continue;
                    if ($d === '/') {
                        $dirs[] = '/';
                    } else {
                        $dirs[] = trim($d, '/');
                    }
                }
                if (!in_array('/', $dirs, true)) array_unshift($dirs, '/');
                $dirs = array_values(array_unique($dirs));
            }
            if (isset($bind_res['binding']) && is_array($bind_res['binding'])) {
                foreach ($bind_res['binding'] as $b) {
                    $name = isset($b['domain']) ? trim($b['domain']) : '';
                    if ($name === '') continue;
                    if ($this->isSystemGiftDomain($name)) continue;
                    $port = isset($b['port']) ? intval($b['port']) : 80;
                    $path = isset($b['path']) ? (string)$b['path'] : '/';
                    if (strpos($path, '../') === 0) $path = substr($path, 3);
                    $path = trim($path);
                    if ($path === '' || $path === '/') {
                        $path = '/';
                    } else {
                        $path = '/' . trim($path, '/');
                    }
                    $bind_id = isset($b['id']) ? $b['id'] : '';
                    $binding_domains[] = array(
                        'name' => $name,
                        'domain' => $name,
                        'port' => $port,
                        'path' => $path,
                        'bind_id' => $bind_id,
                        'is_binding' => true
                    );
                    $binding_names[$name . ':' . $port] = true;
                }
            }
        }
        
        // 2) 获取根域名列表
        $root_domains = array();
        $result = $this->bt_api->Getymlist($this->site_name);
        
        if ($result && isset($result['status']) && ($result['status'] === true || $result['status'] === 'true' || $result['status'] === 1)) {
            if (isset($result['data']) && is_array($result['data'])) {
                foreach ($result['data'] as $domain) {
                    $domain_name = '';
                    if (is_array($domain) && isset($domain['name'])) $domain_name = trim($domain['name']);
                    elseif (is_string($domain)) $domain_name = trim($domain);
                    if ($domain_name === '') continue;
                    if ($this->isSystemGiftDomain($domain_name)) continue;
                    $port = (is_array($domain) && isset($domain['port'])) ? intval($domain['port']) : 80;
                    if (isset($binding_names[$domain_name . ':' . $port])) continue;
                    $root_domains[] = array(
                        'name' => $domain_name,
                        'domain' => $domain_name,
                        'port' => $port,
                        'id' => is_array($domain) && isset($domain['id']) ? $domain['id'] : '',
                        'path' => '/',
                        'bind_id' => '',
                        'is_binding' => false
                    );
                }
            }
            
            $server_ip = $this->getParseAddress();
            return $this->success(array(
                'domains' => array_merge($root_domains, $binding_domains),
                'server_ip' => $server_ip,
                'dirs' => $dirs
            ));
        }
        
        // 如果宝塔API获取失败，尝试通过读取Nginx配置文件
        $config_path = $this->getConfigPath();
        $config_result = $this->bt_api->GetFileContent($config_path);
        
        if ($config_result && isset($config_result['status']) && ($config_result['status'] === true || $config_result['status'] === 'true' || $config_result['status'] === 1)) {
            $config_content = isset($config_result['data']) ? $config_result['data'] : '';
            
            if (!empty($config_content)) {
                preg_match_all('/server_name\s+([^;]+);/', $config_content, $matches);
                $domains = array();
                
                if (isset($matches[1]) && !empty($matches[1])) {
                    foreach ($matches[1] as $domain_line) {
                        $domain_list = explode(' ', trim($domain_line));
                        foreach ($domain_list as $domain) {
                            if (!empty($domain)) {
                                if ($this->isSystemGiftDomain($domain)) continue;
                                $domains[] = array(
                                    'name' => $domain,
                                    'port' => 80,
                                    'id' => 0
                                );
                            }
                        }
                    }
                }
                
                $server_ip = $this->getParseAddress();
                return $this->success(array('domains' => $domains, 'server_ip' => $server_ip, 'dirs' => $dirs));
            }
        }
        
        $server_ip = $this->getParseAddress();
        return $this->success(array('domains' => array(), 'server_ip' => $server_ip, 'dirs' => $dirs));
    }
    
    /**
     * 添加域名
     */
    public function addDomain($ym) {
        $webid = $this->getWebId();
        
        // 获取新添加的域名数量
        $new_domains = explode("\n", $ym);
        $new_count = count($new_domains);
        
        // 获取解析地址
        $parse_address = $this->getParseAddress();
        
        // 验证每个域名
        foreach ($new_domains as $domain) {
            $domain = trim($domain);
            if (empty($domain)) continue;
            
            // 检查是否为IP地址
            if (filter_var($domain, FILTER_VALIDATE_IP)) {
                return $this->error('禁止绑定IP地址，请输入域名');
            }
            
            // 检查是否为IP:端口格式
            if (preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/', $domain)) {
                return $this->error('禁止绑定IP地址，请输入域名');
            }
            
            // 检查是否为解析地址
            if (strcasecmp($domain, $parse_address) === 0) {
                return $this->error('禁止绑定解析地址 ' . $parse_address . '，请输入其他域名');
            }
            
            // 验证域名格式
            $domain_pattern = '/^(\*\.)?([a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/i';
            if (!preg_match($domain_pattern, $domain)) {
                return $this->error('域名格式不正确：' . $domain);
            }
        }
        
        // 获取当前已绑定的域名数量
        $current_domains = $this->bt_api->Getymlist($this->site_name);
        $current_count = 0;
        if ($current_domains && isset($current_domains['status']) && $current_domains['status'] === true) {
            if (isset($current_domains['data']) && is_array($current_domains['data'])) {
                foreach ($current_domains['data'] as $domain) {
                    $domain_name = isset($domain['name']) ? $domain['name'] : (isset($domain['domain']) ? $domain['domain'] : '');
                    if (!$this->isSystemGiftDomain($domain_name)) {
                        $current_count++;
                    }
                }
            }
        }
        
        // 检查域名数量限制
        if ($this->user['yms'] > 0 && ($current_count + $new_count) > $this->user['yms']) {
            return $this->error('域名数量超过限制，已绑定 ' . $current_count . ' 个，最多 ' . $this->user['yms'] . ' 个');
        }
        
        // 使用宝塔API添加域名
        $result = $this->bt_api->AddDomain($webid, $this->site_name, $ym);
        
        // 检查返回结果
        $success = false;
        if ($result) {
            if (isset($result['domains']) && is_array($result['domains'])) {
                foreach ($result['domains'] as $domain_info) {
                    if (isset($domain_info['status']) && ($domain_info['status'] == 1 || $domain_info['status'] === true || $domain_info['status'] === 'true')) {
                        $success = true;
                        break;
                    }
                }
            }
            if (isset($result['status']) && ($result['status'] === true || $result['status'] === 'true' || $result['status'] === 1)) {
                $success = true;
            }
        }
        
        if ($success) {
            $this->log('域名修改', '添加域名: ' . $ym);
            return $this->success(array('msg' => '添加成功'));
        }
        
        $error_msg = '添加失败';
        if (isset($result['domains']) && is_array($result['domains']) && !empty($result['domains'])) {
            $first_domain = $result['domains'][0];
            if (isset($first_domain['msg'])) {
                $error_msg = $first_domain['msg'];
            }
        } elseif (isset($result['msg'])) {
            $error_msg = $result['msg'];
        }
        
        return $this->error($error_msg);
    }
    
    /**
     * 删除域名
     */
    public function deleteDomain($domain, $port = 80) {
        $webid = $this->getWebId();
        
        if (empty($domain)) {
            return $this->error('域名不能为空');
        }
        
        // 检查是否为系统赠送域名
        if ($this->isSystemGiftDomain($domain)) {
            return $this->error('系统赠送域名不能删除');
        }
        
        // 使用宝塔API删除域名
        $result = $this->bt_api->DelDomain($webid, $this->site_name, $domain, $port);
        
        if ($result && isset($result['status']) && ($result['status'] === true || $result['status'] === 'true' || $result['status'] === 1)) {
            $this->log('域名修改', '删除域名: ' . $domain);
            return $this->success(array('msg' => '删除成功'));
        }
        
        return $this->error($result['msg'] ?? '删除失败');
    }
    
    /**
     * 获取子目录绑定
     */
    public function getDirBinding() {
        $webid = $this->getWebId();
        $result = $this->bt_api->GetDirBinding($webid);
        
        if ($result && isset($result['status']) && ($result['status'] === true || $result['status'] === 'true' || $result['status'] === 1)) {
            return $this->success($result);
        }
        
        return $this->success(array('dirs' => array('/'), 'binding' => array()));
    }
    
    /**
     * 添加子目录绑定
     */
    public function addDirBinding($domain, $dir) {
        $webid = $this->getWebId();
        
        if (empty($domain) || empty($dir)) {
            return $this->error('域名和目录不能为空');
        }
        
        $result = $this->bt_api->AddDirBinding($webid, $this->site_name, $domain, $dir);
        
        if ($result && isset($result['status']) && ($result['status'] === true || $result['status'] === 'true' || $result['status'] === 1)) {
            $this->log('子目录绑定', '添加绑定: ' . $domain . ' -> ' . $dir);
            return $this->success(array('msg' => '添加成功'));
        }
        
        return $this->error($result['msg'] ?? '添加失败');
    }
    
    /**
     * 删除子目录绑定
     */
    public function deleteDirBinding($id) {
        $webid = $this->getWebId();
        
        if (empty($id)) {
            return $this->error('绑定ID不能为空');
        }
        
        $result = $this->bt_api->DelDirBinding($webid, $id);
        
        if ($result && isset($result['status']) && ($result['status'] === true || $result['status'] === 'true' || $result['status'] === 1)) {
            $this->log('子目录绑定', '删除绑定ID: ' . $id);
            return $this->success(array('msg' => '删除成功'));
        }
        
        return $this->error($result['msg'] ?? '删除失败');
    }
}
