<?php
// 引入数据库配置
require_once 'config.php';

// 检查用户是否已登录
function isLoggedIn() {
    if (isset($_SESSION['admin_id']) && !empty($_SESSION['admin_id'])) {
        return true;
    }
    return false;
}

// 检查用户是否是超级管理员
function isSuperAdmin() {
    global $conn;
    if (isset($_SESSION['admin_id']) && !empty($_SESSION['admin_id'])) {
        $id = (int)$_SESSION['admin_id'];
        $sql = "SELECT role FROM admin WHERE id = $id LIMIT 1";
        $result = $conn->query($sql);
        
        if ($result && $result->num_rows > 0) {
            $row = $result->fetch_assoc();
            return $row['role'] === '超级管理员';
        }
    }
    return false;
}

// 重定向函数
function redirect($url) {
    header("Location: $url");
    exit;
}

// 显示错误消息
function showError($message) {
    return "<div class='alert alert-danger'>$message</div>";
}

// 显示成功消息
function showSuccess($message) {
    return "<div class='alert alert-success'>$message</div>";
}

// 分页函数
function getPagination($total, $perPage, $currentPage, $url) {
    $totalPages = ceil($total / $perPage);
    
    if ($totalPages <= 1) {
        return '';
    }
    
    $pagination = '<div class="pagination">';
    
    // 上一页
    if ($currentPage > 1) {
        $pagination .= '<a href="' . $url . '&page=' . ($currentPage - 1) . '">&laquo;</a>';
    } else {
        $pagination .= '<a class="disabled">&laquo;</a>';
    }
    
    // 页码
    $startPage = max(1, $currentPage - 2);
    $endPage = min($totalPages, $currentPage + 2);
    
    for ($i = $startPage; $i <= $endPage; $i++) {
        if ($i == $currentPage) {
            $pagination .= '<a class="active">' . $i . '</a>';
        } else {
            $pagination .= '<a href="' . $url . '&page=' . $i . '">' . $i . '</a>';
        }
    }
    
    // 下一页
    if ($currentPage < $totalPages) {
        $pagination .= '<a href="' . $url . '&page=' . ($currentPage + 1) . '">&raquo;</a>';
    } else {
        $pagination .= '<a class="disabled">&raquo;</a>';
    }
    
    $pagination .= '</div>';
    
    return $pagination;
}

// 上传图片函数
function uploadImage($file, $targetDir = '../uploads/photos/') {
    // 检查上传错误
    if ($file['error'] !== UPLOAD_ERR_OK) {
        return [
            'success' => false,
            'message' => '上传失败，错误码: ' . $file['error']
        ];
    }
    
    // 检查文件类型
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    if (!in_array($file['type'], $allowedTypes)) {
        return [
            'success' => false,
            'message' => '只允许上传JPG, PNG或GIF图片'
        ];
    }
    
    // 检查文件大小 (限制为5MB)
    if ($file['size'] > 5 * 1024 * 1024) {
        return [
            'success' => false,
            'message' => '文件大小不能超过5MB'
        ];
    }
    
    // 创建目标目录（如果不存在）
    if (!file_exists($targetDir)) {
        mkdir($targetDir, 0777, true);
    }
    
    // 生成唯一文件名
    $fileExtension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $newFileName = uniqid() . '_' . time() . '.' . $fileExtension;
    $targetPath = $targetDir . $newFileName;
    
    // 移动上传的文件
    if (move_uploaded_file($file['tmp_name'], $targetPath)) {
        return [
            'success' => true,
            'file_path' => str_replace('../', '', $targetPath)
        ];
    } else {
        return [
            'success' => false,
            'message' => '文件上传失败，请重试'
        ];
    }
}

// 获取即将到期的证件数量
function getExpiringDocumentsCount($conn) {
    $counts = [
        'visitor_permits' => 0,
        'entry_permits' => 0,
        'access_cards' => 0,
        'airport_passes' => 0,
        'restricted_area_passes' => 0,
        'vehicle_restricted_passes' => 0,
        'total' => 0
    ];
    
    $tables = [
        'visitor_permits', 
        'entry_permits', 
        'access_cards', 
        'airport_passes', 
        'restricted_area_passes', 
        'vehicle_restricted_passes'
    ];
    
    foreach ($tables as $table) {
        $sql = "SELECT COUNT(*) as count FROM $table WHERE status = '即将到期'";
        $result = $conn->query($sql);
        if ($result && $row = $result->fetch_assoc()) {
            $counts[$table] = (int)$row['count'];
            $counts['total'] += $counts[$table];
        }
    }
    
    return $counts;
}

