<?php

namespace App\Models;

use App\Core\Model;
use PDO;

class AuditLog extends Model
{
    protected $table = 'audit_logs';
    protected $primaryKey = 'id';

    public function log($userId, $action, $entityType = null, $entityId = null, $description = null)
    {
        return $this->create([
            'user_id' => $userId,
            'action' => $action,
            'entity_type' => $entityType,
            'entity_id' => $entityId,
            'description' => $description,
            'ip_address' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1',
            'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '',
        ]);
    }

    public function getWithUser($page = 1, $perPage = 20)
    {
        $offset = ($page - 1) * $perPage;
        $totalStmt = $this->db->query("SELECT COUNT(*) as count FROM {$this->table}");
        $total = $totalStmt->fetch(PDO::FETCH_OBJ)->count;

        $stmt = $this->db->prepare("
            SELECT a.*, u.name as user_name, u.email as user_email
            FROM {$this->table} a
            LEFT JOIN users u ON a.user_id = u.id
            ORDER BY a.id DESC
            LIMIT ? OFFSET ?
        ");
        $stmt->execute([$perPage, $offset]);

        return (object) [
            'data' => $stmt->fetchAll(PDO::FETCH_OBJ),
            'total' => $total,
            'page' => $page,
            'perPage' => $perPage,
            'lastPage' => ceil($total / $perPage),
        ];
    }

    public function getRecent($limit = 10)
    {
        $stmt = $this->db->prepare("
            SELECT a.*, u.name as user_name
            FROM {$this->table} a
            LEFT JOIN users u ON a.user_id = u.id
            ORDER BY a.id DESC LIMIT ?
        ");
        $stmt->execute([$limit]);
        return $stmt->fetchAll(PDO::FETCH_OBJ);
    }
}
