<?php

namespace App\Http\Controllers\Site;

use App\Depoimento;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Segmento;
use App\FeatureSegmentoItem;
use App\Solucao;
use App\FeatureSolucaoItem;
use App\DificuldadeSolucaoItem;
use App\BeneficioSolucaoItem;
use App\Produto;
use App\FeatureProdutoItem;
use App\BeneficioProdutoItem;
use App\ClienteHome;
use App\SolucaoHome;
use App\CaseHome;
use App\BlogPost;
use App\Cta;
use App\Banner;
use App\MatEducativo;
use App\MatFormato;
use App\MatCategoria;
use App\Video;
use App\BlogCategorie;
use App\BlogPostRelacionado;
use App\About;
use App\Author;
use App\Cliente;
use App\Configuracao;
use App\Fornecedor;
use App\Timeline;
use App\Pagina;

use Illuminate\Support\Facades\Mail;
use \App\Mail\MailNotification;
use App\Rules\SecureUpload;
use App\SessaoNumeros;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\Console\Helper\Helper;

class HomeController extends Controller
{

    private $lang = 'pt';
    private $menu_solucoes = null;
    private $menu_segmentos = null;
    
    private $limit = 9;
    private $skip;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        if(parseLocale() == '/') {
            $this->lang = 'pt';
        } else {
            $this->lang = parseLocale();
        }

        $this->menu_segmentos = Segmento::where("language_id", "=", $this->lang)->orderBy('order', 'ASC')->get();
        $this->menu_solucoes = Solucao::with("produtos")
                                        ->where("language_id", "=", $this->lang)->orderBy('order', 'ASC')->get();

            // ->whereHas('produtos', function($query) {
            //     $query->where('status', 1);
            // })

