<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Log;
use Illuminate\Database\Eloquent\Model;
use Telegram\Bot\Api;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(Api::class, function ($app) {
            return new Api(config('services.telegram.token'));
        });
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
        Model::created(function ($model) {
            $this->logDBOperation('created', $model);
        });

        Model::updated(function ($model) {
            $this->logDBOperation('updated', $model);
        });

        Model::deleted(function ($model) {
            $this->logDBOperation('deleted', $model);
        });
    }

    protected function logDBOperation($action, $model)
    {
        $table = $model->getTable();
        $data = $model->getAttributes();
        $log = [
            'time' => now()->toDateTimeString(),
            'action' => $action,
            'table' => $table,
            'data' => $data,
        ];

        Log::channel('dblog')->info('DB Operation', $log);
    }
}
