<?php
// 包含数据库连接函数文件
require_once __DIR__ . '/db.php';

// 检查管理员登录状态
function is_admin_logged_in() {
    return isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true;
}

// 获取所有分类
function get_all_categories() {
    $conn = db_connect();
    
    // 检查categories表是否存在
    $table_check = $conn->query("SHOW TABLES LIKE 'categories'");
    if ($table_check->num_rows == 0) {
        // 表不存在，返回空数组
        $conn->close();
        return [];
    }
    
    $sql = "SELECT * FROM categories ORDER BY sort_order ASC";
    $result = $conn->query($sql);
    $categories = [];
    
    if ($result && $result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $categories[] = $row;
        }
    }
    
    $conn->close();
    return $categories;
}

// 获取分类下的所有链接
function get_links_by_category($category_id) {
    $conn = db_connect();
    $category_id = (int)$category_id;
    
    // 检查links表是否存在
    $table_check = $conn->query("SHOW TABLES LIKE 'links'");
    if ($table_check->num_rows == 0) {
        // 表不存在，返回空数组
        $conn->close();
        return [];
    }
    
    $sql = "SELECT * FROM links WHERE category_id = $category_id ORDER BY sort_order ASC";
    $result = $conn->query($sql);
    $links = [];
    
    if ($result && $result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $links[] = $row;
        }
    }
    
    $conn->close();
    return $links;
}

// 获取网站设置
function get_site_settings() {
    // 预定义返回的默认设置
    $default_settings = array(
        'site_title' => '导航网站',
        'site_description' => '一个简洁优雅的个人导航网站',
        'announcement' => '欢迎使用导航网站',
        'footer_text' => '© ' . date('Y') . ' 导航网站 All Rights Reserved'
    );
    
    try {
        $conn = db_connect();
        
        // 检查表是否存在
        $check_result = $conn->query("SHOW TABLES LIKE 'settings'");
        if (!$check_result || $check_result->num_rows == 0) {
            $conn->close();
            error_log("Settings table does not exist");
            return $default_settings;
        }
        
        // 尝试直接查询，根据当前表结构自动处理
        $settings = array();
        
        // 首先尝试新表结构（有id字段的单行多列格式）
        $sql1 = "SELECT * FROM settings LIMIT 1";
        $result1 = $conn->query($sql1);
        
        if ($result1 && $result1->num_rows > 0) {
            // 成功获取到数据，采用新表结构
            $settings = $result1->fetch_assoc();
            $conn->close();
            return $settings;
        }
        
        // 再尝试旧表结构（name-value对格式）
        $sql2 = "SELECT name, value FROM settings";
        $result2 = $conn->query($sql2);
        
        if ($result2 && $result2->num_rows > 0) {
            while ($row = $result2->fetch_assoc()) {
                $settings[$row['name']] = $row['value'];
            }
            
            if (!empty($settings)) {
                $conn->close();
                return $settings;
            }
        }
        
        // 尝试创建新的设置表
        $create_sql = "CREATE TABLE IF NOT EXISTS settings (
            id INT AUTO_INCREMENT PRIMARY KEY,
            site_title VARCHAR(255) DEFAULT '导航网站',
            site_description TEXT,
            announcement TEXT,
            footer_text TEXT,
            background_image VARCHAR(255),
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
        
        if ($conn->query($create_sql)) {
            // 插入默认设置
            $insert_sql = "INSERT INTO settings (site_title, site_description, announcement, footer_text) 
                           VALUES ('导航网站', '一个简洁优雅的个人导航网站', '欢迎使用导航网站', '© " . date('Y') . " 导航网站 All Rights Reserved')";
            
            if ($conn->query($insert_sql)) {
                // 查询插入的设置
                $new_result = $conn->query("SELECT * FROM settings LIMIT 1");
                if ($new_result && $new_result->num_rows > 0) {
                    $settings = $new_result->fetch_assoc();
                    $conn->close();
                    return $settings;
                }
            }
        }
        
        // 如果都失败，使用默认设置
        $conn->close();
        return $default_settings;
    } catch (Exception $e) {
        error_log("Error in get_site_settings: " . $e->getMessage());
        return $default_settings;
    }
}

