<?php

namespace App\Core;

use PDO;

class AuditLog
{
    private PDO $db;

    public function __construct(PDO $db)
    {
        $this->db = $db;
    }

    public function log(
        string $action,
        ?string $entityType = null,
        ?int $entityId = null,
        ?string $oldValues = null,
        ?string $newValues = null,
        ?int $userId = null,
        ?int $tenantId = null
    ): void {
        try {
            if ($tenantId === null && $userId !== null) {
                $u = $this->db->prepare('SELECT tenant_id FROM users WHERE id = ? LIMIT 1');
                $u->execute([$userId]);
                $row = $u->fetch(\PDO::FETCH_ASSOC);
                $tenantId = $row ? (int)$row['tenant_id'] : null;
            }
            $cols = 'user_id, action, entity_type, entity_id, old_values, new_values, ip_address';
            $vals = ':user_id, :action, :entity_type, :entity_id, :old_values, :new_values, :ip';
            $params = [
                'user_id' => $userId,
                'action' => $action,
                'entity_type' => $entityType,
                'entity_id' => $entityId,
                'old_values' => $oldValues,
                'new_values' => $newValues,
                'ip' => $_SERVER['REMOTE_ADDR'] ?? null
            ];
            try {
                $this->db->query('SELECT tenant_id FROM audit_log LIMIT 1');
                $cols .= ', tenant_id';
                $vals .= ', :tenant_id';
                $params['tenant_id'] = $tenantId;
            } catch (\Throwable $e) {}
            $stmt = $this->db->prepare(
                "INSERT INTO audit_log ($cols) VALUES ($vals)"
            );
            $stmt->execute($params);
        } catch (\Throwable $e) {
            // لا نوقف التطبيق عند فشل التسجيل
        }
    }
}
