<?php

namespace Mtc\Modules\DoctorSurgery\Classes;

use Twig\Environment;

/**
 * ViewFixer class. Resolves Laravel dependencies for the View package to be able to render a pagination view.
 *
 * @author Aleksey Lavrinenko
 * @version 09.09.2016.
 */
class ViewFixer
{
    /**
     * Resolves Laravel dependencies for the View package
     *
     * @param Environment $twig
     */
    public function resolvePaginationDependencies(Environment $twig)
    {
        // a little hack to make it support Laravel of both < 5.3 and 5.3 versions
        if (class_exists(\Illuminate\Pagination\BootstrapThreePresenter::class)) {
            // 5.2, the presenter is bundled with the pagination package
            // so just do nothing here
        } else {
            // 5.3, the Paginator will use View component to render the pagination, so we need to register required
            // services first
            $app = \Illuminate\Support\Facades\App::getFacadeRoot();

            (new \Illuminate\Pagination\PaginationServiceProvider($app))->register();
            if (!$app->bound('view')) {
                // use template paths from twig
                $template_paths = $twig->getLoader()->getPaths();

                $app['config']['view.paths'] = $template_paths;
                // this is the same as twig path now
                // when upgrading to the View in the core, it can use that one
                $cache_path = SITE_PATH . '/cache/blade_cache';
                $app['config']['view.compiled'] = $cache_path;
                // crate the direcotry
                if (!file_exists($cache_path)) {
                    mkdir($cache_path, 0755, true);
                }

                (new \Illuminate\Filesystem\FilesystemServiceProvider($app))->register();
                (new \Illuminate\View\ViewServiceProvider($app))->register();

                // live/sites without laravel/framework dependency
                $illuminate_path = '/Illuminate/Pagination/resources/views';
                $view_dir = SITE_PATH . '/vendor' . strtolower($illuminate_path);
                if (!file_exists($view_dir)) {
                    // staging with 'laravel/framework' dependency
                    $view_dir = SITE_PATH . '/vendor/laravel/framework/src' . $illuminate_path;
                }

                // paginator specific path
                $app['view']->getFinder()->addNamespace('pagination', $view_dir);
            }
        }

        // page and path resolvers
        \Illuminate\Pagination\LengthAwarePaginator::currentPathResolver(function () {
            return explode('?', $_SERVER['REQUEST_URI'])[0];
        });
        \Illuminate\Pagination\LengthAwarePaginator::currentPageResolver(function () {
            return isset($_GET['page']) ? $_GET['page'] : 1;
        });
    }
}
