<?php

declare(strict_types=1);

namespace Seka\Portal\Modul\Statistiky\Providers;

use Carbon\Carbon;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\ServiceProvider;
use Seka\Portal\Modul\Statistiky\Console\ImportZaznamovCommand;
use Seka\Portal\Modul\Statistiky\Console\KontrolaImportuZaznamovCommand;
use Seka\Portal\Modul\Statistiky\Repositories\Eloquent\Transformers\TransformerContract;
use Seka\Portal\Modul\Statistiky\RolesAndPermissions;

/**
 * Class StatistikyServiceProvider
 *
 * @package Seka\Portal\Modul\Statistiky\Providers
 */
final class StatistikyServiceProvider extends ServiceProvider
{
    /**
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     */
    public function boot(): void
    {
        $this->registerModulesRolesAndPermissions();

        $this->app->bind(TransformerContract::class, function () {
            // nepouziva sa
        });

        $this->mergeConfigFrom(__DIR__ . '/../../config/config.php', 'statistiky');

        $this->app->booted(function () {
            $this->breadcrumbs();
        });

        $this->validators();
    }

    protected function registerModulesRolesAndPermissions(): void
    {
        $this->app->bind(RolesAndPermissions::class, function () {
            return new RolesAndPermissions();
        });

        $this->app->tag([
            RolesAndPermissions::class,
        ], 'roleaopravnenia');
    }

    protected function breadcrumbs(): void
    {
        if (class_exists('Breadcrumbs')) {
            // BACKEND
            require __DIR__ . '/../../routes/backend/breadcrumbs.php';

            // FRONTEND
            require __DIR__ . '/../../routes/frontend/breadcrumbs.php';
        }
    }

    private function validators(): void
    {
        Validator::extend('date_months_difference', function ($attribute, $value, $parameters, $validator) {
            $dateFrom = Carbon::parse($parameters[0]);
            $dateTo = Carbon::parse($parameters[1]);
            $maxDifference = (int)$parameters[2];

            if ($dateFrom->diffInMonths($dateTo) > $maxDifference) {
                return false;
            }

            return true;
        });
    }

    public function register(): void
    {
        $this->commands([
            ImportZaznamovCommand::class,
            KontrolaImportuZaznamovCommand::class,
        ]);
    }
}