// 获取已过期的证件数量
function getExpiredDocumentsCount($conn) {
    $counts = [
        'visitor_permits' => 0,
        'entry_permits' => 0,
        'access_cards' => 0,
        'airport_passes' => 0,
        'restricted_area_passes' => 0,
        'vehicle_restricted_passes' => 0,
        'total' => 0
    ];
    
    $tables = [
        'visitor_permits', 
        'entry_permits', 
        'access_cards', 
        'airport_passes', 
        'restricted_area_passes', 
        'vehicle_restricted_passes'
    ];
    
    foreach ($tables as $table) {
        $sql = "SELECT COUNT(*) as count FROM $table WHERE status = '已过期'";
        $result = $conn->query($sql);
        if ($result && $row = $result->fetch_assoc()) {
            $counts[$table] = (int)$row['count'];
            $counts['total'] += $counts[$table];
        }
    }
    
    return $counts;
}

// 获取证件总数
function getTotalDocumentsCount($conn) {
    $counts = [
        'visitor_permits' => 0,
        'entry_permits' => 0,
        'access_cards' => 0,
        'airport_passes' => 0,
        'restricted_area_passes' => 0,
        'vehicle_restricted_passes' => 0,
        'total' => 0
    ];
    
    $tables = [
        'visitor_permits', 
        'entry_permits', 
        'access_cards', 
        'airport_passes', 
        'restricted_area_passes', 
        'vehicle_restricted_passes'
    ];
    
    foreach ($tables as $table) {
        $sql = "SELECT COUNT(*) as count FROM $table";
        $result = $conn->query($sql);
        if ($result && $row = $result->fetch_assoc()) {
            $counts[$table] = (int)$row['count'];
            $counts['total'] += $counts[$table];
        }
    }
    
    return $counts;
}

// 获取人员数量
function getPersonnelCount($conn) {
    $sql = "SELECT COUNT(*) as count FROM personnel";
    $result = $conn->query($sql);
    if ($result && $row = $result->fetch_assoc()) {
        return (int)$row['count'];
    }
    return 0;
}

// 格式化日期显示
function formatDate($date) {
    if (empty($date) || $date == '0000-00-00') {
        return '';
    }
    return date('Y-m-d', strtotime($date));
}

// 获取证件状态CSS类
function getStatusClass($status) {
    switch ($status) {
        case '有效':
            return 'status-success';
        case '即将到期':
            return 'status-pending';
        case '已过期':
            return 'status-failed';
        case '已归还':
            return 'status-secondary';
        default:
            return '';
    }
}

// 检查并更新所有证件状态
function checkAndUpdateAllDocumentStatus($conn) {
    updateDocumentStatus($conn, 'visitor_permits');
    updateDocumentStatus($conn, 'entry_permits');
    updateDocumentStatus($conn, 'access_cards');
    updateDocumentStatus($conn, 'airport_passes');
    updateDocumentStatus($conn, 'restricted_area_passes');
    updateDocumentStatus($conn, 'vehicle_restricted_passes');
}

// 获取人员信息
function getPersonnelById($conn, $id) {
    $id = (int)$id;
    $sql = "SELECT * FROM personnel WHERE id = $id LIMIT 1";
    $result = $conn->query($sql);
    
    if ($result && $result->num_rows > 0) {
        return $result->fetch_assoc();
    }
    
    return null;
}