// 更新网站设置
function update_site_settings($data) {
    $conn = db_connect();
    $site_title = clean($data['site_title']);
    $site_description = clean($data['site_description']);
    $announcement = clean($data['announcement']);
    $footer_text = clean($data['footer_text']);
    
    // 检查settings表结构（查看是否有id字段）
    $result = $conn->query("SHOW COLUMNS FROM settings LIKE 'id'");
    
    if ($result && $result->num_rows > 0) {
        // 表有id字段，使用单行多列格式更新
        // 检查是否有现有数据
        $check = $conn->query("SELECT id FROM settings LIMIT 1");
        if ($check && $check->num_rows > 0) {
            $row = $check->fetch_assoc();
            $settings_id = $row['id'];
            $sql = "UPDATE settings SET 
                    site_title = '$site_title',
                    site_description = '$site_description',
                    announcement = '$announcement',
                    footer_text = '$footer_text'
                    WHERE id = $settings_id";
        } else {
            $sql = "INSERT INTO settings (site_title, site_description, announcement, footer_text) 
                    VALUES ('$site_title', '$site_description', '$announcement', '$footer_text')";
        }
        $result = $conn->query($sql);
    } else {
        // 表使用name-value键值对格式
        $settings = [
            'site_title' => $site_title,
            'site_description' => $site_description,
            'announcement' => $announcement,
            'footer_text' => $footer_text
        ];
        
        // 使用预处理语句更新每个设置
        $stmt = $conn->prepare("INSERT INTO settings (name, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value = ?");
        $result = true;
        
        foreach ($settings as $name => $value) {
            $stmt->bind_param("sss", $name, $value, $value);
            if (!$stmt->execute()) {
                $result = false;
                break;
            }
        }
        
        $stmt->close();
    }
    
    $conn->close();
    return $result;
}

// 获取统计数据
function get_statistics() {
    // 默认统计数据
    $stats = array(
        'categories_count' => 0,
        'links_count' => 0
    );
    
    try {
        $conn = db_connect();
        
        // 检查categories表是否存在
        $check_categories = $conn->query("SHOW TABLES LIKE 'categories'");
        if ($check_categories && $check_categories->num_rows > 0) {
            // 获取分类总数
            $sql = "SELECT COUNT(*) as total FROM categories";
            $result = $conn->query($sql);
            if ($result && $result->num_rows > 0) {
                $row = $result->fetch_assoc();
                $stats['categories_count'] = $row['total'];
            }
        }
        
        // 检查links表是否存在
        $check_links = $conn->query("SHOW TABLES LIKE 'links'");
        if ($check_links && $check_links->num_rows > 0) {
            // 获取链接总数
            $sql = "SELECT COUNT(*) as total FROM links";
            $result = $conn->query($sql);
            if ($result && $result->num_rows > 0) {
                $row = $result->fetch_assoc();
                $stats['links_count'] = $row['total'];
            }
        }
        
        $conn->close();
    } catch (Exception $e) {
        error_log("Error in get_statistics: " . $e->getMessage());
    }
    
    return $stats;
}

