<?php

namespace App\Http\Controllers\Frontend;

use DB;
use Carbon\Carbon;
use App\Mail\UserMail;
use App\Models\Setting;
use Illuminate\Http\Request;
use App\Models\CustomerReview;
use App\Models\CustomerMessage;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use App\Models\InputFieldPlaceHolder;

class HomeController extends Controller
{
    public function index(){
        $data['setting'] = Setting::first();
        $data['input_field'] = InputFieldPlaceHolder::first();
        $data['review'] = CustomerReview::where('status','active')->orderBy('id')->get();
        return view('frontend.index',compact('data'));
    }

    public function sentEmail(Request $request){
        // dd($request->all());
        DB::beginTransaction();
        try {
            $validated = $request->validate([
                'input_field_3' => ['required','email','max:255'],

            ]);
            $input_field = InputFieldPlaceHolder::first();
            $requestAllExceptToken = $request->except('_token');
            $form_data = json_encode($requestAllExceptToken);
            $receiverEmail = Setting::first()->message_email;

            $mailData = [
                'input_field' => $input_field,
                'data' => $requestAllExceptToken
            ];
            // dd($mailData);    
            $sendMail = Mail::to($receiverEmail)->send(new UserMail($mailData));

            if($sendMail){
                CustomerMessage::insert([
                    'sender_email' => $request->input_field_3,
                    'receiver_email' => $receiverEmail,
                    'form_data' => $form_data,
                    'mail_sent_date' => date('Y-m-d'),
                    'created_at' => Carbon::now()
                ]);
            }

            $notification = array(
                'message' => 'Mail Sent Successfully!!',
                'alert-type' => 'success'
            );

            DB::commit();

            return redirect()->back()->with($notification);
        } catch (\Exception $e) {
            DB::rollback();
                $message = $e->getMessage();
                $notification = array(
                    'message' => $message,
                    'alert-type' => 'error'
                );
            return redirect()->back()->with($notification);
        }
        
    } // end of sent mail
}
