<?php
declare(strict_types=1);

namespace App\Models;

use App\Core\Model;
use PDO;

/**
 * Audit Log Model for tracking system activities
 */
class AuditLogModel extends Model
{
    protected string $table = 'audit_logs';

    /**
     * Create an audit log entry
     */
    public function log(
        int $tenantId,
        ?int $userId,
        string $action,
        string $module,
        ?int $recordId = null,
        ?array $old = null,
        ?array $new = null
    ): void {
        $data = [
            'tenant_id' => $tenantId,
            'user_id' => $userId,
            'action' => $action,
            'module' => $module,
            'record_id' => $recordId,
            'old_data' => $old ? json_encode($old) : null,
            'new_data' => $new ? json_encode($new) : null,
            'ip_address' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown'
        ];
        $this->create($data);
    }

    /**
     * Get paginated logs with filters
     */
    public function getAll(int $tenantId, array $filters = [], int $page = 1, int $perPage = 20): array
    {
        $offset = ($page - 1) * $perPage;
        $sql = "SELECT a.*, u.name as user_name 
                FROM audit_logs a 
                LEFT JOIN users u ON a.user_id = u.id 
                WHERE a.tenant_id = :tenant_id";

        $params = [':tenant_id' => $tenantId];

        if (!empty($filters['module'])) {
            $sql .= " AND a.module = :module";
            $params[':module'] = $filters['module'];
        }

        if (!empty($filters['action'])) {
            $sql .= " AND a.action = :action";
            $params[':action'] = $filters['action'];
        }

        $sql .= " ORDER BY a.created_at DESC LIMIT $perPage OFFSET $offset";

        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll();
    }

    /**
     * Count total logs for pagination
     */
    public function countAll(int $tenantId, array $filters = []): int
    {
        $sql = "SELECT COUNT(*) FROM audit_logs WHERE tenant_id = :tenant_id";
        $params = [':tenant_id' => $tenantId];

        if (!empty($filters['module'])) {
            $sql .= " AND module = :module";
            $params[':module'] = $filters['module'];
        }

        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);
        return (int) $stmt->fetchColumn();
    }
}
