<?php
// admin_functions.php
session_start();
include('config.php');

// Function to log admin activity
function logAdminActivity($admin_id, $action, $description = null, $module = null, $affected_id = null, $affected_table = null) {
    global $conn;
    
    // Get admin details
    $admin_sql = "SELECT name, role FROM admins WHERE id = $admin_id";
    $admin_result = mysqli_query($conn, $admin_sql);
    
    if ($admin_result && mysqli_num_rows($admin_result) > 0) {
        $admin = mysqli_fetch_assoc($admin_result);
        $admin_name = mysqli_real_escape_string($conn, $admin['name']);
        $admin_role = $admin['role'];
        
        // Get IP and User Agent
        $ip_address = $_SERVER['REMOTE_ADDR'];
        $user_agent = mysqli_real_escape_string($conn, $_SERVER['HTTP_USER_AGENT']);
        
        // Escape other inputs
        $action = mysqli_real_escape_string($conn, $action);
        $description = mysqli_real_escape_string($conn, $description);
        $module = mysqli_real_escape_string($conn, $module);
        
        // Insert activity log
        $sql = "INSERT INTO admin_activities (admin_id, admin_name, admin_role, action, description, module, ip_address, user_agent, affected_id, affected_table) 
                VALUES ($admin_id, '$admin_name', '$admin_role', '$action', '$description', '$module', '$ip_address', '$user_agent', $affected_id, '$affected_table')";
        
        return mysqli_query($conn, $sql);
    }
    
    return false;
}

// Function to check admin permission
function checkAdminPermission($module, $permission_type) {
    global $conn;
    
    if (!isset($_SESSION['admin_id']) || !isset($_SESSION['admin_role'])) {
        return false;
    }
    
    $admin_role = $_SESSION['admin_role'];
    
    $sql = "SELECT $permission_type as permission 
            FROM admin_permissions 
            WHERE role = '$admin_role' 
            AND module = '$module' 
            LIMIT 1";
    
    $result = mysqli_query($conn, $sql);
    
    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        return $row['permission'] == 1;
    }
    
    return false;
}

// Function to get admin permissions for a module
function getAdminPermissions($module) {
    global $conn;
    
    if (!isset($_SESSION['admin_id']) || !isset($_SESSION['admin_role'])) {
        return array();
    }
    
    $admin_role = $_SESSION['admin_role'];
    
    $sql = "SELECT can_view, can_create, can_edit, can_delete, can_approve, can_export 
            FROM admin_permissions 
            WHERE role = '$admin_role' 
            AND module = '$module' 
            LIMIT 1";
    
    $result = mysqli_query($conn, $sql);
    
    if ($result && mysqli_num_rows($result) > 0) {
        return mysqli_fetch_assoc($result);
    }
    
    return array(
        'can_view' => 0,
        'can_create' => 0,
        'can_edit' => 0,
        'can_delete' => 0,
        'can_approve' => 0,
        'can_export' => 0
    );
}

// Function to check if admin can access a page
function checkPageAccess($module) {
    if (!checkAdminPermission($module, 'can_view')) {
        $_SESSION['error_message'] = "You don't have permission to access this page.";
        header('Location: index.php');
        exit();
    }
}

// Function to get recent admin activities
function getRecentAdminActivities($limit = 10) {
    global $conn;
    
    $sql = "SELECT a.*, ad.name as admin_name, ad.role as admin_role
            FROM admin_activities a
            LEFT JOIN admins ad ON a.admin_id = ad.id
            ORDER BY a.created_at DESC
            LIMIT $limit";
    
    $result = mysqli_query($conn, $sql);
    $activities = array();
    
    while ($row = mysqli_fetch_assoc($result)) {
        $activities[] = $row;
    }
    
    return $activities;
}

// Function to get admin activity statistics
function getAdminActivityStats($admin_id = null, $days = 30) {
    global $conn;
    
    $date_filter = date('Y-m-d', strtotime("-$days days"));
    
    $where_clause = "WHERE created_at >= '$date_filter'";
    if ($admin_id) {
        $where_clause .= " AND admin_id = $admin_id";
    }
    
    $sql = "SELECT 
            COUNT(*) as total_activities,
            COUNT(DISTINCT admin_id) as active_admins,
            DATE(created_at) as activity_date,
            COUNT(*) as daily_count
            FROM admin_activities 
            $where_clause
            GROUP BY DATE(created_at)
            ORDER BY activity_date DESC";
    
    $result = mysqli_query($conn, $sql);
    $stats = array();
    
    while ($row = mysqli_fetch_assoc($result)) {
        $stats[] = $row;
    }
    
    return $stats;
}

// Function to update admin last login
function updateAdminLastLogin($admin_id) {
    global $conn;
    
    $sql = "UPDATE admins SET last_login = NOW() WHERE id = $admin_id";
    return mysqli_query($conn, $sql);
}
?>