<?php namespace App\Libs\Composers;

use BlogCategory;
use BlogAuthor;
use DB;
use Entry;

class BlogContributerComposer
{
    use ObjectDetailTrait;

    public function compose($view)
    {
        $data = $view->getData();
        $parameters = $data['parameters'];
        $authorSlug = last($parameters);

        $referrer = !empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
        $blogUrl = lang_url('blog');
        $backUrl = '#';
        if (strpos($referrer, $blogUrl.'?') !== 0 && $referrer != $blogUrl) {
            $backUrl = $blogUrl;
        }

        $author = BlogAuthor::full()
            ->with(array(
                'media', 'posts' => function ($query) {
                    $query->full()
                        ->select('id', 'media_id', 'title', 'date', 'lang_uri as uri')
                        ->where('status', 'published')
                        ->with(['media'])
                        ->orderBy('date', 'desc')
                        ->limit(12);
                }
            ))
            ->where("lang_slug", $authorSlug)->first();

        $this->checkIsPublished($author, $data['isPreview']);

        $categoriesAuthor = DB::select(
            DB::raw(
                "SELECT DISTINCT blog_category_id FROM blog_category_blog_post l, blog_author_blog_post a WHERE a.blog_author_id = ".$author->id." AND a.blog_post_id = l.blog_post_id"
            )
        );

        $categories = BlogCategory::full()
            ->where('status', 'published')
            ->whereIn('id', array_column($categoriesAuthor, 'blog_category_id'))
            ->orderBy('website_objects.position', 'asc')
            ->get();

        $blogLandingPage = Entry::full()->where('slug', 'blog')->first();
        $blogTitle = $blogLandingPage ? $blogLandingPage->title : 'South Pole Penguin Perspectives Blog';

        $metaData = new \stdClass();
        $metaData->meta_title = 'South Pole Blog - ' . $author->title . ', ' . $author->position_company;
        $metaData->meta_description = trim(cut_string(strip_tags($author->content), 130)) . '... - ' . $blogTitle;
        $metaData->meta_keywords = $author->title;

        $redirectPath = lang_url(config('path.frontend.blog_listing_slug'));

        $view->with(array(
            'author' => $author,
            'backUrl' => $backUrl,
            'metaData' => $metaData,
            'categories' => $categories,
            'redirectPath' => $redirectPath,
            'breadcrumbs' => $this->addBreadcrumb($author, $data['breadcrumbs'] ?? []),
        ));
    }
}
