<?php

namespace App\Http\Controllers;

use App\Mail\NewsletterMail;
use App\Models\Contact;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Modules\Admin\app\Models\Setting;
use Illuminate\Http\Response;

class MailController extends Controller
{
    public function sendNewsMail(Request $request)
    {
        $messages = array(
            'email.required' => 'Email is required',
            'email.email' => 'Email invalid',
            'name.required' => 'Your name is required',
            'company.required' => 'Company name is required',
            'phone.required' => 'Phone number is required',
        );

        $validateData = [
            'email' => 'required|email',
            'name' => 'required',
            'company' => 'required',
            'phone' => 'required',
        ];

        $request->validate($validateData, $messages);


        try {
            $setting = Setting::first();
            $contact = Contact::where('email', $request->email)->first();

            if($contact!==null) {
                $contact->update($request->all());
                $send = Mail::to($setting->email)->send(new NewsletterMail($request->all()));
                return response()->json(['status'=>true, 'message' => 'The request email has been sent successfully!'], Response::HTTP_OK);
            }else{
                Contact::create($request->all());
                $send = Mail::to($setting->email)->send(new NewsletterMail($request->all()));
                return response()->json(['status'=>true, 'message' => 'The request email has been sent successfully!'], Response::HTTP_OK);
            }
            
        } catch (\Exception $e) {
            return response()->json(['status'=>false, 'message' => 'Send email fail'], Response::HTTP_OK);
        }
    }
}
