<?php
/**
 * audit_logger.php - Centralized audit trail logging utility
 * Include this in any admin page that needs to log actions.
 * 
 * Usage:
 *   audit_log($conn, 'order_approved', 'token_orders', $order_id, $user_id, $admin_id,
 *       json_encode($old), json_encode($new), 'Optional note');
 */

function audit_log($conn, $action_type, $target_table, $target_id, $user_id, $admin_id, $old_values = null, $new_values = null, $note = null)
{
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';

    $stmt = $conn->prepare(
        "INSERT INTO audit_log (action_type, target_table, target_id, user_id, admin_id, old_values, new_values, note, ip_address) 
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"
    );

    if (!$stmt)
        return 0; // Table may not exist yet

    $stmt->bind_param(
        "ssiiiisss",
        $action_type,
        $target_table,
        $target_id,
        $user_id,
        $admin_id,
        $old_values,
        $new_values,
        $note,
        $ip
    );

    $stmt->execute();
    return $conn->insert_id;
}

/**
 * Get audit history for a specific target
 */
function get_audit_history($conn, $target_table, $target_id, $limit = 50)
{
    $stmt = $conn->prepare(
        "SELECT al.*, 
                admin.org_name as admin_name,
                u.org_name as user_name
         FROM audit_log al
         LEFT JOIN users admin ON al.admin_id = admin.id
         LEFT JOIN users u ON al.user_id = u.id
         WHERE al.target_table = ? AND al.target_id = ?
         ORDER BY al.created_at DESC
         LIMIT ?"
    );
    if (!$stmt)
        return [];
    $stmt->bind_param("sii", $target_table, $target_id, $limit);
    $stmt->execute();
    return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
}

/**
 * Get all audit history for a user (as target)
 */
function get_user_audit_history($conn, $user_id, $limit = 100)
{
    $stmt = $conn->prepare(
        "SELECT al.*, 
                admin.org_name as admin_name
         FROM audit_log al
         LEFT JOIN users admin ON al.admin_id = admin.id
         WHERE al.user_id = ?
         ORDER BY al.created_at DESC
         LIMIT ?"
    );
    if (!$stmt)
        return [];
    $stmt->bind_param("ii", $user_id, $limit);
    $stmt->execute();
    return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
}
?>