// 获取人员的所有证件信息
function getPersonnelDocuments($conn, $personnelId) {
    $personnelId = (int)$personnelId;
    $documents = [
        'visitor_permits' => [],
        'entry_permits' => [],
        'access_cards' => [],
        'airport_passes' => [],
        'restricted_area_passes' => [],
        'vehicle_restricted_passes' => []
    ];
    
    // 获取访客许可证
    $sql = "SELECT * FROM visitor_permits WHERE personnel_id = $personnelId ORDER BY expiry_date DESC";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $documents['visitor_permits'][] = $row;
        }
    }
    
    // 获取进入许可证
    $sql = "SELECT * FROM entry_permits WHERE personnel_id = $personnelId ORDER BY expiry_date DESC";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $documents['entry_permits'][] = $row;
        }
    }
    
    // 获取门禁卡
    $sql = "SELECT * FROM access_cards WHERE personnel_id = $personnelId ORDER BY expiry_date DESC";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $documents['access_cards'][] = $row;
        }
    }
    
    // 获取机场证
    $sql = "SELECT * FROM airport_passes WHERE personnel_id = $personnelId ORDER BY expiry_date DESC";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $documents['airport_passes'][] = $row;
        }
    }
    
    // 获取禁区证
    $sql = "SELECT * FROM restricted_area_passes WHERE personnel_id = $personnelId ORDER BY expiry_date DESC";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $documents['restricted_area_passes'][] = $row;
        }
    }
    
    // 获取车辆禁区证
    $sql = "SELECT * FROM vehicle_restricted_passes WHERE personnel_id = $personnelId ORDER BY expiry_date DESC";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $documents['vehicle_restricted_passes'][] = $row;
        }
    }
    
    return $documents;
}

// 搜索人员
function searchPersonnel($conn, $keyword, $page = 1, $perPage = 10) {
    $keyword = sanitize($conn, $keyword);
    $offset = ($page - 1) * $perPage;
    
    // 计算总记录数
    $countSql = "SELECT COUNT(*) as total FROM personnel 
                WHERE english_name LIKE '%$keyword%' 
                OR chinese_name LIKE '%$keyword%' 
                OR chinese_code LIKE '%$keyword%' 
                OR nickname LIKE '%$keyword%' 
                OR phone LIKE '%$keyword%' 
                OR id_passport LIKE '%$keyword%'";
    $countResult = $conn->query($countSql);
    $totalRecords = 0;
    
    if ($countResult && $row = $countResult->fetch_assoc()) {
        $totalRecords = (int)$row['total'];
    }
    
    // 获取分页数据
    $sql = "SELECT * FROM personnel 
            WHERE english_name LIKE '%$keyword%' 
            OR chinese_name LIKE '%$keyword%' 
            OR chinese_code LIKE '%$keyword%' 
            OR nickname LIKE '%$keyword%' 
            OR phone LIKE '%$keyword%' 
            OR id_passport LIKE '%$keyword%'
            ORDER BY id DESC
            LIMIT $offset, $perPage";
    
    $result = $conn->query($sql);
    $data = [];
    
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
    }
    
    return [
        'total' => $totalRecords,
        'data' => $data
    ];
}

// 获取所有即将到期的证件
function getAllExpiringDocuments($conn) {
    $expiringDocs = [];
    
    // 访客许可证
    $sql = "SELECT vp.*, p.chinese_name, p.english_name, p.phone, p.email 
            FROM visitor_permits vp 
            JOIN personnel p ON vp.personnel_id = p.id 
            WHERE vp.status = '即将到期'
            ORDER BY vp.expiry_date ASC";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $row['type'] = '访客许可证';
            $row['table'] = 'visitor_permits';
            $expiringDocs[] = $row;
        }
    }
    
    // 进入许可证
    $sql = "SELECT ep.*, p.chinese_name, p.english_name, p.phone, p.email 
            FROM entry_permits ep 
            JOIN personnel p ON ep.personnel_id = p.id 
            WHERE ep.status = '即将到期'
            ORDER BY ep.expiry_date ASC";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $row['type'] = '进入许可证';
            $row['table'] = 'entry_permits';
            $expiringDocs[] = $row;
        }
    }
    
    // 门禁卡
    $sql = "SELECT ac.*, p.chinese_name, p.english_name, p.phone, p.email 
            FROM access_cards ac 
            JOIN personnel p ON ac.personnel_id = p.id 
            WHERE ac.status = '即将到期'
            ORDER BY ac.expiry_date ASC";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $row['type'] = '门禁卡';
            $row['table'] = 'access_cards';
            $expiringDocs[] = $row;
        }
    }
    
    // 机场证
    $sql = "SELECT ap.*, p.chinese_name, p.english_name, p.phone, p.email 
            FROM airport_passes ap 
            JOIN personnel p ON ap.personnel_id = p.id 
            WHERE ap.status = '即将到期'
            ORDER BY ap.expiry_date ASC";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $row['type'] = '机场证';
            $row['table'] = 'airport_passes';
            $expiringDocs[] = $row;
        }
    }
    
    // 禁区证
    $sql = "SELECT rap.*, p.chinese_name, p.english_name, p.phone, p.email 
            FROM restricted_area_passes rap 
            JOIN personnel p ON rap.personnel_id = p.id 
            WHERE rap.status = '即将到期'
            ORDER BY rap.expiry_date ASC";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $row['type'] = '禁区证';
            $row['table'] = 'restricted_area_passes';
            $expiringDocs[] = $row;
        }
    }
    
    // 车辆禁区证
    $sql = "SELECT vrp.*, p.chinese_name, p.english_name, p.phone, p.email 
            FROM vehicle_restricted_passes vrp 
            JOIN personnel p ON vrp.personnel_id = p.id 
            WHERE vrp.status = '即将到期'
            ORDER BY vrp.expiry_date ASC";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $row['type'] = '车辆禁区证';
            $row['table'] = 'vehicle_restricted_passes';
            $expiringDocs[] = $row;
        }
    }
    
    return $expiringDocs;
}

