<?php
/**
 * Unified Activity Logger for Admin and Vendor Portals
 */
function log_activity($action, $details = null, $portal = null)
{
    global $con;
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }

    // Determine Portal and User ID
    if ($portal === null) {
        if (isset($_SESSION['aid']) && !empty($_SESSION['aid'])) {
            $portal = 'admin';
            $user_id = intval($_SESSION['aid']);
        } elseif (isset($_SESSION['vendor_id']) && !empty($_SESSION['vendor_id'])) {
            $portal = 'vendor';
            // In vendor portal, the logged in user is the vendor's user record
            $user_id = isset($_SESSION['id']) ? intval($_SESSION['id']) : 0;
        } else {
            $portal = 'admin';
            $user_id = 0;
        }
    } else {
        if ($portal === 'admin') {
            $user_id = isset($_SESSION['aid']) ? intval($_SESSION['aid']) : 0;
        } else {
            $user_id = isset($_SESSION['id']) ? intval($_SESSION['id']) : 0;
        }
    }

    $action = mysqli_real_escape_string($con, $action);
    $details = mysqli_real_escape_string($con, $details);
    $ip = $_SERVER['REMOTE_ADDR'];
    $portal = mysqli_real_escape_string($con, $portal);

    $query = "INSERT INTO admin_activity_log (portal, admin_id, action, details, ip_address) 
              VALUES ('$portal', '$user_id', '$action', '$details', '$ip')";

    mysqli_query($con, $query);
}
?>