<?php
// 用户认证相关函数
function isLoggedIn() {
    return isset($_SESSION['user']) && !empty($_SESSION['user']);
}

function isAdmin() {
    return isLoggedIn() && $_SESSION['user']['role'] === 'admin';
}

function login($username, $password) {
    $admin_file = USERS_PATH . '/admin.json';
    if (file_exists($admin_file)) {
        $admin_data = json_decode(file_get_contents($admin_file), true);
        if ($admin_data['username'] === $username && password_verify($password, $admin_data['password'])) {
            $_SESSION['user'] = $admin_data;
            return true;
        }
    }
    return false;
}

function logout() {
    unset($_SESSION['user']);
    session_destroy();
}

// 用户管理函数
function getAllUsers() {
    $users = [];
    $user_files = glob(USERS_PATH . '/*.json');
    
    foreach ($user_files as $user_file) {
        $user_data = json_decode(file_get_contents($user_file), true);
        if ($user_data) {
            // 不返回密码信息
            unset($user_data['password']);
            $users[] = $user_data;
        }
    }
    
    return $users;
}

function createUser($username, $password, $role = 'editor') {
    $user_file = USERS_PATH . '/' . $username . '.json';
    
    // 检查用户是否已存在
    if (file_exists($user_file)) {
        return false;
    }
    
    $user_data = [
        'username' => $username,
        'password' => password_hash($password, PASSWORD_DEFAULT),
        'role' => $role,
        'created_at' => date('Y-m-d H:i:s')
    ];
    
    return file_put_contents($user_file, json_encode($user_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

function deleteUser($username) {
    // 不允许删除admin用户
    if ($username === 'admin') {
        return false;
    }
    
    $user_file = USERS_PATH . '/' . $username . '.json';
    
    if (file_exists($user_file)) {
        return unlink($user_file);
    }
    
    return false;
}

function getUser($username) {
    $user_file = USERS_PATH . '/' . $username . '.json';
    
    if (file_exists($user_file)) {
        return json_decode(file_get_contents($user_file), true);
    }
    
    return null;
}

function saveUser($user_data) {
    $user_file = USERS_PATH . '/' . $user_data['username'] . '.json';
    return file_put_contents($user_file, json_encode($user_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

// 文章相关函数
function getAllPosts() {
    $posts = [];
    $years = glob(POSTS_PATH . '/*', GLOB_ONLYDIR);
    
    foreach ($years as $year_dir) {
        $months = glob($year_dir . '/*', GLOB_ONLYDIR);
        foreach ($months as $month_dir) {
            $days = glob($month_dir . '/*', GLOB_ONLYDIR);
            foreach ($days as $day_dir) {
                $post_files = glob($day_dir . '/*.json');
                foreach ($post_files as $post_file) {
                    $post_data = json_decode(file_get_contents($post_file), true);
                    if ($post_data) {
                        // 确保status字段存在，如果不存在则默认为published
                        if (!isset($post_data['status'])) {
                            $post_data['status'] = 'published';
                        }
                        $posts[] = $post_data;
                    }
                }
            }
        }
    }
    
    usort($posts, function($a, $b) {
        return strtotime($b['created_at']) - strtotime($a['created_at']);
    });
    
    return $posts;
}

function getPost($year, $month, $day, $slug) {
    $post_file = POSTS_PATH . "/$year/$month/$day/$slug.json";
    if (file_exists($post_file)) {
        return json_decode(file_get_contents($post_file), true);
    }
    return null;
}

function savePost($post_data) {
    $year = date('Y', strtotime($post_data['created_at']));
    $month = date('m', strtotime($post_data['created_at']));
    $day = date('d', strtotime($post_data['created_at']));
    
    $post_dir = POSTS_PATH . "/$year/$month/$day";
    if (!is_dir($post_dir)) {
        if (!mkdir($post_dir, 0755, true)) {
            error_log("Failed to create directory: $post_dir");
            return false;
        }
    }
    
    $post_file = $post_dir . '/' . $post_data['slug'] . '.json';
    $result = file_put_contents($post_file, json_encode($post_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
    
    if ($result === false) {
        error_log("Failed to write post file: $post_file");
        return false;
    }
    
    error_log("Post saved successfully to: $post_file");
    return $result;
}

// 评论相关函数
function getComments($post_id) {
    $comment_file = COMMENTS_PATH . "/$post_id.json";
    if (file_exists($comment_file)) {
        $comments = json_decode(file_get_contents($comment_file), true);
        return array_filter($comments, function($comment) {
            return $comment['status'] === 'approved';
        });
    }
    return [];
}

function addComment($post_id, $nickname, $content, $email = '') {
    $comment_file = COMMENTS_PATH . "/$post_id.json";
    $comments = [];
    
    if (file_exists($comment_file)) {
        $comments = json_decode(file_get_contents($comment_file), true);
    }
    
    $settings = getSettings();
    
    $new_comment = [
        'id' => uniqid(),
        'nickname' => $nickname,
        'content' => $content,
        'email' => $email,
        'status' => $settings['comment']['auto_approve'] ? 'approved' : 'pending',
        'created_at' => date('Y-m-d H:i:s'),
        'ip' => $_SERVER['REMOTE_ADDR']
    ];
    
    $comments[] = $new_comment;
    
    return file_put_contents($comment_file, json_encode($comments, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

function approveComment($post_id, $comment_id) {
    $comment_file = COMMENTS_PATH . "/$post_id.json";
    if (file_exists($comment_file)) {
        $comments = json_decode(file_get_contents($comment_file), true);
        foreach ($comments as &$comment) {
            if ($comment['id'] === $comment_id) {
                $comment['status'] = 'approved';
                break;
            }
        }
        return file_put_contents($comment_file, json_encode($comments, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
    }
    return false;
}

function deleteComment($post_id, $comment_id) {
    $comment_file = COMMENTS_PATH . "/$post_id.json";
    if (file_exists($comment_file)) {
        $comments = json_decode(file_get_contents($comment_file), true);
        $comments = array_filter($comments, function($comment) use ($comment_id) {
            return $comment['id'] !== $comment_id;
        });
        return file_put_contents($comment_file, json_encode(array_values($comments), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
    }
    return false;
}

// 工具函数
function generateSlug($title) {
    return preg_replace('/[^a-zA-Z0-9\-_]/', '', str_replace(' ', '-', strtolower($title)));
}

function formatDate($date) {
    return date('Y年m月d日 H:i', strtotime($date));
}

function sanitizeInput($input) {
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}

function truncateText($text, $length = 100) {
    if (mb_strlen($text) <= $length) {
        return $text;
    }
    return mb_substr($text, 0, $length) . '...';
}

// 设置相关函数
function getSettings() {
    $settings_file = DATA_PATH . '/settings.json';
    if (file_exists($settings_file)) {
        return json_decode(file_get_contents($settings_file), true);
    }
    
    // 返回默认设置
    return [
        'site' => [
            'name' => '个人朋友圈',
            'description' => '记录生活点滴',
            'timezone' => 'Asia/Shanghai'
        ],
        'email' => [
            'smtp_host' => 'smtp.mxhichina.com',
            'smtp_port' => 465,
            'smtp_secure' => 'ssl',
            'smtp_username' => '',
            'smtp_password' => '',
            'from_email' => '',
            'from_name' => '个人朋友圈'
        ],
        'comment' => [
            'require_email_verification' => true,
            'auto_approve' => false,
            'verification_code_length' => 6,
            'verification_code_expire' => 300
        ]
    ];
}

function saveSettings($settings) {
    $settings_file = DATA_PATH . '/settings.json';
    return file_put_contents($settings_file, json_encode($settings, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

// 验证码相关函数
function generateVerificationCode($length = 6) {
    return str_pad(random_int(0, pow(10, $length) - 1), $length, '0', STR_PAD_LEFT);
}

function saveVerificationCode($email, $code) {
    $verification_file = DATA_PATH . '/verification_codes/' . md5($email) . '.json';
    $data = [
        'email' => $email,
        'code' => $code,
        'created_at' => time(),
        'expire_at' => time() + getSettings()['comment']['verification_code_expire']
    ];
    return file_put_contents($verification_file, json_encode($data));
}

function verifyCode($email, $code) {
    $verification_file = DATA_PATH . '/verification_codes/' . md5($email) . '.json';
    if (!file_exists($verification_file)) {
        return false;
    }
    
    $data = json_decode(file_get_contents($verification_file), true);
    if ($data['code'] === $code && time() <= $data['expire_at']) {
        unlink($verification_file); // 验证成功后删除验证码
        return true;
    }
    
    return false;
}

// 邮件发送函数
function sendVerificationEmail($email, $code) {
    $settings = getSettings();
    
    // 如果邮件配置不完整，返回false
    if (empty($settings['email']['smtp_host']) || empty($settings['email']['smtp_username']) || empty($settings['email']['smtp_password'])) {
        return false;
    }
    
    $subject = '邮箱验证码 - ' . $settings['site']['name'];
    $message = "您的验证码是：{$code}\n\n验证码有效期为 " . ($settings['comment']['verification_code_expire'] / 60) . " 分钟。\n\n如果这不是您的操作，请忽略此邮件。";
    
    $headers = [
        'From: ' . $settings['email']['from_name'] . ' <' . $settings['email']['from_email'] . '>',
        'Reply-To: ' . $settings['email']['from_email'],
        'Content-Type: text/plain; charset=UTF-8'
    ];
    
    // 简单的邮件发送（生产环境建议使用PHPMailer等库）
    return mail($email, $subject, $message, implode("\r\n", $headers));
}

// 评论管理函数
function updateCommentStatus($post_id, $comment_id, $status) {
    $comment_file = COMMENTS_PATH . "/$post_id.json";
    if (!file_exists($comment_file)) {
        return false;
    }
    
    $comments = json_decode(file_get_contents($comment_file), true);
    foreach ($comments as &$comment) {
        if ($comment['id'] === $comment_id) {
            $comment['status'] = $status;
            break;
        }
    }
    
    return file_put_contents($comment_file, json_encode($comments, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

// 文章管理函数
function deletePost($post_id) {
    // 查找文章文件
    $years = glob(POSTS_PATH . '/*', GLOB_ONLYDIR);
    
    foreach ($years as $year_dir) {
        $months = glob($year_dir . '/*', GLOB_ONLYDIR);
        foreach ($months as $month_dir) {
            $days = glob($month_dir . '/*', GLOB_ONLYDIR);
            foreach ($days as $day_dir) {
                $post_files = glob($day_dir . '/*.json');
                foreach ($post_files as $post_file) {
                    $post_data = json_decode(file_get_contents($post_file), true);
                    if ($post_data && isset($post_data['id']) && $post_data['id'] === $post_id) {
                        // 删除文章文件
                        if (unlink($post_file)) {
                            // 删除相关评论
                            $comment_file = COMMENTS_PATH . "/$post_id.json";
                            if (file_exists($comment_file)) {
                                unlink($comment_file);
                            }
                            return true;
                        }
                        return false;
                    }
                }
            }
        }
    }
    
    return false;
}

function updatePostStatus($post_id, $status) {
    // 查找文章文件
    $years = glob(POSTS_PATH . '/*', GLOB_ONLYDIR);
    
    foreach ($years as $year_dir) {
        $months = glob($year_dir . '/*', GLOB_ONLYDIR);
        foreach ($months as $month_dir) {
            $days = glob($month_dir . '/*', GLOB_ONLYDIR);
            foreach ($days as $day_dir) {
                $post_files = glob($day_dir . '/*.json');
                foreach ($post_files as $post_file) {
                    $post_data = json_decode(file_get_contents($post_file), true);
                    if ($post_data && isset($post_data['id']) && $post_data['id'] === $post_id) {
                        $post_data['status'] = $status;
                        return file_put_contents($post_file, json_encode($post_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
                    }
                }
            }
        }
    }
    
    return false;
}

function getAllComments() {
    $all_comments = [];
    $comment_files = glob(COMMENTS_PATH . '/*.json');
    
    foreach ($comment_files as $file) {
        $post_id = basename($file, '.json');
        $comments = json_decode(file_get_contents($file), true);
        
        if ($comments) {
            foreach ($comments as $comment) {
                $comment['post_id'] = $post_id;
                // 尝试获取文章标题
                $post_file = POSTS_PATH . "/$post_id.json";
                if (file_exists($post_file)) {
                    $post = json_decode(file_get_contents($post_file), true);
                    $comment['post_title'] = $post['title'] ?? $post_id;
                }
                $all_comments[] = $comment;
            }
        }
    }
    
    // 按时间倒序排列
    usort($all_comments, function($a, $b) {
        return strtotime($b['created_at']) - strtotime($a['created_at']);
    });
    
    return $all_comments;
}

// 获取网站名称
function getSiteName() {
    $settings = getSettings();
    if ($settings && isset($settings['site']['name'])) {
        return $settings['site']['name'];
    }
    return SITE_NAME; // 回退到默认值
}

// 获取网站描述
function getSiteDescription() {
    $settings = getSettings();
    if ($settings && isset($settings['site']['description'])) {
        return $settings['site']['description'];
    }
    return SITE_DESCRIPTION; // 回退到默认值
}

// 获取背景图片路径
function getBackgroundImage() {
    // 从settings.json获取当前背景图文件名
    $settings = getSettings();
    if ($settings && isset($settings['site']['current_background'])) {
        $filename = $settings['site']['current_background'];
        $file_path = __DIR__ . '/../src/' . $filename;
        if (file_exists($file_path)) {
            return '/src/' . $filename;
        }
    }
    
    // 如果设置中没有或文件不存在，查找默认文件
    $dir = __DIR__ . '/../src/';
    $extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    
    foreach ($extensions as $ext) {
        if (file_exists($dir . 'backpic.' . $ext)) {
            return '/src/backpic.' . $ext;
        }
    }
    
    // 如果都没有找到，返回默认背景图
    return '/src/backpic.jpg';
}

// 获取头像图片路径
function getAvatarImage() {
    // 从settings.json获取当前头像文件名
    $settings = getSettings();
    if ($settings && isset($settings['site']['current_avatar'])) {
        $filename = $settings['site']['current_avatar'];
        $file_path = __DIR__ . '/../src/' . $filename;
        if (file_exists($file_path)) {
            return '/src/' . $filename;
        }
    }
    
    // 如果设置中没有或文件不存在，查找默认文件
    $dir = __DIR__ . '/../src/';
    $extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    
    foreach ($extensions as $ext) {
        if (file_exists($dir . 'avatar.' . $ext)) {
            return '/src/avatar.' . $ext;
        }
    }
    
    // 如果都没有找到，返回默认头像
    return '/src/avatar.png';
}
?>
