<?php
/**
 * 模板基类
 * 提供模板通用的功能和组件加载
 */

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

require_once __DIR__ . '/api/UserApi.php';

abstract class TemplateBase {
    protected $theme;
    protected $user;
    protected $userApi;
    protected $templateDir;
    protected $componentsDir;
    protected $pagesDir;
    
    public function __construct($theme = 'default') {
        $this->theme = $theme;
        $this->templateDir = __DIR__ . '/../templates/' . $theme;
        $this->componentsDir = $this->templateDir . '/components';
        $this->pagesDir = $this->templateDir . '/pages';
        
        // 初始化用户
        $this->user = check_user();
        if (!$this->user) {
            header('Location: /user/login.php');
            exit;
        }
        
        // 初始化 API
        $this->userApi = new UserApi($this->user);
    }
    
    /**
     * 渲染页面
     */
    public function render($page = 'dashboard') {
        $pageFile = $this->pagesDir . '/' . $page . '.php';
        
        if (!file_exists($pageFile)) {
            $pageFile = $this->pagesDir . '/dashboard.php';
        }
        
        // 获取数据
        $data = $this->getPageData($page);
        
        // 渲染布局
        $this->renderLayout($page, $data, $pageFile);
    }
    
    /**
     * 获取页面数据
     */
    protected function getPageData($page) {
        $commonData = [
            'user' => $this->user,
            'userInfo' => $this->userApi->getUserInfo(),
            'stats' => $this->userApi->getStats(),
            'resourceUsage' => $this->userApi->getResourceUsage()
        ];
        
        $pageData = [];
        
        switch ($page) {
            case 'dashboard':
            case 'sy':
                $pageData = [
                    'logs' => $this->userApi->getRecentLogs(5),
                    'announcements' => $this->userApi->getAnnouncements(4)
                ];
                break;
                
            case 'site':
            case 'set':
                $pageData = [
                    'settings' => $this->userApi->getSiteSettings(),
                    'domains' => $this->userApi->getDomains()
                ];
                break;
                
            case 'database':
            case 'sql':
                $pageData = [
                    'databases' => $this->userApi->getDatabases()
                ];
                break;
                
            case 'file':
                $pageData = [
                    'ftpAccounts' => $this->userApi->getFtpAccounts()
                ];
                break;
                
            case 'backup':
                $pageData = [
                    'backups' => [] // 通过 API 异步加载
                ];
                break;
        }
        
        return array_merge($commonData, $pageData);
    }
    
    /**
     * 渲染布局（由子类实现）
     */
    abstract protected function renderLayout($page, $data, $pageFile);
    
    /**
     * 加载组件
     */
    protected function component($name, $data = []) {
        $componentFile = $this->componentsDir . '/' . $name . '.php';
        
        if (file_exists($componentFile)) {
            extract($data);
            include $componentFile;
        }
    }
    
    /**
     * 获取资源 URL
     */
    protected function asset($path) {
        return '/templates/' . $this->theme . '/assets/' . $path;
    }
    
    /**
     * 获取站点名称
     */
    protected function getSiteName() {
        global $conf;
        return isset($conf['name']) && !empty($conf['name']) ? $conf['name'] : '控制面板';
    }
    
    /**
     * 转义 HTML
     */
    protected function e($str) {
        return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
    }
    
    /**
     * 获取当前页面
     */
    protected function getCurrentPage() {
        return isset($_GET['page']) ? $_GET['page'] : 'dashboard';
    }
    
    /**
     * 检查当前页面是否激活
     */
    protected function isActive($page) {
        return $this->getCurrentPage() === $page ? 'active' : '';
    }
}
