<?php

namespace App\Http\Controllers;

use Mapper;
use Validator;
use Mail;
use App\Mail\LowcostMail as LowcostMail;
use App\Settings as mSetting;
use App\Media as mMedia;
use App\Message as mMessage;
use App\Pagename;
use Illuminate\Http\Request;

class Contact extends Controller
{
	public function getMedia($section)
    {
        return mMedia::firstOrCreate(['media_page' => 'contact', 'media_section' => $section]);
    }

    public function getGeneral($section)
    {
        return mGeneral::firstOrCreate(['general_page'=>'contact','general_section'=> $section]);
	}
	
	public function getSetting($name, $default = '')
	{
		return mSetting::firstOrCreate(['setting_name' => $name], ['setting_value' => $default]);
	}

    function index(){
    	$location = $this->getSetting('companyLatLon', '-7.7955798,110.36948959999995')->setting_value;

    	// Mapper::map($lat, $lng, ['markers' => ['title' => 'My Company']]);

    	$data['banner'] = $this->getMedia('banner-header');
    	$data['map'] = $location;
      $data['page'] = 'contact';
      $page_id = Pagename::where('key','contact')->first()->id;
      $data['meta_tags'] = Pagename::find($page_id)->meta_tags;
    	return view('contact')->with($data);
    }

    function sendMessage(Request $req){
    	$name = $req->name;
    	$email = $req->email;
    	$message = $req->message;

    	$this->validate($req, [
    	    'name' => 'required',
          'email' => 'email|required',
          'message'=>'required',
    	]);

  		$validator = Validator::make($req->all(), [
  		    'name' => 'required',
  	      'email' => 'email|required',
  	      'message'=>'required',
  		]);

  		if($validator->fails()){
  			$req->flash(['name', 'email','message']);
  		}

      $maildata = [
        'name'=>$name,
        'email'=>$email,
        'message'=>$message,
      ];

      $emailto = mSetting::where('setting_name','companyEmail')->first()->setting_value;
      Mail::to($emailto)->send(new LowcostMail($name, $email, $message));

      $db = new mMessage;
    	$db->message_sender_name = $name;
    	$db->message_sender_email = $email;
    	$db->message_sender_content = $message;
    	$db->save();

    	$req->session()->flash('message', 'Message sent successfully!');
		  $req->session()->flash('alert-class', 'alert-success');

    	return back();
    }
}
