<?php
/**
 * Audit Log / Activity History
 * GET /v1/audit-log
 * Returns paginated activity history
 */

use App\Core\Database;
use App\Middleware\AuthMiddleware;

$decoded = AuthMiddleware::check();
$db = Database::getInstance();

$tenantId = $decoded['tenant_id'];
$role = $decoded['role'];
$page = max(1, (int)($_GET['page'] ?? 1));
$limit = min(50, max(10, (int)($_GET['limit'] ?? 20)));
$offset = ($page - 1) * $limit;
$entityType = $_GET['entity_type'] ?? null;
$action = $_GET['action'] ?? null;

$where = [];
$params = [];

if ($role !== 'super_admin') {
    $where[] = 'a.tenant_id = ?';
    $params[] = $tenantId;
}

if ($entityType) {
    $where[] = 'a.entity_type = ?';
    $params[] = $entityType;
}

if ($action) {
    $where[] = 'a.action LIKE ?';
    $params[] = "%$action%";
}

$whereClause = $where ? 'WHERE ' . implode(' AND ', $where) : '';

try {
    // Total count
    $countStmt = $db->prepare("SELECT COUNT(*) FROM audit_logs a $whereClause");
    $countStmt->execute($params);
    $total = (int)$countStmt->fetchColumn();

    // Fetch logs
    $stmt = $db->prepare("
        SELECT a.*, u.name as user_name 
        FROM audit_logs a
        LEFT JOIN users u ON a.user_id = u.id
        $whereClause
        ORDER BY a.created_at DESC
        LIMIT $limit OFFSET $offset
    ");
    $stmt->execute($params);
    $logs = $stmt->fetchAll();

    // Format logs
    foreach ($logs as &$log) {
        // Decrypt user name if encrypted
        if (!empty($log['user_name'])) {
            $dec = \App\Core\Encryption::decrypt($log['user_name']);
            $log['user_name'] = ($dec !== false && $dec !== null) ? $dec : $log['user_name'];
        }
        $log['old_values'] = json_decode($log['old_data'] ?? '{}', true);
        $log['details'] = json_decode($log['new_data'] ?? '{}', true);
        unset($log['old_data'], $log['new_data'], $log['user_agent'], $log['ip_address']);
        
        // Generate human-readable summary
        $a = $log['action'] ?? '';
        if (str_starts_with($a, 'invoice.')) {
            $log['summary'] = match($a) {
                'invoice.approved' => 'تم اعتماد فاتورة',
                'invoice.updated' => 'تم تعديل فاتورة',
                'invoice.bulk_approved' => 'اعتماد جماعي',
                'invoice.uploaded' => 'تم رفع فاتورة',
                'invoice.extracted' => 'تم استخراج بيانات فاتورة',
                default => $a,
            };
        } elseif (str_starts_with($a, 'user.')) {
            $log['summary'] = match($a) {
                'user.created' => 'تم إنشاء مستخدم جديد',
                'user.updated' => 'تم تعديل بيانات مستخدم',
                'user.deleted' => 'تم حذف مستخدم',
                'user.login' => 'تسجيل دخول',
                default => $a,
            };
        } elseif (str_starts_with($a, 'company.')) {
            $log['summary'] = match($a) {
                'company.created' => 'تم إنشاء شركة جديدة',
                'company.updated' => 'تم تعديل بيانات شركة',
                default => $a,
            };
        } elseif (str_starts_with($a, 'payment.')) {
            $log['summary'] = match($a) {
                'payment.created' => 'تم إنشاء طلب دفع',
                'payment.uploaded' => 'تم رفع وصل دفع',
                'payment.approved' => 'تم اعتماد دفعة',
                default => $a,
            };
        } else {
            $log['summary'] = $a;
        }
    }
    unset($log);

    json_success([
        'logs' => $logs,
        'pagination' => [
            'page' => $page,
            'limit' => $limit,
            'total' => $total,
            'pages' => $total > 0 ? (int)ceil($total / $limit) : 1,
        ],
    ]);
} catch (\Exception $e) {
    error_log("Audit log error: " . $e->getMessage());
    json_error('خطأ في جلب سجل النشاط: ' . $e->getMessage(), 500);
}
