<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\SubscripeionMail;
use Validator;

class HomeController extends Controller
{
    public function index()
    {
        $carouselRows = \App\Models\HomeCarousel::where('is_front_show', '=', true)
            ->orderBy('lft', 'asc')
            ->orderBy('id', 'desc');
        $newsRows = \App\Models\News::where('is_front_show', '=', true)
            ->orderBy('post_at', 'desc')
            ->take('3');
        $eventRows = \App\Models\Event::where('is_front_show', '=', true)
            ->orderBy('post_at', 'desc')
            ->take('3');
        return view('home', [
            'carouselRows' => $carouselRows->get(),
            'newsRows' => $newsRows->get(),
            'eventRows' => $eventRows->get(),
        ]);
    }
    
    public function indexPost(Request $request)
    {
        $message = '';
        $result = 'success';
        $subscribeInquery = $request->input('subscribeInquery');
        if ($subscribeInquery)
        {
            try 
            {
                //$request->validate();
                $validator = Validator::make($request->all(), [
                    'subscribeInquery' => 'required|email',
                ], $messages = [
                    'required' => 'The :attribute field is required.',
                    'email' => 'The :attribute field is not a email address.',
                ]);
                if ($validator->fails()) 
                {
                    $result = 'errorSubscribe';
                    $message = 'Opps！ Please try again.';
                }
                else
                {
                    //
                    Mail::to('newsletter.cri@coreality-inc.com')->send(
                        new SubscripeionMail($subscribeInquery)
                    );
                    $result = 'successSubscribe';
                    $message = 'We have received your subscribe inquiry！';
                }
            }
            catch (Exception $ex)
            {
                $result = 'errorSubscribe';
                $message = 'Opps！ Please try again.';
            }
            
            
        }

        if ($message != '') 
        {
            return redirect()->back()->with($result, $message);
        }
        else
            return redirect()->back();
        
    }
}
