<?php namespace App\Libs\Composers\CF;

use News;

class CfNewsDetailComposer
{
    use \App\Libs\Composers\SidebarComposerTrait;

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

        $newsDetail = News::full()
            ->with('media', 'document')
            ->orderBy('website_objects.position', 'asc')
            ->where("slug", $slug)->first();

        if (!$newsDetail) {
            abort(404);
        }

        if ($newsDetail->status != 'published') {
            $user = \Auth::guard('admin')->user();
            if (!$user) {
                abort(404);
            }
        }

        $metaData = new \stdClass();
        if (!empty($newsDetail->meta_title)) {
            $metaData->meta_title = $newsDetail->meta_title;
        } else {
            $metaData->meta_title = cut_string(strip_tags($newsDetail->title), 100);
        }
        if (!empty($newsDetail->meta_description)) {
            $metaData->meta_description = $newsDetail->meta_description;
        } else {
            $metaData->meta_description = cut_string(strip_tags($newsDetail->summary), 200);
        }
        $metaData->meta_keywords = $newsDetail->meta_keywords;

        $this->composeSidebar($view, \CfDefaultTemplateCfg::query());

        $view->with(array(
            'newsDetail' => $newsDetail,
            'metaData' => $metaData
        ));
    }
}
