<?php namespace App\Libs\Composers;

use BlogPost;

class BlogDetailComposer
{
    use SidebarComposerTrait, ObjectDetailTrait;

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

        $referrer = !empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
        $blogUrl = lang_url($websiteObject->lang_uri);
        $backUrl = '#';

        if (strpos($referrer, $blogUrl.'?') !== 0 && $referrer != $blogUrl) {
            $backUrl = lang_url($websiteObject->lang_uri);
        } else {
            if (strpos($referrer, url('/')) === false) {
                $backUrl = lang_url($websiteObject->lang_uri);
            }
        }

        $post = BlogPost::full()
            ->withBlocks()
            ->with(array(
                'media', 'questions' => function ($query) {
                    $query->full()->orderBy('position', 'asc');
                }, 'authors' => function ($query) {
                    $query->orderBy('blog_author_blog_post.position', 'asc');
                }, 'categories' => function ($query) {
                    $query->orderBy('blog_category_blog_post.position', 'asc');
                }, 'relatedPosts' => function ($query) {
                    $query->full()
                        ->select("id", "title", "lang_slug as slug", "lang_uri as uri", "media_id")
                        ->where('status', 'published')
                        ->where('lang_status', 'published')
                        ->with(array(
                            'media', 'authors' => function ($query) {
                                $query->full()
                                    ->orderBy('blog_author_blog_post.position', 'asc');
                            }
                        ))->orderBy('blog_post_blog_post.position', 'asc');
                }
            ))
            ->orderBy('website_objects.position', 'asc')
            ->where("lang_slug", $postSlug)
            //->where('status', 'published')
            ->first();

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

        $metaData = new \stdClass();
        if (!empty($post->meta_title)) {
            $metaData->meta_title = $post->meta_title;
        } else {
            $metaData->meta_title = cut_string(strip_tags($post->title), 100);
        }
        if (!empty($post->meta_description)) {
            $metaData->meta_description = $post->meta_description;
        } else {
            $metaData->meta_description = cut_string(strip_tags($post->excerpt), 200);
        }
        if ($post->media) {
            $metaData->metaImage = getMediaUrl($post->media->filename, '800w');
        }
        $metaData->meta_keywords = $post->meta_keywords;
        if (!empty($post->canonical_url)) {
            $metaData->canonical_url = $post->canonical_url;
        }

        $relatedPosts = $post->relatedPosts;

        if (!$relatedPosts->count()) {
            $cat = $post->categories->first();
            if ($cat) {
                $relatedPosts = BlogPost::full()
                    ->select("id", "title", "lang_slug as slug", "lang_uri as uri", "media_id")
                    ->with(array(
                        'media', 'authors' => function ($query) {
                            $query->orderBy('blog_author_blog_post.position', 'asc');
                        }
                    ))
                    ->whereExists(function ($query) use ($cat) {
                        $query->select(\DB::raw(1))
                            ->from("blog_category_blog_post")
                            ->whereRaw("blog_category_blog_post.blog_post_id = blog_posts.id")
                            ->where("blog_category_id", $cat->id);
                    })
                    ->where('blog_posts.id', '!=', $post->id)
                    ->where('status', 'published')
                    ->where('lang_status', 'published')
                    ->orderBy('date', 'desc')
                    ->limit(3)
                    ->get();
            }
        }

        $this->composeObjectSidebar($view, $post);

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

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