<?php
session_start();
require_once __DIR__ . '/../src/Database.php';
require_once __DIR__ . '/../src/Auth.php';
require_once __DIR__ . '/../src/Editor.php';

$db = new Database();
$auth = new Auth($db);
$editor = new Editor($db);

$action = $_GET['action'] ?? '';

// 如果没有指定动作，检查登录状态并重定向
if (empty($action)) {
    if ($auth->isLoggedIn()) {
        header('Location: index.php?action=auth-code');
    } else {
        header('Location: index.php?action=login');
    }
    exit;
}

// 检查用户是否已登录（预览页面和彩信模板管理不需要登录）
if (!in_array($action, ['login', 'preview', 'mms']) && !$auth->isLoggedIn()) {
    header('Location: index.php?action=login');
    exit;
}

switch ($action) {
    case 'login':
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $username = $_POST['username'] ?? '';
            $password = $_POST['password'] ?? '';
            if ($auth->login($username, $password)) {
                header('Location: index.php?action=auth-code');
                exit;
            } else {
                $error = '用户名或密码错误';
            }
        }
        include '../templates/login.php';
        break;
        

    case 'logout':
        $auth->logout();
        header('Location: index.php');
        exit;
        
    case 'editor':
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $title = $_POST['title'] ?? '';
            $content = $_POST['content'] ?? '';
            $contentId = $_POST['content_id'] ?? null;
            
            if (!empty($title) && !empty($content)) {
                if ($editor->saveContent($title, $content, $contentId)) {
                    $success = $contentId ? '内容更新成功！' : '内容保存成功！';
                } else {
                    $error = '保存失败，请重试';
                }
            }
        }
        $contents = $editor->getAllContents();
        include '../templates/editor.php';
        break;
        
    case 'preview':
        $id = $_GET['id'] ?? 0;
        $content = $editor->getContentForPreview($id);
        include '../templates/preview.php';
        break;
        
    case 'change-password':
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $currentPassword = $_POST['current_password'] ?? '';
            $newPassword = $_POST['new_password'] ?? '';
            $confirmPassword = $_POST['confirm_password'] ?? '';
            
            if (empty($currentPassword) || empty($newPassword) || empty($confirmPassword)) {
                $error = '请填写所有字段';
            } elseif ($newPassword !== $confirmPassword) {
                $error = '新密码和确认密码不匹配';

            } elseif ($auth->changePassword($currentPassword, $newPassword)) {
                $success = '密码修改成功！';
            } else {
                $error = '当前密码错误';
            }
        }
        include '../templates/change-password.php';
        break;
        
    case 'auth-code':
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $machineCode = $_POST['machine_code'] ?? '';
            $expireDate = $_POST['expire_date'] ?? '';
            
            if (!empty($machineCode) && !empty($expireDate)) {
                // 生成授权码的逻辑
                $authCode = generateAuthCode($machineCode, $expireDate);
                $success = '授权码生成成功！';
            } else {
                $error = '请填写机器码和到期日期';
            }
        }
        include '../templates/auth-code.php';
        break;
        
    case 'mms':
        include '../templates/mms-templates.php';
        break;
}

// 生成授权码的函数
function generateAuthCode($machineCode, $expireDate) {
    // 使用MD5算法生成32位大写授权码
    $data = $machineCode . "gd051106" . $expireDate;
    $md5Hash = md5($data);
    return $expireDate . strtoupper($md5Hash);
}