<?php

namespace App\Helpers;

use App\Album;
use App\Facade\UserConfig;
use Illuminate\Support\Facades\Auth;

class DbHelper
{
    public static function getAlbumsForCurrentUser()
    {
        $user = Auth::user();
        $userId = is_null($user) ? 0 : $user->id;

        $albums = Album::where('is_private', false)
            ->orWhere(function ($query) use ($userId)
            {
                $query->where('is_private', true)
                    ->where('user_id', $userId);
            })
            ->orderBy('name')
            ->withCount('photos')
            ->paginate(UserConfig::get('items_per_page'));

        return $albums;
    }

    /**
     * Fetches an album using its URL alias.
     * @param string $urlAlias URL alias of the album to fetch.
     * @return Album|null
     */
    public static function loadAlbumByUrlAlias($urlAlias)
    {
        return Album::where('url_alias', $urlAlias)->first();
    }
}