// 验证管理员密码
function verify_admin_password($password) {
    try {
        $conn = db_connect();
        $hashed_password = hash('sha256', $password . SALT);
        
        // 检查admin表是否存在
        $check_table = $conn->query("SHOW TABLES LIKE 'admin'");
        if (!$check_table || $check_table->num_rows == 0) {
            error_log("Admin table does not exist");
            $conn->close();
            return false;
        }
        
        // 尝试准备语句
        $stmt = $conn->prepare("SELECT * FROM admin WHERE password = ? LIMIT 1");
        if (!$stmt) {
            error_log("Prepare statement failed: " . $conn->error);
            $conn->close();
            return false;
        }
        
        $stmt->bind_param("s", $hashed_password);
        if (!$stmt->execute()) {
            error_log("Execute statement failed: " . $stmt->error);
            $stmt->close();
            $conn->close();
            return false;
        }
        
        $result = $stmt->get_result();
        $found = ($result && $result->num_rows > 0);
        $stmt->close();
        $conn->close();
        return $found;
    } catch (Exception $e) {
        error_log("Error in verify_admin_password: " . $e->getMessage());
        return false;
    }
}

// 更新管理员密码
function update_admin_password($new_password) {
    try {
        $conn = db_connect();
        $hashed_password = hash('sha256', $new_password . SALT);
        
        // 检查admin表是否存在
        $check_table = $conn->query("SHOW TABLES LIKE 'admin'");
        if (!$check_table || $check_table->num_rows == 0) {
            error_log("Admin table does not exist");
            $conn->close();
            return false;
        }
        
        // 检查是否有管理员账户
        $id_check = $conn->query("SELECT id FROM admin LIMIT 1");
        if (!$id_check || $id_check->num_rows == 0) {
            // 没有管理员账户，尝试创建一个
            $insert_result = $conn->query("INSERT INTO admin (username, password) VALUES ('admin', '$hashed_password')");
            $success = ($insert_result !== false);
            $conn->close();
            return $success;
        }
        
        $row = $id_check->fetch_assoc();
        $admin_id = $row['id'];
        
        // 更新密码
        $stmt = $conn->prepare("UPDATE admin SET password = ? WHERE id = ?");
        if (!$stmt) {
            error_log("Prepare statement failed: " . $conn->error);
            $conn->close();
            return false;
        }
        
        $stmt->bind_param("si", $hashed_password, $admin_id);
        $success = $stmt->execute();
        if (!$success) {
            error_log("Execute statement failed: " . $stmt->error);
        }
        
        $stmt->close();
        $conn->close();
        return $success;
    } catch (Exception $e) {
        error_log("Error in update_admin_password: " . $e->getMessage());
        return false;
    }
}

// 记录访问日志
function log_visit($page) {
    $conn = db_connect();
    
    // 检查visit_logs表是否存在
    $table_check = $conn->query("SHOW TABLES LIKE 'visit_logs'");
    if ($table_check->num_rows == 0) {
        // 表不存在，尝试创建
        $create_sql = "CREATE TABLE IF NOT EXISTS visit_logs (
            id INT AUTO_INCREMENT PRIMARY KEY,
            ip VARCHAR(45) NOT NULL,
            user_agent VARCHAR(255) NOT NULL,
            page VARCHAR(100) NOT NULL,
            visit_time DATETIME NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
        
        $conn->query($create_sql);
        
        // 再次检查表是否创建成功
        $check_again = $conn->query("SHOW TABLES LIKE 'visit_logs'");
        if ($check_again->num_rows == 0) {
            // 创建失败，简单记录到错误日志并返回
            error_log("无法创建visit_logs表");
            $conn->close();
            return;
        }
    }
    
    $ip = $_SERVER['REMOTE_ADDR'];
    $user_agent = clean($_SERVER['HTTP_USER_AGENT']);
    $timestamp = date('Y-m-d H:i:s');
    
    // 使用预处理语句防止SQL注入
    $stmt = $conn->prepare("INSERT INTO visit_logs (ip, user_agent, page, visit_time) VALUES (?, ?, ?, ?)");
    if ($stmt) {
        $stmt->bind_param("ssss", $ip, $user_agent, $page, $timestamp);
        $stmt->execute();
        $stmt->close();
    } else {
        // 记录错误
        error_log("无法预处理INSERT语句: " . $conn->error);
    }
    
    $conn->close();
}

?>
