<?php

namespace Modules\Home\Http\Controllers;

use stdClass;
use Illuminate\Http\Request;
use Modules\Ads\Entities\Ads;
use Modules\Team\Entities\Teams;
use Modules\Core\Entities\Colors;
use Modules\Polls\Entities\Polls;
use Modules\Posts\Entities\Posts;
use Illuminate\Routing\Controller;
use Modules\Core\Entities\Menuses;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
use Modules\Events\Entities\Events;
use Modules\Photos\Entities\Photos;

use Modules\Layout\Entities\Layouts;
use Modules\Stream\Entities\Streams;
use Modules\Polls\Entities\PollOptions;
use Modules\Settings\Entities\Settings;
use Modules\Schedule\Entities\Schedules;
use Modules\Schedule\Entities\TeamTexts;
use Illuminate\Contracts\Support\Renderable;
use Modules\Events\Entities\EventsTexts;
use Modules\Photos\Entities\PhotosTexts;
use Modules\Polls\Entities\PollsTexts;
use Modules\Posts\Entities\PostsTexts;
use Modules\Schedule\Entities\ScheduleTexts;
use Modules\Statistics\Entities\StatisticsInformations;
use Modules\Stream\Entities\StreamTexts;

class HomeController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index()
    {
        
        $day_the_week = strtolower(date('l'));

        $settings = Settings::first();
        $headers = Menuses::where('enable', true)->where('type', 'header')->orderBy('order')->get();
        $footers = Menuses::where('enable', true)->where('type', 'footer')->orderBy('order')->get();
        $colors = Colors::first();
        $teams = Teams::orderBy('order')->get();
        $teamtext = TeamTexts::first();
        $ad_top = Ads::where('type', 'top')->first();
        $ad_side = Ads::where('type', 'side')->first();
        $ads = Ads::where('type', 'footer')->get();
        $post_emphasis = Posts::where('emphasis', true)->first();
        $posts = Posts::where('emphasis', '!=', true)->orderBy('order')->limit(2)->get();
        $postsText = PostsTexts::first();
        $events = Events::orderBy('created_at', 'desc')->limit(4)->get();
        $eventstext = EventsTexts::first();
        $photos = Photos::all();
        $photostext = PhotosTexts::first();
        
        $layout = new stdClass();
        $layout->favicon = Layouts::where('type', 'favicon')->first();
        $layout->header = Layouts::where('type', 'header')->first();
        $layout->footer = Layouts::where('type', 'footer')->first();
        $layout->facebook = Layouts::where('type', 'facebook')->first();
        $layout->instagram = Layouts::where('type', 'instagram')->first();
        $layout->whatsapp = Layouts::where('type', 'whatsapp')->first();
        $layout->slides = Layouts::where('type', 'slide')->get();

        $poll = Polls::where('active', true)->first();

        if($poll){
            $polloptions = PollOptions::where('id_poll', $poll->id)->get();
            if($polloptions){
                $poll->options = $polloptions;
            }else{
                $poll->options = array();
            }
        }else{
            $polloptions = false;
            $poll = (object) array('enable' => false);
        }
        
        $polltext = PollsTexts::first(); 
        
        $statisticsinformations = StatisticsInformations::all();
        $schedules = Schedules::where('day_the_week', $day_the_week)->get();
        $scheduletext = ScheduleTexts::first();
        $stream = Streams::first();
        $streamtext = StreamTexts::first();

        return view('home::index',
            [
                'settings' => $settings,
                'layout' => $layout,
                'headers' => $headers,
                'ad_top' => $ad_top,
                'ad_side' => $ad_side,
                'ads' => $ads,
                'day_the_week' => $day_the_week,
                'schedules' => $schedules,
                'scheduletext' => $scheduletext,
                'teams' => $teams,
                'teamtext' => $teamtext,
                'post_emphasis' => $post_emphasis,
                'posts' => $posts,
                'postsText' => $postsText,
                'events' => $events,
                'eventstext' => $eventstext,
                'photos' => $photos,
                'photostext' => $photostext,
                'poll' => $poll,
                'polltext' => $polltext,
                'statisticsinformations' => $statisticsinformations,
                'stream' => $stream,
                'streamtext' => $streamtext,
                'footers' => $footers,
                'colors' => $colors
            ]
        );
    }

    /**
     * Show the form for creating a new resource.
     * @return Renderable
     */
    public function create()
    {
        return view('home::create');
    }

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return Renderable
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Show the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function show($id)
    {
        return view('home::show');
    }

    /**
     * Show the form for editing the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function edit($id)
    {
        return view('home::edit');
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @param int $id
     * @return Renderable
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     * @param int $id
     * @return Renderable
     */
    public function sendmail(Request $request)
    {
        $data = $request->all();

        $replay_name = $data['replay_name'];
        $replay_email = $data['replay_email'];
        $replay_phone = isset($data['replay_phone']) ? $data['replay_phone'] : 'Não informado';
        $html_body = $data['html_body'];
        
        $settings = Settings::first();

        $smtp_name = $settings->smtp_name;
        $smtp_source_email = $settings->smtp_source_email;
        $smtp_source_return = $settings->smtp_source_return;
        $smtp_port = $settings->smtp_port;
        $smtp_host = $settings->smtp_host;
        $smtp_user = $settings->smtp_user;
        $smtp_password = $settings->smtp_password;
        $smtp_security = $settings->smtp_security;
        

        

        require base_path("vendor/autoload.php");

        $mail = new PHPMailer(true);

        try {
            
            $mail->CharSet = 'UTF-8'; 
            
        

            if($smtp_source_email && $smtp_host){

                $mail->isSMTP(); 
                $mail->Host       = $smtp_host;                     //Set the SMTP server to send through
                $mail->SMTPAuth   = $smtp_source_email;                                 //Enable SMTP authentication
                $mail->Username   = $smtp_user;                     //SMTP username
                $mail->Password   = $smtp_password;                               //SMTP password
                $mail->Port       = $smtp_port;                                    //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
                
                // Se parar de funcionar, remover linha abaixo
                if($ssmtp_security == 'auto'){
                    $mail->SMTPAutoTLS = false;
                }else{
                    $mail->SMTPSecure = $smtp_security;         //Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
                }

                $mail->SetFrom($smtp_source_email, $smtp_name); //Name is optional
            }else{
                return array(
                    'success' => false,
                    'message' => 'No momento essa função não está disponível'
                );
                // $mail->SetFrom($smtp_source_email, $smtp_name); //Name is optional
            }

            
            $mail->AddAddress($smtp_source_return);
            $mail->addReplyTo($replay_email, $replay_name);
            $mail->isHTML(true);

            $mail->Subject   = $replay_name . ' entrou em contato através do seu WebSite. Telefone ('.$replay_phone.')';
            $mail->Body      = $html_body;
            
            $mail->send();

            return array(
                'success' => true,
                'message' => 'Enviado com suecesso'
            );
        } catch (Exception $e) {

            return array(
                'success' => false,
                'message' => 'Enviado com suecesso'
            );
        }
        
    }
    
}