        // dd($this->menu_solucoes[0]->produtos);
       // $this->middleware('auth');
    }


    public function index()
    {

        $config = Configuracao::first();
        
        $menu_segmentos = $this->menu_segmentos;
        $menu_solucoes = $this->menu_solucoes;
        
        switch ($this->lang) {
            case 'pt': $langNoticia = 'pt_br'; break;
            case 'es': $langNoticia = 'es_es'; break;
            case 'en': $langNoticia = 'en_us'; break;
            default:  $langNoticia = 'pt_br'; break;
        }

        $banners = Banner::where("language", "=", $this->lang)->where("status", "=", 1)->orderBy('order', 'ASC')->get();
        
        $clientes = ClienteHome::with('cliente')->where("language_id", "=", $this->lang)->get();
        $clientesSlide = Cliente::get();
        $solucoes = SolucaoHome::with('solucao')->where("language_id", "=", $this->lang)->get();
        
        //dd($solucoes);
        $cases = CaseHome::with('blogPost.blogcategory')
                           ->where("language_id", "=", $this->lang)
                           ->get();
        $noticias = BlogPost::with('blogcategory')
                              ->where("language_id", "=", $langNoticia)
                              ->where("tipo", "=", 'blog')
                              ->where("date_published", "<", date("Y-m-d H:i:s"))
                              ->where("status", "=", 1)
                              ->orderBy('date_published', 'desc')
                              ->limit(20)
                              ->get();

        $ctaHome = Cta::where("home", "=", 1)->first();
        $cta = null;
        if ($ctaHome) {
            if($this->lang == 'pt') {
                $cta = array("titulo" => $ctaHome->titulo_pt,
                                "description" => $ctaHome->description_pt,
                                "image" => $ctaHome->image,
                                "target" => $ctaHome->target,
                                "btncta" => $ctaHome->btncta_pt,
                                "btnlinkcta" => $ctaHome->btnlinkcta_pt,
                                "bt_color" => $ctaHome->bt_color);
            } else if($this->lang == 'es') {
                $cta = array("titulo" => $ctaHome->titulo_es,
                                "description" => $ctaHome->description_es,
                                "image" => $ctaHome->image,
                                "target" => $ctaHome->target,
                                "btncta" => $ctaHome->btncta_es,
                                "btnlinkcta" => $ctaHome->btnlinkcta_es,
                                "bt_color" => $ctaHome->bt_color);
            } else if($this->lang == 'en') {
                $cta = array("titulo" => $ctaHome->titulo_en,
                                "description" => $ctaHome->description_en,
                                "image" => $ctaHome->image,
                                "target" => $ctaHome->target,
                                "btncta" => $ctaHome->btncta_en,
                                "btnlinkcta" => $ctaHome->btnlinkcta_en,
                                "bt_color" => $ctaHome->bt_color);
            }
        }

        
        $numbers = SessaoNumeros::orderBy('ordem', 'ASC')->get();
        
        return view('site.home', compact('menu_segmentos', 'menu_solucoes', 'clientes', 'solucoes', 'cases', 'cta', 'banners', 'noticias', 'config', 'numbers', 'clientesSlide'));
    }

    public function segmento(Request $request)
    {

        $menu_segmentos = $this->menu_segmentos;
        $menu_solucoes = $this->menu_solucoes;
        $pagina = 'segmento';
        $features_itens = null;

        $obj = Segmento::with("solucaos", "featureSegmento", "clientes", "clientes", "faqs")->where("slug", "=", $request['slug'])->first();
        //dd($obj);
        
        if ($obj->featureSegmento)
            $features_itens = FeatureSegmentoItem::with('biblioteca')->where("feature_segmento_id", "=", $obj->featureSegmento->id )->orderBy('order', 'ASC')->get();
        
        $clientesObj = $obj->clientes;
        foreach ($clientesObj as $arr) {
            
            $titulo = $descricao = $botao = $link = '';
            switch($this->lang){
                case 'pt' : 
                    $titulo = $arr->titulo_pt;
                    $descricao = $arr->description_pt;
                    $botao = $arr->btncta_pt;
                    $link = $arr->linkbtncta_pt;
                    break;
                case 'es' : 
                    $titulo = $arr->titulo_es;
                    $descricao = $arr->description_es;
                    $botao = $arr->btncta_es;
                    $link = $arr->linkbtncta_es;                    
                    break;
                case 'en' : 
                    $titulo = $arr->titulo_en;
                    $descricao = $arr->description_en;
                    $botao = $arr->btncta_en;
                    $link = $arr->linkbtncta_en;                    
                    break;
            }

            $clientes[] = array(
                "id" => $arr->id,
                "titulo" => $titulo,
                "descricao" => $descricao,
                "logo" => $arr->marca,
                "background" => $arr->image,
                "botao" => $botao,
                "link" => $link
            );
        }

        $caminhos = [
            ['url' => route('principal'), 'titulo' => 'Apoio'],
            ['url' => '', 'titulo' => $obj->name],
        ];
        $clientes = null;
        //dd($caminhos);
        
        return view('site.template_002', compact('obj', 'caminhos', 'menu_segmentos', 'menu_solucoes', 'features_itens', 'clientes','pagina'));
    }

    public function solucao(Request $request)
    {
        $menu_segmentos = $this->menu_segmentos;
        $menu_solucoes = $this->menu_solucoes;
        $pagina = 'solucao';
        $lang = $this->lang;

        $noticias = $cases = null;

        $obj = Solucao::with("produtos", "dificuldadeSolucao", "featureSolucao", "depoimentos", "beneficioSolucao", "noticias.blogcategory")->where("slug", "=", $request['slug'])->first();
        if($obj) {
            if (@$obj->noticias) { 
                foreach($obj->noticias as $blog) {
                    if ($blog->tipo == 'blog') {
                        $noticias[] = array("id" => $blog->id,
                                            "title" => $blog->title,
                                            "slug" => $blog->slug,
                                            "subtitle" => $blog->subtitle,
                                            "description" => $blog->descrition,
                                            "image" => $blog->image,
                                            "dia" => dataBr($blog->date_published),
                                            "categoria" => array("id" => $blog->blogcategory->id,
                                                                "name" => $blog->blogcategory->name)
                                            );
                    } else {
                        $cases[] =    array("id" => $blog->id,
                                            "slug" => $blog->slug,
                                            "background" => $blog->background,
                                            "title" => $blog->title,
                                            "subtitle" => $blog->subtitle,
                                            "description" => $blog->descrition,
                                            "image" => $blog->image,
                                            "dia" => dataBr($blog->date_published),
                                            "categoria" => array("id" => $blog->blogcategory->id,
                                                                "name" => $blog->blogcategory->name)
                                            );
                    }   
                }
            }

            $dificuldades_itens =  (@$obj->dificuldadeSolucao) ? DificuldadeSolucaoItem::with('biblioteca')->where("dificuldade_solucao_id", "=", $obj->dificuldadeSolucao->id )->get() : null;
            
            $features_itens = (@$obj->featureSolucao) ? FeatureSolucaoItem::with('biblioteca')->where("feature_solucao_id", "=", $obj->featureSolucao->id )->orderBy('order', 'ASC')->get() : null;
            $beneficios_itens = (@$obj->beneficioSolucao) ? BeneficioSolucaoItem::with('biblioteca')->where("beneficio_solucao_id", "=", $obj->beneficioSolucao->id )->orderBy('order', 'ASC')->get(): null;
            
            $caminhos = [
                ['url' => route('principal'), 'titulo' => 'Apoio'],
                ['url' => '', 'titulo' => $obj->name],
            ];
            
            return view('site.template_003', compact('obj', 'caminhos', 'dificuldades_itens', 'features_itens', 'beneficios_itens', 'noticias', 'cases', 'menu_segmentos', 'menu_solucoes', 'pagina', 'lang'));
        } else {
            return redirect()->route('principal');
        }
            //dd($obj);

    }


    public function produto(Request $request)
    {

        $menu_segmentos = $this->menu_segmentos;
        $menu_solucoes = $this->menu_solucoes;
        $pagina = 'produto';
        $lang = $this->lang;

        $noticias = $cases = null;

        $obj = Produto::with("beneficioProduto", "featureProduto", "depoimentos", "noticias.blogcategory")->where("slug", "=", $request['slug'])->first();
        
        if ($obj->noticias) { 
            foreach($obj->noticias as $blog) {
                if ($blog->tipo == 'blog') {
                    $noticias[] = array("id" => $blog->id,
                                        "slug" => $blog->slug,
                                        "title" => $blog->title,
                                        "subtitle" => $blog->subtitle,
                                        "description" => $blog->descrition,
                                        "image" => $blog->image,
                                        "dia" => dataBr($blog->date_published),
                                        "categoria" => array("id" => $blog->blogcategory->id,
                                                             "name" => $blog->blogcategory->name)
                                        );
                } else {
                    $cases[] =    array("id" => $blog->id,
                                        "slug" => $blog->slug,
                                        "title" => $blog->title,
                                        "subtitle" => $blog->subtitle,
                                        "description" => $blog->descrition,
                                        "image" => $blog->image,
                                        "background" => $blog->background,
                                        "dia" => dataBr($blog->date_published),
                                        "categoria" => array("id" => $blog->blogcategory->id,
                                                            "name" => $blog->blogcategory->name)
                                        );
                }   
            }
        }

        $caminhos = [
            ['url' => route('principal'), 'titulo' => 'Apoio'],
            ['url' => route('site.solucao', $obj->solucao->slug), 'titulo' => $obj->solucao->shortname],
            ['url' => '', 'titulo' => $obj->name],
        ];

        //dd($caminhos);
        //dd($cases);

        $features_itens = FeatureProdutoItem::with('biblioteca')->where("feature_produto_id", "=", $obj->featureProduto->id )->orderBy('order', 'ASC')->get();
        $beneficios_itens = BeneficioProdutoItem::with('biblioteca')->where("beneficio_produto_id", "=", $obj->beneficioProduto->id )->orderBy('order', 'ASC')->get();

        return view('site.template_004', compact('obj', 'caminhos', 'features_itens', 'beneficios_itens', 'noticias', 'cases', 'menu_segmentos', 'menu_solucoes', 'pagina', 'lang'));
    }

    
    public function matEducativo(Request $request)
    {
        $menu_segmentos = $this->menu_segmentos;
        $menu_solucoes = $this->menu_solucoes;
        $pagina = 'matEducativo';
        $lang = $this->lang;

        
        $skip = ($request['page']-1) * $this->limit;
       
        $idioma = getLanguage($lang);

        
        $allRegistros = MatEducativo::where("language", "=", $lang )->where("status", 1 )->get();
   
        $objs = MatEducativo::with('matFormato', 'matCategoria')->where("language", "=", $lang )->where("status", 1 )->orderBy("id", 'DESC')->skip($skip)->limit($this->limit)->get();
        //dd($objs);
        
        $formatos = MatFormato::where("language_id", "=", $idioma)->get();
        //dd($formatos);
        $categorias = MatCategoria::where("language_id", "=", $idioma)->get();
        $totalRegistros = count($allRegistros);
        $totalPages = ceil(($totalRegistros) / $this->limit);

        return view('site.template_007', compact('objs', 'totalPages', 'totalRegistros', 'formatos', 'categorias', 'menu_segmentos', 'menu_solucoes', 'pagina', 'lang'));
    }
    
    public function videos(Request $request)
    {
        $menu_segmentos = $this->menu_segmentos;
        $menu_solucoes = $this->menu_solucoes;
        $pagina = 'video';
        $lang = $this->lang;
       
        $idioma = getLanguage($lang);
        $skip = ($request['page']-1) * $this->limit;

        $allRegistros = Video::where("language_id", "=", $lang )->get();

        $objs = Video::where("language_id", "=", $lang )->skip($skip)->limit($this->limit)->get();

        $totalRegistros = count($allRegistros);
        $totalPages = ceil(($totalRegistros) / $this->limit);
       
        return view('site.template_0071', compact('objs', 'totalPages', 'totalRegistros', 'menu_segmentos', 'menu_solucoes', 'pagina', 'lang'));
    }
    
    public function postMatEducativo(Request $request)
    {


        $lang = $this->lang;

        $html = '';

        $formato = $request['formato'];
        $categoria = $request['categoria'];
        $pesquisa = $request['pesquisa'];
       
        $idioma = getLanguage($lang);

        
        $skip = ($request['page']-1) * $this->limit;
        
        $allRegistros = MatEducativo::where(function($query) use ($formato){
                                        if ($formato != '') :
                                            return $query->where('mat_formato_id', '=', $formato);
                                        endif;
                                    })
                                    ->where(function($query)  use ($categoria){
                                        if ($categoria != '')  :
                                            return $query->where('mat_categoria_id', '=', $categoria);
                                        endif;
                                    })
                                    ->where(function($query)  use ($pesquisa){
                                        if ($pesquisa != '') :
                                            return $query->where('description', 'LIKE', '%'.$pesquisa.'%');
                                        endif;
                                    })
                                    ->where("status", 1)
                                    ->get();
        
        
        $objs = MatEducativo::with('matFormato', 'matCategoria')
                            ->where(function($query) use ($formato){
                                if ($formato != '') :
                                    return $query->where('mat_formato_id', '=', $formato);
                                endif;
                            })
                            ->where(function($query)  use ($categoria){
                                if ($categoria != '')  :
                                    return $query->where('mat_categoria_id', '=', $categoria);
                                endif;
                            })
                            ->where(function($query)  use ($pesquisa){
                                if ($pesquisa != '') :
                                    return $query->where('description', 'LIKE', '%'.$pesquisa.'%');
                                endif;
                            })
                            ->where("status", 1)
                            ->orderBy("id", 'DESC')->skip($skip)->limit($this->limit)->get();

        $totalRegistros = count($allRegistros);
        $totalPages = ceil(($totalRegistros) /  $this->limit);                   
                          
        if ($objs) :
            if (count($objs) > 0) :
                foreach($objs as $obj) :
                    $image = isset($obj->image) ? url('storage/matEducativo/'.$obj->image) : asset('assets/img/content/img-material-01.jpg');
                    

                    $html .= '<article class="c-card-material">
                                <a href="'.$obj->link.'" target="_blank">
                                <figure class="c-card-material__cover">
                                    <img src="'.$image.'" alt="img-material-01">
                                </figure>
                                <div class="c-card-material__info">
                                    <p class="c-card-material__meta">
                                        <strong>'.$obj->matFormato->title.'</strong>
                                        <strong>'.$obj->matCategoria->title.'</strong>
                                    </p>
                                    <h3 class="c-card-material__title">'.$obj->description.'</h3>
                                </div>
                                </a>
                                </article>';
                endforeach;
            endif;
        endif;

        $data = array("success" => true, "html" => $html, "totalPages" => $totalPages);
        return response()->json($data);
        
    }


    public function postVideos(Request $request)
    {

        $lang = $this->lang;
        $html = '';

        $pesquisa = $request['pesquisa'];

        $skip = ($request['page']-1) * $this->limit;
        $allRegistros = Video::where(function($query)  use ($pesquisa){
                                        if ($pesquisa != '') :
                                            return $query->where('name', 'LIKE', '%'.$pesquisa.'%')->orWhere('description', 'LIKE', '%'.$pesquisa.'%');
                                        endif;
                                    })->get();


        $objs = Video::where('language_id', '=', $lang)->where('name', 'LIKE', '%'.$pesquisa.'%')->orWhere('description', 'LIKE', '%'.$pesquisa.'%')->skip($skip)->limit($this->limit)->get();

        $totalRegistros = count($allRegistros);
        $totalPages = ceil(($totalRegistros) /  $this->limit);

        if ($objs) :
            if (count($objs) > 0) :
                foreach($objs as $obj) :
                    $image = isset($obj->image) ? url('storage/videos/'.$obj->image) : asset('assets/img/content/img-material-01.jpg');
                    

                    $html .= '<article class="c-card-material">
                                <figure class="c-card-material__cover">
                                    <img src="'.$image.'" alt="img-material-01">
                                </figure>
                                <div class="c-card-material__info">
                                    <h3 class="c-card-material__title">'.$obj->name.'</h3>
                                </div>
                                </article>';
                endforeach;
            endif;
        endif;

        $data = array("success" => true, "html" => $html, "totalPages" => $totalPages);
        return response()->json($data);
        
    }
    
    public function blog(Request $request, $tag = null)
    {
        $menu_segmentos = $this->menu_segmentos;
        $menu_solucoes = $this->menu_solucoes;
        $pagina = 'blog';

        
        $lang = $this->lang;
       
        $idioma = getLanguage($lang);
        $skip = ($request['page']-1) * $this->limit;
        
        $allRegistros = BlogPost::with("blogcategory")
                                ->where("tipo", "=", 'blog' )
                                ->where("status", "=", 1 )
                                ->where("date_published", "<", date("Y-m-d H:i:s"))
                                ->where("language_id", "=", $idioma )
                                ->where(function($query)  use ($tag){
                                    if ($tag != '') :
                                        return $query->where('tags', 'LIKE', '%'.$tag.'%');
                                    endif;
                                })->orderBy("date_published", 'DESC')->get();
        
        $objs = BlogPost::with("blogcategory")
                          ->where("tipo", "=", 'blog' )
                          ->where("status", "=", 1 )
                          ->where("date_published", "<", date("Y-m-d H:i:s"))
                          ->where("language_id", "=", $idioma )
                          ->where("status", "=", 1)
                          ->where(function($query)  use ($tag){
                            if ($tag != '') :
                                return $query->where('tags', 'LIKE', '%'.$tag.'%');
                            endif;
                          })->orderBy("date_published", 'DESC')
                          ->skip($skip)
                          ->limit($this->limit)
                          ->get();
        
        $totalRegistros = count($allRegistros);
        $totalPages = ceil(($totalRegistros) / $this->limit);

        $categorias = BlogCategorie::where("language_id", "=", $idioma)->get();
       
        return view('site.template_005', compact('objs', 'categorias', 'tag', 'totalPages', 'totalRegistros', 'menu_segmentos', 'menu_solucoes', 'pagina', 'lang'));
    }

    public function postBlog(Request $request)
    {

        $html = '';
        $lang = $this->lang;
       
        $idioma = getLanguage($lang);

        $categoria = $request['categoria'];
        $pesquisa = $request['pesquisa'];

        $skip = ($request['page']-1) * $this->limit;
        $allRegistros = BlogPost::where("language_id", "=", $idioma )
                                  ->where("tipo", "=", 'blog' ) 
                                  ->where("status", "=", 1)  
                                  ->where("date_published", "<", date("Y-m-d H:i:s"))
                                    ->where(function($query)  use ($pesquisa){
                                        if ($pesquisa != '') :
                                            return $query->where('title', 'LIKE', '%'.$pesquisa.'%')->orWhere('content', 'LIKE', '%'.$pesquisa.'%');
                                        endif;
                                    })->where(function($query)  use ($categoria){
                                        if ($categoria != '')  :
                                            return $query->where('blogcategory_id', '=', $categoria);
                                        endif;
                                    })->orderBy("date_published", 'DESC')->get();


        $objs = BlogPost::where("language_id", "=", $idioma )
                        ->where("tipo", "=", 'blog' )   
                        ->where("status", "=", 1)      
                        ->where("date_published", "<", date("Y-m-d H:i:s"))      
                            ->where(function($query)  use ($pesquisa){
                                if ($pesquisa != '') :
                                    return $query->where('title', 'LIKE', '%'.$pesquisa.'%')->orWhere('content', 'LIKE', '%'.$pesquisa.'%');
                                endif;
                            })->where(function($query)  use ($categoria){
                                if ($categoria != '')  :
                                    return $query->where('blogcategory_id', '=', $categoria);
                                endif;
                            })->orderBy("date_published", 'DESC')->skip($skip)->limit($this->limit)->get();


        $totalRegistros = count($allRegistros);
        $totalPages = ceil(($totalRegistros) /  $this->limit);

        if ($objs) :
            if (count($objs) > 0) :
                foreach($objs as $obj) :
                    $image = isset($obj->image) ? url('storage/blog/'.$obj->image) : asset('assets/img/content/img-material-01.jpg');
                    $likes = ($obj->likes != '') ? $obj->likes : 0;
                    $alt_text = isset($obj->alt_image) ? $obj->alt_image : @$obj->image;

                    $html .= '<article class="c-card-news">
                                <a href="'.route('site.blogInterna', $obj->slug).'">
                                    <figure class="c-card-news__cover">
                                        <img src="'.$image.'" alt="'.$alt_text.'">
                                    </figure>
                                    <p class="c-card-news__meta">
                                        <strong>'.$obj->blogcategory->name.'</strong>
                                        <time>'.dataBr($obj->date_published).'</time>
                                    </p>
                                    <h3 class="c-card-news__title">'.$obj->title.'</h3>
                                </a>   
                                <button class="like-button like-button--list" data-post-id="'. $obj->id .'"><i class="icon icon-dislike"></i> <span>'.$likes.'</span></button> 
                            </article>';
                endforeach;
            endif;
        endif;

        $data = array("success" => true, "html" => $html, "totalPages" => $totalPages);
        return response()->json($data);
        
    }


    public function blogInterna(Request $request)
    {
        $menu_segmentos = $this->menu_segmentos;
        $menu_solucoes = $this->menu_solucoes;
        $pagina = 'blog';
        $lang = $this->lang;
        $author = $noticias = null;
       
        $idioma = getLanguage($lang);
        
        $obj = BlogPost::with("blogcategory", "author" )->where("slug", "=", $request['slug'] )->first();
        if (!$obj) {
            return redirect()->route('principal');
        }
        if ($obj->author) :
            switch ($lang) {
                case 'pt': $description = $obj->author->descriptionpt; break;
                case 'en': $description = $obj->author->descriptionen; break;
                case 'es': $description = $obj->author->descriptiones; break;
                default: $description = $obj->author->descriptionpt; break;
            }
            $author = array("name" => $obj->author->name,
                            "description" => $description,
                            "image" => $obj->author->image );
        endif;

        $tags = null;
        if ($obj->tags != ''){
            $tags = explode(",", $obj->tags);
        }

        if (@$obj->id) { 
            $relacionadas = BlogPostRelacionado::where('blog_post_id', '=', $obj->id )->get();
            if ($relacionadas){
                foreach($relacionadas as $rel){
                    //$post = BlogPost::with("blogcategory")->find($rel['blog_post_rel_id'])->first();
                    $posts = BlogPost::with("blogcategory")->where('status', '=', 1)->where("date_published", "<", date("Y-m-d H:i:s"))->where("id", "=", $rel['blog_post_rel_id'])->get();
                    if (count($posts) > 0) { 
                        
                        $post = $posts[0];
                        $noticias[] = array("id" => $post->id,
                                            "slug" => $post->slug,
                                            "title" => $post->title,
                                            "subtitle" => $post->subtitle,
                                            "description" => $post->descrition,
                                            "image" => $post->image,
                                            "alt_image" => $post->alt_image,
                                            "dia" => dataBr($post->date_published),
                                            "categoria" => array("id" => $post->blogcategory->id,
                                                                "name" => $post->blogcategory->name));
                    }
                }
            }
        }

        
        $caminhos = [
            ['url' => route('principal'), 'titulo' => 'Apoio', "last" => "false"],
            ['url' => route('site.blogs'), 'titulo' => 'Blog', "last" => "true"],
        ];

        //dd($caminhos);
        
        return view('site.template_006', compact('obj', 'caminhos', 'author', 'tags', 'noticias', 'menu_segmentos', 'menu_solucoes', 'pagina', 'lang'));
    }

    public function cases(Request $request, $tag = null)
    {
        $menu_segmentos = $this->menu_segmentos;
        $menu_solucoes = $this->menu_solucoes;
        $pagina = 'case';
        $lang = $this->lang;
       
        $idioma = getLanguage($lang);
        $skip = ($request['page']-1) * $this->limit;

        $allRegistros = BlogPost::with("blogcategory")
                        ->where("language_id", "=", $idioma )
                        ->where("tipo", "=", 'case' )
                        ->where("status", "=", 1)
                        ->where("date_published", "<", date("Y-m-d H:i:s"))  
                        ->where(function($query)  use ($tag){
                            if ($tag != '') :
                                return $query->where('tags', 'LIKE', '%'.$tag.'%');
                            endif;
                        })->orderBy("date_published", 'DESC')->get();

        $objs = BlogPost::with("blogcategory")
                        ->where("tipo", "=", 'case' )
                        ->where("status", "=", 1)
                        ->where("date_published", "<", date("Y-m-d H:i:s"))  
                        ->where("language_id", "=", $idioma )
                        ->where(function($query)  use ($tag){
                            if ($tag != '') :
                                return $query->where('tags', 'LIKE', '%'.$tag.'%');
                            endif;
                        })->orderBy("date_published", 'DESC')
                        ->skip($skip)->limit($this->limit)->get();
        
        $totalRegistros = count($allRegistros);
        $totalPages = ceil(($totalRegistros) / $this->limit);

        $categorias = BlogCategorie::where("language_id", "=", $idioma)->get();
       
        return view('site.template_0051', compact('objs', 'categorias', 'tag', 'totalPages', 'totalRegistros', 'menu_segmentos', 'menu_solucoes', 'pagina', 'lang'));
    }


    
    public function postCase(Request $request)
    {

        $html = '';
        $lang = $this->lang;
       
        $idioma = getLanguage($lang);

        $categoria = $request['categoria'];
        $pesquisa = $request['pesquisa'];

        $skip = ($request['page']-1) * $this->limit;
        $allRegistros = BlogPost::where("language_id", "=", $idioma )
                                  ->where("tipo", "=", 'case' ) 
                                  ->where("status", "=", 1)
                                  ->where("date_published", "<", date("Y-m-d H:i:s"))  
                                    ->where(function($query)  use ($pesquisa){
                                        if ($pesquisa != '') :
                                            return $query->where('title', 'LIKE', '%'.$pesquisa.'%')->orWhere('content', 'LIKE', '%'.$pesquisa.'%');
                                        endif;
                                    })->where(function($query)  use ($categoria){
                                        if ($categoria != '')  :
                                            return $query->where('blogcategory_id', '=', $categoria);
                                        endif;
                                    })->orderBy("date_published", 'DESC')->get();


        $objs = BlogPost::where("language_id", "=", $idioma )
                        ->where("tipo", "=", 'case' ) 
                        ->where("status", "=", 1)  
                        ->where("date_published", "<", date("Y-m-d H:i:s"))              
                            ->where(function($query)  use ($pesquisa){
                                if ($pesquisa != '') :
                                    return $query->where('title', 'LIKE', '%'.$pesquisa.'%')->orWhere('content', 'LIKE', '%'.$pesquisa.'%');
                                endif;
                            })->where(function($query)  use ($categoria){
                                if ($categoria != '')  :
                                    return $query->where('blogcategory_id', '=', $categoria);
                                endif;
                            })->orderBy("date_published", 'DESC')->skip($skip)->limit($this->limit)->get();


        $totalRegistros = count($allRegistros);
        $totalPages = ceil(($totalRegistros) /  $this->limit);

        if ($objs) :
            if (count($objs) > 0) :
                foreach($objs as $obj) :
                    $image = isset($obj->image) ? url('storage/blog/'.$obj->image) : asset('assets/img/content/noticia-thumb-01.jpg');
                    $alt_text = isset($obj->alt_image) ? $obj->alt_image : @$obj->image;

                    $html .= '<article class="c-card-news">
                                <a href="'.route('site.caseInterna', $obj->slug).'">
                                    <figure class="c-card-news__cover">
                                        <img src="'.$image.'" alt="'.$alt_text.'">
                                    </figure>
                                    <p class="c-card-news__meta">
                                        <strong>'.$obj->blogcategory->name.'</strong>
                                        <time>'.dataBr($obj->date_published).'</time>
                                    </p>
                                    <h3 class="c-card-news__title">'.$obj->title.'</h3>
                                </a>    
                            </article>';
                endforeach;
            endif;
        endif;

        $data = array("success" => true, "html" => $html, "totalPages" => $totalPages);
        return response()->json($data);
        
    }

    

    public function caseInterna(Request $request)
    {
        $menu_segmentos = $this->menu_segmentos;
        $menu_solucoes = $this->menu_solucoes;
        $pagina = 'case';
        $lang = $this->lang;
        $author = $noticias = null;
       
        $idioma = getLanguage($lang);
        
        $obj = BlogPost::with("blogcategory", "author" )->where("slug", "=", $request['slug'] )->first();

        $tags = null;
        if ($obj->tags != ''){
            $tags = explode(",", $obj->tags);
        }
        
        if (@$obj->author) :
            switch ($lang) {
                case 'pt': $description = $obj->author->descriptionpt; break;
                case 'en': $description = $obj->author->descriptionen; break;
                case 'es': $description = $obj->author->descriptiones; break;
                default: $description = $obj->author->descriptionpt; break;
            }
            $author = array("name" => $obj->author->name,
                            "description" => $description,
                            "image" => $obj->author->image );
        endif;

        if (@$obj->id) { 
            $relacionadas = BlogPostRelacionado::where('blog_post_id', '=', $obj->id )->get();
            if ($relacionadas){
                foreach($relacionadas as $rel){
                    //$post = BlogPost::with("blogcategory")->find($rel['blog_post_rel_id'])->first();
                    $posts = BlogPost::with("blogcategory")->where('status', '=', 1)->where("date_published", "<", date("Y-m-d H:i:s"))->where("id", "=", $rel['blog_post_rel_id'])->get();
                    if (count($posts) > 0) { 
                        $post = $posts[0];
                        $noticias[] = array("id" => $post->id,
                                            "slug" => $post->slug,
                                            "title" => $post->title,
                                            "subtitle" => $post->subtitle,
                                            "description" => $post->descrition,
                                            "image" => $post->image,
                                            "alt_image" => $post->alt_image,
                                            "dia" => dataBr($post->date_published),
                                            "categoria" => array("id" => $post->blogcategory->id,
                                                                "name" => $post->blogcategory->name));
                    }
                }
            }
        }

        $caminhos = [
            ['url' => route('principal'), 'titulo' => 'Apoio', 'last' => "false"],
            ['url' => route('site.cases'), 'titulo' => 'Cases', 'last' => "true" ],
            
        ];
        
        return view('site.template_0061', compact('obj', 'caminhos', 'author', 'tags', 'noticias', 'menu_segmentos', 'menu_solucoes', 'pagina', 'lang'));
    }


    public function about(Request $request)
    {
        $menu_segmentos = $this->menu_segmentos;
        $menu_solucoes = $this->menu_solucoes;
        $pagina = 'segmento';

        $obj = About::where("language_id", "=", $this->lang)->first();
        
        $timelines = Timeline::where("language_id", "=", $this->lang)->get();

        //dd($timelines);
        
        return view('site.template_011', compact('obj',  'timelines', 'menu_segmentos', 'menu_solucoes', 'pagina'));
    }


    public function pages(Request $request)
    {
        $menu_segmentos = $this->menu_segmentos;
        $menu_solucoes = $this->menu_solucoes;
        $pagina = 'pages';

        $obj = Pagina::where("language_id", "=", $this->lang)->where("slug", "=", $request['slug'])->first();
        
        
        return view('site.template_010', compact('obj',  'menu_segmentos', 'menu_solucoes', 'pagina'));
    }


    public function contato(Request $request)
    {
        $menu_segmentos = $this->menu_segmentos;
        $menu_solucoes = $this->menu_solucoes;
        $pagina = 'contato';
        
        return view('site.template_009', compact('menu_segmentos', 'menu_solucoes', 'pagina'));
    }

    public function sejaFornecedor(Request $request)
    {
        $menu_segmentos = $this->menu_segmentos;
        $menu_solucoes = $this->menu_solucoes;
        $pagina = 'seja-fornecedor';

        $obj = Fornecedor::first();
        
        return view('site.seja-fornecedor', compact('menu_segmentos', 'menu_solucoes', 'pagina', 'obj'));
    }


    public function sendForm(Request $request)
    {


        if ($request['name'] == '' || $request['email'] == '' || $request['phone'] == '' || $request['company'] == '' || $request['position'] == ''
            || $request['city'] == '' || $request['state'] == '' || $request['subject'] == ''  || $request['message'] == '' || !(filter_var($request['email'], FILTER_VALIDATE_EMAIL)))  {
            $data = array("status" => false, "txt" => 'Preencha todos os campos.');
            return response()->json($data);
            

        } else {
            $client = new \GuzzleHttp\Client();

            $response = $client->request(
                'POST',
                'https://www.google.com/recaptcha/api/siteverify',
                [
                    'form_params' => [
                        'secret'   => '6LdIUdUlAAAAAB_6YSeG6hwYkS0vGSLNQwihKL_W',//env('RECAPTCHA_SECRET'),
                        'response' => $request->input('g-recaptcha-response'),
                        'remoteip' => $request->ip(),
                    ]
                ]
            );

            $response_json = json_decode($response->getBody());
            
            if ($response_json->success !== true) {
                $data = array("status" => true, "txt" => 'Captcha Inválido.');
                return response()->json($data);
            } else { 

                $contato = new \App\Contato();
                
                $contato->name = $request['name'];
                $contato->email = $request['email'];
                $contato->phone = $request['phone'];
                $contato->company = $request['company'];
                $contato->position = $request['position'];
                $contato->subject = $request['subject'];
                $contato->comercializacao = $request['opcao']; // comprador/fornecedor
                $contato->state = $request['state'];
                $contato->city = $request['city'];
                $contato->message = $request['message'];
                $contato->modal = 0;
                $contato->save();

                $dados = array("nome" => $request['name'],
                                "email" => $request['email'],
                                "telefone" => $request['phone'],
                                "empresa" => $request['company'],
                                "cargo" => $request['position'],
                                "cidade" => $request['city'],
                                "estado" => $request['state'],
                                "assunto" => $request['subject'],
                                "comercializacao" => $request['opcao'],
                                "mensagem" => $request['message'],
                                "tipo" => "send_contato");

                $arrCc=null;
                switch ($request['subject']) {
                    // case 'Comercial': $arrCc = ['estrategia.comercial@mv.com.br', 'deise@mv.com.br']; break;
                    // case 'Cursos e Treinamento': $arrCc = ['estrategia.comercial@mv.com.br', 'deise@mv.com.br']; break;
                    // case 'Solicitação de Apresentação': $arrCc = ['estrategia.comercial@mv.com.br', 'deise@mv.com.br']; break;
                    case 'orçamentos': $arrCc = ['campanhasdr@mv.com.br']; break;
                    case 'Ouvidoria': $arrCc = ['deise@mv.com.br', 'kristhiane.lima@mv.com.br', 'wagner.johnatan@mv.com.br']; break;
                    // case 'Canais e Parcerias': $arrCc = ['estrategia.comercial@mv.com.br', 'deise@mv.com.br']; break;
                    // case 'Outros': $arrCc = ['estrategia.comercial@mv.com.br', 'deise@mv.com.br']; break;
                } 

                if ($arrCc != null) {
                    Mail::to('eduardo.negrao@apoiocotacoes.com.br')
                            ->cc($arrCc)
                            ->send( new MailNotification('send_contato', $dados));
                            
                } else {
                    Mail::to('eduardo.negrao@apoiocotacoes.com.br')
                        ->send( new MailNotification('send_contato', $dados));
                }
                
                $texto = 'Agradecemos o seu contato. Retornaremos o seu contato em breve.';    
                if ($request['idioma'] == 'en') { 
                    $texto = 'Thanks for contacting us. We will get back to you shortly.';
                }
                $data = array("status" => true, "txt" => $texto);
                return response()->json($data);
            }
        }
    }



    public function sendFormContato(Request $request)
    {


        if ($request['nome'] == '' || $request['email'] == '' || $request['phone'] == '' || $request['company'] == '' || $request['position'] == '' || $request['messagem'] == ''  || !(filter_var($request['email'], FILTER_VALIDATE_EMAIL)))  {
            $data = array("status" => false, "txt" => 'Preencha todos os campos.');
            return response()->json($data);
            
        } else {
            $client = new \GuzzleHttp\Client();

            $response = $client->request(
                'POST',
                'https://www.google.com/recaptcha/api/siteverify',
                [
                    'form_params' => [
                        'secret'   => '6LdIUdUlAAAAAB_6YSeG6hwYkS0vGSLNQwihKL_W',//env('RECAPTCHA_SECRET'),
                        'response' => $request->input('g-recaptcha-response'),
                        'remoteip' => $request->ip(),
                    ]
                ]
            );


            $response_json = json_decode($response->getBody());
            
            if ($response_json->success !== true) {
                $data = array("status" => true, "txt" => 'Captcha Inválido.');
                return response()->json($data);
            } else { 

                $contato = new \App\Contato();
                
                $contato->name = $request['nome'];
                $contato->email = $request['email'];
                $contato->phone = $request['phone'];
                $contato->company = $request['company'];
                $contato->position = $request['position'];
                $contato->message = $request['messagem'];
                $contato->formpath = $request['formpath'];
                $contato->modal = 1;
                $contato->save();


                $dados = array("nome" => $request['nome'],
                                "email" => $request['email'],
                                "telefone" => $request['phone'],
                                "empresa" => $request['company'],
                                "cargo" => $request['position'],
                                "message" => $request['messagem'],
                                "formpath" => $request['formpath'],
                                "tipo" => "send_contato_modal");

                Mail::to('eduardo.negrao@apoiocotacoes.com.br')
                    ->cc(['campanhasdr@mv.com.br'])  
                    ->send( new MailNotification('send_contato_modal', $dados));
            
                $texto = 'Agradecemos o seu contato. Retornaremos o seu contato em breve.';    
                if ($request['idioma'] == 'en') { 
                    $texto = 'Thanks for contacting us. We will get back to you shortly.';
                }
                $data = array("status" => true, "txt" => $texto);
                return response()->json($data);
            }
        }
    }
    
    public function trabalhe(Request $request)
    {
        $menu_segmentos = $this->menu_segmentos;
        $menu_solucoes = $this->menu_solucoes;
        $pagina = 'trabalhe';
        
        return view('site.template_012', compact('menu_segmentos', 'menu_solucoes', 'pagina'));
    }


    public function sendFormTrabalhe(Request $request)
    { 

         $validator = Validator::make($request->all(), [
                'file' => ['file', new SecureUpload],
            ]);

        if ($validator->fails()) {
            $data = array("status" => false, "txt" => 'Arquivo Inválido.');
            return response()->json($data);
           
        }

        if ($request['name'] == '' || $request['email'] == '' || $request['phone'] == '' ||  $request['position'] == ''
            || $request['city'] == '' || $request['state'] == '' || !$request->hasFile('file') || !(filter_var($request['email'], FILTER_VALIDATE_EMAIL)))  {
            $data = array("status" => false, "txt" => 'Preencha todos os campos.');
            return response()->json($data);
        } else {
            $client = new \GuzzleHttp\Client();

            $response = $client->request(
                'POST',
                'https://www.google.com/recaptcha/api/siteverify',
                [
                    'form_params' => [
                        'secret'   => '6LdIUdUlAAAAAB_6YSeG6hwYkS0vGSLNQwihKL_W',//env('RECAPTCHA_SECRET'),
                        'response' => $request->input('g-recaptcha-response'),
                        'remoteip' => $request->ip(),
                    ]
                ]
            );

            $response_json = json_decode($response->getBody());
            
            if ($response_json->success !== true) {
                $data = array("status" => true, "txt" => 'Captcha Inválido.');
                return response()->json($data);
            } else { 
            
                $extValidas = array('doc','docx','pdf','png','jpg','gif');

                $nameFile = '';    
                    
                if ($request->hasFile('file') && $request->file('file')->isValid()) {
                    
                    $name = uniqid(date('HisYmd'));
                    $extension = $request->file->extension();
                    
                    if (!in_array($extension, $extValidas)) {
                        $data = array("status" => true, "txt" => 'Extensão de arquivo inválida.');
                        return response()->json($data);
                    } else {     
                        $nameFile = "{$name}.{$extension}";
                        $upload = $request->file->storeAs(config('app.folder').'curriculos', $nameFile);
                        if ( !$upload )
                            return redirect()
                                        ->back()
                                        ->with('error', 'Falha ao fazer upload')
                                        ->withInput();

                        $dados = array("nome" => $request['name'],
                                        "email" => $request['email'],
                                        "telefone" => $request['phone'],
                                        "empresa" => $request['company'],
                                        "cargo" => $request['position'],
                                        "cidade" => $request['city'],
                                        "estado" => $request['state'],
                                        "assunto" => "Trabalhe Conosco",
                                        "mensagem" => $request['message'],
                                        "file" =>  $nameFile,
                                        "tipo" => "send_contato_job");
                        Mail::to('campanhasdr@mv.com.br') 
                            ->send( new MailNotification('send_contato_job', $dados));
                        
                        $data = array("status" => true, "txt" => 'Curriculo enviado com sucesso');
                        return response()->json($data);
                    }
                } else {
                    $data = array("status" => true, "txt" => 'Informe um arquivo válido.');
                    return response()->json($data);
                }
            }
        }
    }

}
