<?php

namespace App\Repositories\Core\App;

use Illuminate\Support\Facades\Route;

use App\Models\Core\App\Application;
use App\Repositories\Core\App\ApplicationPages;
use App\Repositories\Languages;

class Applications
{

    public static function getFullBySlug($slug)
    {
        return Application::with('clients')->active()->bySlug($slug)->first();
    }

    public static function getAll()
    {
        return Application::all();
    }

    public static function getOptions()
    {
        return Application::pluck('name', 'id')->toArray();
    }

    public static function edit($id)
    {
        return self::get($id)->toArray();
    }

    public static function store($data)
    {
        $id = isset($data['id']) ? $data['id'] : false;
        return $id ? self::update($data, $id) : self::create($data);
    }

    public static function create($data)
    {
        return Application::create($data);
    }

    public static function update($data, $id = false)
    {
        $id = $id ? $id : $data['id'];
        $item = self::get($id);
        $item->update($data);
        return $item;
    }

    public static function destroy($id)
    {
        return Application::destroy($id);
    }

    public static function getName($id)
    {
        return self::get($id)->name;
    }
 
    public static function get($id)
    {
        return Application::findOrFail($id);
    }

    public static function getCurrent()
    {
        $route = explode('.', Route::currentRouteName());
        $app = isset($route[0]) ? $route[0] : null;
        $page = isset($route[1]) ? $route[1] : null;
        $action = isset($route[2]) ? $route[2] : null;

        if (self::getBySlug($app)) {
            $data['current'] = self::getBySlug($app)->toArray();
            $application_id = $data['current']['id'];
            $data['page'] = ApplicationPages::getBySlug($application_id, $page);
            $data['pages'] = ApplicationPages::getActiveByApplication($application_id);
            $data['action'] = $action;
        } else {
            $data['current']['slug'] = $app;
        }
        $data['langs'] = Languages::getActive();
        $data['lang'] = Languages::getCurrent();
        return $data;
    }

    public static function getActives()
    {
        return Application::active()->get()->toArray();
    }

    public static function getActivesWithModules()
    {
        return Application::with('modules')->active()->get()->toArray();
    }

    public static function getVisibles()
    {
        return Application::visible()->get()->toArray();
    }

    public static function getBySlug($slug)
    {
        return Application::active()->bySlug($slug)->first();
    }

    public static function toggleActive($id, $active) {
        return self::update(['active' => $active], $id);
    }

    public static function toggleVisible($id, $visible) {
        return self::update(['visible' => $visible], $id);
    }
}