// 获取所有已过期的证件
function getAllExpiredDocuments($conn) {
    $expiredDocs = [];
    
    // 访客许可证
    $sql = "SELECT vp.*, p.chinese_name, p.english_name, p.phone, p.email 
            FROM visitor_permits vp 
            JOIN personnel p ON vp.personnel_id = p.id 
            WHERE vp.status = '已过期'
            ORDER BY vp.expiry_date ASC";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $row['type'] = '访客许可证';
            $row['table'] = 'visitor_permits';
            $expiredDocs[] = $row;
        }
    }
    
    // 进入许可证
    $sql = "SELECT ep.*, p.chinese_name, p.english_name, p.phone, p.email 
            FROM entry_permits ep 
            JOIN personnel p ON ep.personnel_id = p.id 
            WHERE ep.status = '已过期'
            ORDER BY ep.expiry_date ASC";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $row['type'] = '进入许可证';
            $row['table'] = 'entry_permits';
            $expiredDocs[] = $row;
        }
    }
    
    // 门禁卡
    $sql = "SELECT ac.*, p.chinese_name, p.english_name, p.phone, p.email 
            FROM access_cards ac 
            JOIN personnel p ON ac.personnel_id = p.id 
            WHERE ac.status = '已过期'
            ORDER BY ac.expiry_date ASC";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $row['type'] = '门禁卡';
            $row['table'] = 'access_cards';
            $expiredDocs[] = $row;
        }
    }
    
    // 机场证
    $sql = "SELECT ap.*, p.chinese_name, p.english_name, p.phone, p.email 
            FROM airport_passes ap 
            JOIN personnel p ON ap.personnel_id = p.id 
            WHERE ap.status = '已过期'
            ORDER BY ap.expiry_date ASC";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $row['type'] = '机场证';
            $row['table'] = 'airport_passes';
            $expiredDocs[] = $row;
        }
    }
    
    // 禁区证
    $sql = "SELECT rap.*, p.chinese_name, p.english_name, p.phone, p.email 
            FROM restricted_area_passes rap 
            JOIN personnel p ON rap.personnel_id = p.id 
            WHERE rap.status = '已过期'
            ORDER BY rap.expiry_date ASC";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $row['type'] = '禁区证';
            $row['table'] = 'restricted_area_passes';
            $expiredDocs[] = $row;
        }
    }
    
    // 车辆禁区证
    $sql = "SELECT vrp.*, p.chinese_name, p.english_name, p.phone, p.email 
            FROM vehicle_restricted_passes vrp 
            JOIN personnel p ON vrp.personnel_id = p.id 
            WHERE vrp.status = '已过期'
            ORDER BY vrp.expiry_date ASC";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $row['type'] = '车辆禁区证';
            $row['table'] = 'vehicle_restricted_passes';
            $expiredDocs[] = $row;
        }
    }
    
    return $expiredDocs;
}
?>
