<?php
/**
 * سجل النشاطات - تسجيل من فعل ماذا ومتى
 * activity_log - Who did what and when
 */

function logActivity($action, $entity_type, $entity_id = null, $details = '', $user_id_override = null) {
    global $conn;
    if (!isset($conn)) return false;

    $user_id = $user_id_override !== null ? $user_id_override : ($_SESSION['user_id'] ?? null);
    $username = $_SESSION['username'] ?? null;
    if ($user_id && !$username) {
        $r = $conn->query("SELECT username FROM users WHERE id = " . (int)$user_id);
        if ($r && $row = $r->fetch_assoc()) $username = $row['username'];
    }
    $ip = $_SERVER['REMOTE_ADDR'] ?? null;

    $stmt = $conn->prepare("INSERT INTO activity_log (user_id, username, action, entity_type, entity_id, details, ip_address) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("isssiss", $user_id, $username, $action, $entity_type, $entity_id, $details, $ip);
    return $stmt->execute();
}
