<?php
require_once __DIR__ . '/../base_api.php';

class PhpAPI extends BaseAPI {
    public function getPhpVersions() {
        $installed_versions = array();
        $available_versions = array(
            array('value' => '56', 'text' => 'PHP 5.6'),
            array('value' => '70', 'text' => 'PHP 7.0'),
            array('value' => '71', 'text' => 'PHP 7.1'),
            array('value' => '72', 'text' => 'PHP 7.2'),
            array('value' => '73', 'text' => 'PHP 7.3'),
            array('value' => '74', 'text' => 'PHP 7.4'),
            array('value' => '80', 'text' => 'PHP 8.0'),
            array('value' => '81', 'text' => 'PHP 8.1'),
            array('value' => '82', 'text' => 'PHP 8.2'),
            array('value' => '83', 'text' => 'PHP 8.3'),
            array('value' => '84', 'text' => 'PHP 8.4'),
            array('value' => '85', 'text' => 'PHP 8.5')
        );
        
        // 通过宝塔API获取已安装的PHP版本
        $result = $this->bt_api->GetPHPVersion();
        if ($result && is_array($result)) {
            foreach ($result as $php_version) {
                if (isset($php_version['version']) && isset($php_version['name']) && $php_version['version'] != '00') {
                    // 检查版本是否在可用版本列表中
                    foreach ($available_versions as $version) {
                        if ($version['value'] == $php_version['version']) {
                            $installed_versions[] = $version;
                            break;
                        }
                    }
                }
            }
        } else {
            // API调用失败，尝试通过shell命令检测PHP版本
            $shell_command = 'ls -la /www/server/php/ | grep -E "PHP-(5[2-6]|7[0-4]|8[0-5])" | awk -F "-" \'{print $2}\'';
            $shell_result = $this->bt_api->shell_yx($shell_command);
            
            if ($shell_result && isset($shell_result['output'])) {
                $php_versions = explode("\n", $shell_result['output']);
                foreach ($php_versions as $php_version) {
                    $php_version = trim($php_version);
                    if ($php_version && preg_match('/^\d+$/', $php_version)) {
                        // 检查版本是否在可用版本列表中
                        foreach ($available_versions as $version) {
                            if ($version['value'] == $php_version) {
                                $installed_versions[] = $version;
                                break;
                            }
                        }
                    }
                }
            }
            
            // 如果仍然没有检测到版本，提供一些常用的默认版本
            if (empty($installed_versions)) {
                $default_versions = array('56', '74', '80', '81');
                foreach ($default_versions as $default_version) {
                    foreach ($available_versions as $version) {
                        if ($version['value'] == $default_version) {
                            $installed_versions[] = $version;
                            break;
                        }
                    }
                }
            }
        }
        
        // 去重
        $installed_versions = array_values(array_unique($installed_versions, SORT_REGULAR));
        
        // 分离已安装和未安装的版本
        $not_installed = array();
        foreach ($available_versions as $version) {
            $found = false;
            foreach ($installed_versions as $installed) {
                if ($installed['value'] == $version['value']) {
                    $found = true;
                    break;
                }
            }
            if (!$found) {
                $not_installed[] = $version;
            }
        }
        
        // Get the currently selected PHP version from the database
        global $DB;
        $current_version = $DB->get_row("SELECT `php_version` FROM `zj` WHERE `id`='{$this->user['id']}'");
        $selected_version = $current_version && $current_version['php_version'] ? $current_version['php_version'] : '';
        
        // 尝试从nginx配置文件获取实际的PHP版本
        $actual_php_version = $this->getActualPhpVersionFromNginx();
        if ($actual_php_version) {
            // 如果配置文件中的版本与数据库不一致，以配置文件为准
            if ($actual_php_version !== $selected_version) {
                $this->debug_log('PHP版本不一致，更新数据库: ' . $selected_version . ' -> ' . $actual_php_version);
                // 更新数据库
                $actual_php_version_escaped = $DB->escape($actual_php_version);
                $user_id_escaped = intval($this->user['id']);
                $DB->query("UPDATE `zj` SET `php_version`='{$actual_php_version_escaped}' WHERE `id`='{$user_id_escaped}'");
                $selected_version = $actual_php_version;
            }
        }
        
        $this->success(array(
            'versions' => array(
                'installed' => $installed_versions,
                'available' => $not_installed
            ),
            'selected_version' => $selected_version
        ));
        
    }
    
