<?php

namespace App\Repositories;

use App\Config\ContextDB;
use App\Models\Log;
use PDO;

class LogRepository {
    private PDO $context;

    public function __construct(){
        $this->context = (new ContextDB())->conn;
    }

    public function create(Log $log): bool 
    {
        $stmt = $this->context->prepare("
            INSERT INTO logs (action, entity, entity_id, description, old_data, new_data) 
            VALUES (:action, :entity, :entity_id, :description, :old_data, :new_data)
        ");

        return $stmt->execute([
            "action" => $log->action,
            "entity" => $log->entity,
            "entity_id" => $log->entity_id,
            "description" => $log->description,
            "old_data" => $log->old_data ? json_encode($log->old_data) : null,
            "new_data" => $log->new_data ? json_encode($log->new_data) : null
        ]);
    }

    public function getAll(int $limit = 100): array {
        $stmt = $this->context->prepare("
            SELECT * FROM logs ORDER BY created_at DESC LIMIT :limit
        ");
        $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function getByEntity(string $entity, int $entity_id): array {
        $stmt = $this->context->prepare("
            SELECT * FROM logs WHERE entity = :entity AND entity_id = :entity_id ORDER BY created_at DESC
        ");
        $stmt->execute([
            'entity' => $entity,
            'entity_id' => $entity_id
        ]);

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}