<?php
/**
 * 项目系统对接插件 - 动作处理文件
 * 处理所有请求和钩子
 */

namespace plugin\shop\project_system;

// 引入核心类
require_once __DIR__ . '/server.php';

class Action {
    
    private $server;
    
    public function __construct() {
        $this->server = new Server();
    }
    
    /**
     * 安装插件
     */
    public static function install() {
        global $db;
        
        // 创建网站记录表
        $sql1 = "CREATE TABLE IF NOT EXISTS `lzsys_project_websites` (
            `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
            `user_id` int(11) DEFAULT '0',
            `domain` varchar(255) NOT NULL,
            `root_path` varchar(500) DEFAULT '',
            `php_version` varchar(10) DEFAULT '74',
            `status` tinyint(1) DEFAULT '1',
            `create_time` int(11) DEFAULT '0',
            `expire_time` int(11) DEFAULT '0',
            PRIMARY KEY (`id`),
            KEY `domain` (`domain`),
            KEY `user_id` (`user_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
        
        // 创建数据库记录表
        $sql2 = "CREATE TABLE IF NOT EXISTS `lzsys_project_databases` (
            `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
            `user_id` int(11) DEFAULT '0',
            `db_name` varchar(100) NOT NULL,
            `username` varchar(100) DEFAULT '',
            `password` varchar(255) DEFAULT '',
            `status` tinyint(1) DEFAULT '1',
            `create_time` int(11) DEFAULT '0',
            PRIMARY KEY (`id`),
            KEY `db_name` (`db_name`),
            KEY `user_id` (`user_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
        
        // 创建FTP记录表
        $sql3 = "CREATE TABLE IF NOT EXISTS `lzsys_project_ftp` (
            `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
            `user_id` int(11) DEFAULT '0',
            `username` varchar(100) NOT NULL,
            `root_path` varchar(500) DEFAULT '',
            `status` tinyint(1) DEFAULT '1',
            `create_time` int(11) DEFAULT '0',
            PRIMARY KEY (`id`),
            KEY `username` (`username`),
            KEY `user_id` (`user_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
        
        // 创建订单关联表
        $sql4 = "CREATE TABLE IF NOT EXISTS `lzsys_project_orders` (
            `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
            `order_id` int(11) DEFAULT '0',
            `user_id` int(11) DEFAULT '0',
            `domain` varchar(255) DEFAULT '',
            `db_name` varchar(100) DEFAULT '',
            `ftp_user` varchar(100) DEFAULT '',
            `create_time` int(11) DEFAULT '0',
            PRIMARY KEY (`id`),
            KEY `order_id` (`order_id`),
            KEY `user_id` (`user_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
        
        try {
            $db->query($sql1);
            $db->query($sql2);
            $db->query($sql3);
            $db->query($sql4);
            return ['status' => true, 'msg' => '安装成功'];
        } catch (\Exception $e) {
            return ['status' => false, 'msg' => '安装失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 卸载插件
     */
    public static function uninstall() {
        global $db;
        
        // 删除数据表（可选，根据需求决定是否保留数据）
        // $db->query("DROP TABLE IF EXISTS lzsys_project_websites");
        // $db->query("DROP TABLE IF EXISTS lzsys_project_databases");
        // $db->query("DROP TABLE IF EXISTS lzsys_project_ftp");
        // $db->query("DROP TABLE IF EXISTS lzsys_project_orders");
        
        return ['status' => true, 'msg' => '卸载成功'];
    }
    
    /**
     * 升级插件
     */
    public static function upgrade($fromVersion, $toVersion) {
        return ['status' => true, 'msg' => '升级成功'];
    }
    
    /**
     * 订单支付成功钩子
     */
    public static function orderPaid($orderData) {
        $action = new self();
        
        // 获取订单信息
        $orderId = $orderData['order_id'] ?? 0;
        $userId = $orderData['user_id'] ?? 0;
        $productId = $orderData['product_id'] ?? 0;
        
        // 获取产品配置
        $config = $action->getProductConfig($productId);
        
        if (empty($config)) {
            return ['status' => false, 'msg' => '产品配置不存在'];
        }
        
        $results = [];
        
        // 创建网站
        if (!empty($config['domain'])) {
            $websiteResult = $action->server->createWebsite(
                $config['domain'],
                $config['root_path'] ?? '',
                $config['php_version'] ?? ''
            );
            $results['website'] = $websiteResult;
        }
        
        // 创建数据库
        if (!empty($config['create_database'])) {
            $dbName = str_replace('.', '_', $config['domain']);
            $dbResult = $action->server->createDatabase($dbName);
            $results['database'] = $dbResult;
        }
        
        // 创建FTP
        if (!empty($config['create_ftp'])) {
            $ftpUser = 'ftp_' . str_replace('.', '_', $config['domain']);
            $ftpResult = $action->server->createFtp($ftpUser);
            $results['ftp'] = $ftpResult;
        }
        
        // 记录订单关联
        $action->recordOrderRelation($orderId, $userId, $config);
        
        return ['status' => true, 'msg' => '服务开通成功', 'data' => $results];
    }
    
    /**
     * 服务到期提醒钩子
     */
    public static function serviceExpire($serviceData) {
        // 发送到期提醒通知
        // 可以集成短信、邮件通知
        return ['status' => true];
    }
    
    /**
     * 用户注册钩子
     */
    public static function userRegister($userData) {
        // 用户注册后的处理
        return ['status' => true];
    }
    
    /**
     * 处理AJAX请求
     */
    public function handleAjax() {
        $action = $_REQUEST['action'] ?? '';
        
        switch ($action) {
            case 'create_website':
                return $this->ajaxCreateWebsite();
                
            case 'delete_website':
                return $this->ajaxDeleteWebsite();
                
            case 'create_database':
                return $this->ajaxCreateDatabase();
                
            case 'delete_database':
                return $this->ajaxDeleteDatabase();
                
            case 'create_ftp':
                return $this->ajaxCreateFtp();
                
            case 'delete_ftp':
                return $this->ajaxDeleteFtp();
                
            case 'apply_ssl':
                return $this->ajaxApplySSL();
                
            case 'test_connection':
                return $this->ajaxTestConnection();
                
            case 'get_website_list':
                return $this->ajaxGetWebsiteList();
                
            case 'get_database_list':
                return $this->ajaxGetDatabaseList();
                
            case 'get_ftp_list':
                return $this->ajaxGetFtpList();
                
            case 'auto_login':
                return $this->ajaxAutoLogin();
                
            default:
                return json_encode(['status' => false, 'msg' => '未知操作']);
        }
    }
    
    /**
     * AJAX创建网站
     */
    private function ajaxCreateWebsite() {
        $domain = $_POST['domain'] ?? '';
        $path = $_POST['path'] ?? '';
        $phpVersion = $_POST['php_version'] ?? '';
        
        if (empty($domain)) {
            return json_encode(['status' => false, 'msg' => '域名不能为空']);
        }
        
        $result = $this->server->createWebsite($domain, $path, $phpVersion);
        return json_encode($result);
    }
    
    /**
     * AJAX删除网站
     */
    private function ajaxDeleteWebsite() {
        $domain = $_POST['domain'] ?? '';
        $deletePath = $_POST['delete_path'] ?? false;
        
        if (empty($domain)) {
            return json_encode(['status' => false, 'msg' => '域名不能为空']);
        }
        
        $result = $this->server->deleteWebsite($domain, $deletePath);
        return json_encode($result);
    }
    
    /**
     * AJAX创建数据库
     */
    private function ajaxCreateDatabase() {
        $dbName = $_POST['db_name'] ?? '';
        
        if (empty($dbName)) {
            return json_encode(['status' => false, 'msg' => '数据库名不能为空']);
        }
        
        $result = $this->server->createDatabase($dbName);
        return json_encode($result);
    }
    
    /**
     * AJAX删除数据库
     */
    private function ajaxDeleteDatabase() {
        $dbName = $_POST['db_name'] ?? '';
        
        if (empty($dbName)) {
            return json_encode(['status' => false, 'msg' => '数据库名不能为空']);
        }
        
        $result = $this->server->deleteDatabase($dbName);
        return json_encode($result);
    }
    
    /**
     * AJAX创建FTP
     */
    private function ajaxCreateFtp() {
        $username = $_POST['username'] ?? '';
        $path = $_POST['path'] ?? '';
        
        if (empty($username)) {
            return json_encode(['status' => false, 'msg' => '用户名不能为空']);
        }
        
        $result = $this->server->createFtp($username, '', $path);
        return json_encode($result);
    }
    
    /**
     * AJAX删除FTP
     */
    private function ajaxDeleteFtp() {
        $username = $_POST['username'] ?? '';
        
        if (empty($username)) {
            return json_encode(['status' => false, 'msg' => '用户名不能为空']);
        }
        
        $result = $this->server->deleteFtp($username);
        return json_encode($result);
    }
    
    /**
     * AJAX申请SSL
     */
    private function ajaxApplySSL() {
        $domain = $_POST['domain'] ?? '';
        
        if (empty($domain)) {
            return json_encode(['status' => false, 'msg' => '域名不能为空']);
        }
        
        $result = $this->server->applySSL($domain);
        return json_encode($result);
    }
    
    /**
     * AJAX测试连接
     */
    private function ajaxTestConnection() {
        $result = $this->server->testConnection();
        return json_encode($result);
    }
    
    /**
     * AJAX获取网站列表
     */
    private function ajaxGetWebsiteList() {
        $page = intval($_GET['page'] ?? 1);
        $limit = intval($_GET['limit'] ?? 10);
        
        $list = $this->server->getWebsiteList($page, $limit);
        return json_encode(['status' => true, 'data' => $list]);
    }
    
    /**
     * AJAX获取数据库列表
     */
    private function ajaxGetDatabaseList() {
        $page = intval($_GET['page'] ?? 1);
        $limit = intval($_GET['limit'] ?? 10);
        
        $list = $this->server->getDatabaseList($page, $limit);
        return json_encode(['status' => true, 'data' => $list]);
    }
    
    /**
     * AJAX获取FTP列表
     */
    private function ajaxGetFtpList() {
        $page = intval($_GET['page'] ?? 1);
        $limit = intval($_GET['limit'] ?? 10);
        
        $list = $this->server->getFtpList($page, $limit);
        return json_encode(['status' => true, 'data' => $list]);
    }
    
    /**
     * AJAX自动登录
     */
    private function ajaxAutoLogin() {
        $userId = intval($_SESSION['user_id'] ?? 0);
        $username = $_SESSION['username'] ?? '';
        
        if (empty($userId)) {
            return json_encode(['status' => false, 'msg' => '未登录']);
        }
        
        $url = $this->server->getUserCenterUrl($userId, $username);
        
        if (empty($url)) {
            return json_encode(['status' => false, 'msg' => '用户中心地址未配置']);
        }
        
        return json_encode(['status' => true, 'url' => $url]);
    }
    
    /**
     * 获取产品配置
     */
    private function getProductConfig($productId) {
        global $db;
        $sql = "SELECT * FROM lzsys_shop_product WHERE product_id = ?";
        $product = $db->query($sql, [$productId])->fetch();
        
        if (!$product) {
            return [];
        }
        
        // 解析产品配置
        $config = json_decode($product['config'] ?? '{}', true);
        return $config;
    }
    
    /**
     * 记录订单关联
     */
    private function recordOrderRelation($orderId, $userId, $config) {
        global $db;
        
        $sql = "INSERT INTO lzsys_project_orders 
                (order_id, user_id, domain, db_name, ftp_user, create_time) 
                VALUES (?, ?, ?, ?, ?, ?)";
        
        $db->query($sql, [
            $orderId,
            $userId,
            $config['domain'] ?? '',
            $config['db_name'] ?? '',
            $config['ftp_user'] ?? '',
            time()
        ]);
    }
}

// 处理AJAX请求
if (isset($_REQUEST['action'])) {
    $action = new Action();
    echo $action->handleAjax();
    exit;
}
