<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */



namespace Core\Lib;

class Controller
{
    protected $db;
    protected $viewData = [];
    
    public function __construct()
    {
        // 引入数据库实例
        $this->db = \Core\Db\DB::getInstance();
        
        // 检查登录状态
        $this->checkAuth();
        
        // 传递公共数据到视图
        $this->viewData['site_name'] = $this->getSiteName();
    }
    
    /**
     * 检查登录状态
     */
    protected function checkAuth()
    {
        // 获取当前模块
        $module = $this->getModule();
        
        // 登录页和安装程序不需要检查
        $noAuthModules = ['login', 'install', 'api'];
        
        if (in_array($module, $noAuthModules)) {
            return;
        }
        
        // 检查SESSION中的登录状态
        if (!isset($_SESSION['admin_id']) || empty($_SESSION['admin_id'])) {
            // AJAX请求返回JSON
            if ($this->isAjax()) {
                $this->json(302, '请先登录');
            }
            // 跳转到登录页
            header('Location: /admin/login.php');
            exit;
        }
        
        // 记录最后活动时间
        $_SESSION['last_activity'] = time();
    }
    
    /**
     * 获取当前模块名
     */
    protected function getModule()
    {
        $script = basename($_SERVER['SCRIPT_NAME'], '.php');
        return $script;
    }
    
    /**
     * 判断是否为AJAX请求
     */
    protected function isAjax()
    {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 
               strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
    }
    
    /**
     * 获取站点名称
     */
    protected function getSiteName()
    {
        $config = $this->db->fetch("SELECT config_value FROM {$this->db->table('config')} WHERE config_key = 'site_name'");
        return $config ? $config['config_value'] : '企业CMS';
    }
    
    /**
     * 渲染视图
     */
    protected function display($template = '', $data = [])
    {
        // 合并数据
        $data = array_merge($this->viewData, $data);
        
        // 提取变量到当前作用域
        extract($data);
        
        // 如果没有指定模板，根据当前控制器和方法确定
        if (empty($template)) {
            $controller = basename(get_class($this));
            $action = basename($_SERVER['REQUEST_URI']);
            $template = strtolower(str_replace('Controller', '', $controller)) . '.html';
        }
        
        // 模板路径
        $tplPath = dirname(__DIR__) . '/core/tpl/' . $template;
        
        if (file_exists($tplPath)) {
            include $tplPath;
        } else {
            echo "模板不存在: " . $tplPath;
        }
    }
    
    /**
     * 返回JSON
     */
    protected function json($code = 200, $msg = '', $data = [])
    {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode([
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    /**
     * 返回成功
     */
    protected function success($msg = '操作成功', $data = [])
    {
        $this->json(200, $msg, $data);
    }
    
    /**
     * 返回失败
     */
    protected function error($msg = '操作失败', $data = [])
    {
        $this->json(400, $msg, $data);
    }
    
    /**
     * 分页
     */
    protected function paginate($total, $pageSize = 20)
    {
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
        $page = max(1, $page);
        
        $totalPages = ceil($total / $pageSize);
        
        return [
            'page' => $page,
            'page_size' => $pageSize,
            'total' => $total,
            'total_pages' => $totalPages,
            'limit' => ($page - 1) * $pageSize
        ];
    }
    
    /**
     * 生成分页HTML
     */
    protected function getPageHtml($page, $totalPages, $url = '')
    {
        if ($totalPages <= 1) {
            return '';
        }
        
        $html = '<div class="pagination">';
        
        // 上一页
        if ($page > 1) {
            $html .= '<a href="' . $url . '?page=' . ($page - 1) . '" class="prev">上一页</a>';
        }
        
        // 页码
        $start = max(1, $page - 2);
        $end = min($totalPages, $page + 2);
        
        if ($start > 1) {
            $html .= '<a href="' . $url . '?page=1">1</a>';
            if ($start > 2) {
                $html .= '<span class="ellipsis">...</span>';
            }
        }
        
        for ($i = $start; $i <= $end; $i++) {
            $active = ($i == $page) ? ' class="active"' : '';
            $html .= '<a href="' . $url . '?page=' . $i . '"' . $active . '>' . $i . '</a>';
        }
        
        if ($end < $totalPages) {
            if ($end < $totalPages - 1) {
                $html .= '<span class="ellipsis">...</span>';
            }
            $html .= '<a href="' . $url . '?page=' . $totalPages . '">' . $totalPages . '</a>';
        }
        
        // 下一页
        if ($page < $totalPages) {
            $html .= '<a href="' . $url . '?page=' . ($page + 1) . '" class="next">下一页</a>';
        }
        
        $html .= '</div>';
        
        return $html;
    }
    
    /**
     * 获取查询参数
     */
    protected function getQuery($key, $default = '')
    {
        return isset($_GET[$key]) ? trim($_GET[$key]) : $default;
    }
    
    /**
     * 获取POST参数
     */
    protected function getPost($key, $default = '')
    {
        return isset($_POST[$key]) ? trim($_POST[$key]) : $default;
    }
    
    /**
     * 获取所有POST数据
     */
    protected function getAllPost()
    {
        return $_POST;
    }
    
    /**
     * 写入操作日志
     */
    protected function addLog($action, $module, $content = '')
    {
        $data = [
            'user_id' => $_SESSION['admin_id'],
            'username' => $_SESSION['admin_name'],
            'action' => $action,
            'module' => $module,
            'content' => $content,
            'ip' => $this->getClientIp(),
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
            'create_time' => time()
        ];
        
        $this->db->insert('log', $data);
    }
    
    /**
     * 获取客户端IP
     */
    protected function getClientIp()
    {
        $ip = '0.0.0.0';
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }
    
    /**
     * 验证CSRF令牌
     */
    protected function verifyCsrfToken()
    {
        $token = $_POST['csrf_token'] ?? '';
        return !empty($token) && isset($_SESSION['csrf_token']) && $token === $_SESSION['csrf_token'];
    }
    
    /**
     * 生成CSRF令牌
     */
    protected function generateCsrfToken()
    {
        if (!isset($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = md5(uniqid(mt_rand(), true));
        }
        return $_SESSION['csrf_token'];
    }
}