    public function setPhpVersion($version) {
        $php_version_map = array(
            '56' => '5.6',
            '70' => '7.0',
            '71' => '7.1',
            '72' => '7.2',
            '73' => '7.3',
            '74' => '7.4',
            '80' => '8.0',
            '81' => '8.1',
            '82' => '8.2',
            '83' => '8.3',
            '84' => '8.4',
            '85' => '8.5'
        );
        
        // 验证PHP版本是否已安装
        $result = $this->bt_api->GetPHPVersion();
        $installed_versions = array();
        
        if ($result && is_array($result)) {
            foreach ($result as $php_version) {
                if (isset($php_version['version']) && $php_version['version'] != '00') {
                    $installed_versions[] = $php_version['version'];
                }
            }
        }
        
        // 去重
        $installed_versions = array_unique($installed_versions);
        
        if (!in_array($version, $installed_versions)) {
            $this->error('该PHP版本未安装');
        }
        
        if (isset($php_version_map[$version])) {
            $php_version = $php_version_map[$version];
            $result = $this->bt_api->SetPHPVersion($this->site_name, $version);
            
            // 调试：记录结果
            $this->debug_log('setPhpVersion结果: ' . print_r($result, true));
            
            if ($result && isset($result['status']) && ($result['status'] === true || $result['status'] === 'true' || $result['status'] === 1)) {
                // Save the selected PHP version to the database
                global $DB;
                $version_escaped = $DB->escape($version);
                $user_id_escaped = intval($this->user['id']);
                $DB->query("UPDATE `zj` SET `php_version`='{$version_escaped}' WHERE `id`='{$user_id_escaped}'");
                
                $this->log('PHP版本切换', '切换到PHP ' . $php_version);
                $this->success(array('msg' => '切换成功'));
            }
        }
        
        $error_msg = isset($result['msg']) ? $result['msg'] : '切换失败';
        $this->error($error_msg);
    }
    
    /**
     * 从nginx配置文件获取实际的PHP版本
     * @return string|null PHP版本号（如 '74'）或null
     */
    private function getActualPhpVersionFromNginx() {
        // 获取网站名称
        $site_name = $this->site_name;
        if (empty($site_name)) {
            return null;
        }
        
        // nginx配置文件路径
        $nginx_conf_path = '/www/server/panel/vhost/nginx/' . $site_name . '.conf';
        
        // 尝试通过宝塔API读取文件
        $url = $this->bt_api->BT_PANEL . '/files?action=GetFileBody';
        $p_data = $this->bt_api->GetKeyData();
        $p_data['path'] = $nginx_conf_path;
        
        $this->debug_log('尝试读取nginx配置文件: ' . $nginx_conf_path);
        
        $result = $this->bt_api->HttpPostCookie($url, $p_data);
        
        if (strpos($result, '{') === 0) {
            $decoded_result = json_decode($result, true);
            
            if ($decoded_result && isset($decoded_result['status']) && $decoded_result['status'] && isset($decoded_result['data'])) {
                $config_content = $decoded_result['data'];
                
                // 查找PHP版本配置，如：include enable-php-74.conf;
                if (preg_match('/enable-php-(\d+)\.conf/', $config_content, $matches)) {
                    $php_version = $matches[1];
                    $this->debug_log('从nginx配置文件找到PHP版本: ' . $php_version);
                    return $php_version;
                }
            }
        }
        
        $this->debug_log('无法从nginx配置文件获取PHP版本');
        return null;
    }
}
?>