<?php
/**
 * Get Audit Log Details
 * AJAX endpoint to fetch detailed log information
 */

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../includes/SecurityHelper.php';

// Check authentication - redirect to login if not logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ' . BASE_URL . '/login.php');
    exit;
}

// Check admin role - support both new and legacy session variables
$user_role = $user_role ?? $_SESSION['role'] ?? '';
if (!isset($_SESSION['user_id']) || ($user_role !== 'admin')) {
    http_response_code(403);
    die('❌ অ্যাক্সেস denied। আপনার এই পেজ দেখার অনুমতি নেই।<br><br>
    <a href="' . BASE_URL . '/login.php" class="btn btn-primary">লগইন পেজে যান</a>');
}

// Set content type to JSON
header('Content-Type: application/json');

// Get log ID
$log_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$log_id) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => '❌ লগ আইডি প্রয়োজন'
    ]);
    exit;
}

try {
    // First try to get from active audit_log
    $stmt = $pdo->prepare("
        SELECT 
            al.*,
            u.username,
            u.email,
            u.full_name
        FROM audit_log al
        LEFT JOIN users u ON al.user_id = u.id
        WHERE al.id = ?
    ");
    $stmt->execute([$log_id]);
    $log = $stmt->fetch();
    
    // If not found, check archive
    if (!$log) {
        $archive_stmt = $pdo->prepare("
            SELECT 
                ala.*,
                u.username,
                u.email,
                u.full_name
            FROM audit_log_archive ala
            LEFT JOIN users u ON ala.user_id = u.id
            WHERE ala.id = ?
        ");
        $archive_stmt->execute([$log_id]);
        $log = $archive_stmt->fetch();
        
        if ($log) {
            $log['is_archived'] = true;
        }
    } else {
        $log['is_archived'] = false;
    }
    
    if (!$log) {
        http_response_code(404);
        echo json_encode([
            'success' => false,
            'message' => '❌ লগ খুঁজে পাওয়া যায়নি'
        ]);
        exit;
    }
    
    // Decode JSON values
    $old_values = null;
    $new_values = null;
    
    if (!empty($log['old_values'])) {
        $old_values = json_decode($log['old_values'], true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            $old_values = $log['old_values']; // Return as string if not valid JSON
        }
    }
    
    if (!empty($log['new_values'])) {
        $new_values = json_decode($log['new_values'], true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            $new_values = $log['new_values']; // Return as string if not valid JSON
        }
    }
    
    // Format response
    $response = [
        'success' => true,
        'data' => [
            'id' => $log['id'],
            'action' => $log['action'],
            'table_name' => $log['table_name'],
            'record_id' => $log['record_id'],
            'user_id' => $log['user_id'],
            'username' => $log['username'] ?? 'System',
            'email' => $log['email'] ?? null,
            'full_name' => $log['full_name'] ?? null,
            'user_role' => $log['user_role'],
            'ip_address' => $log['ip_address'],
            'user_agent' => $log['user_agent'],
            'session_id' => $log['session_id'],
            'created_at' => $log['created_at'],
            'is_archived' => $log['is_archived'],
            'old_values' => $old_values,
            'new_values' => $new_values
        ]
    ];
    
    // If archived, include archived_at
    if ($log['is_archived'] && isset($log['archived_at'])) {
        $response['data']['archived_at'] = $log['archived_at'];
    }
    
    // Log this view action (but not for every request to avoid spam)
    if (rand(1, 10) === 1) { // Log 10% of views
        $view_log_stmt = $pdo->prepare("
            INSERT INTO audit_log (user_id, user_role, action, table_name, record_id, ip_address, user_agent, created_at)
            VALUES (?, ?, 'VIEW_DETAILS', ?, ?, ?, ?, NOW())
        ");
        $view_log_stmt->execute([
            $_SESSION['user_id'],
            $user_role,
            $log['is_archived'] ? 'audit_log_archive' : 'audit_log',
            $log_id,
            $_SERVER['REMOTE_ADDR'] ?? 'unknown',
            $_SERVER['HTTP_USER_AGENT'] ?? 'unknown'
        ]);
    }
    
    echo json_encode($response);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => '❌ ত্রুটি: ' . $e->getMessage()
    ]);
    
    // Log error
    SecurityHelper::logEvent('AUDIT_LOG_VIEW_ERROR', [
        'error' => $e->getMessage(),
        'log_id' => $log_id,
        'user_id' => $_SESSION['user_id'] ?? null
    ]);
}

exit;
