<?php

namespace App\Http\Controllers;

use App\Mail\GeneralMail;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;

class MailController extends Controller
{
    public function singleMail(Request $request){

        $validator = Validator::make($request->all(), [
            'subject' => 'required',
            'message' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status'=>'error',
                'title'=> 'FAILED',
                'message'=>$validator->errors()->first()
            ]);
        }

        $validated = $validator->validated();

        $user = User::find($request->id);
        $mailBody = [
            'name'=>$user->username,
            'subject' => $validated['subject'],
            'message' => $validated['message'],
            'mail_type' => 'admin_user',
        ];

        try{
            Mail::to($user->email)->send(new GeneralMail($validated['subject'],$mailBody));

            return response()->json([
                'status' => 'success',
                'title' => 'Mail Sent',
                'message' => 'Mail has been sent to '.$user->username,
                // 'data' => $mailBody
            ]);

        }catch(\Exception $e){
            return response()->json([
                'status' => 'error',
                'title' => 'Unable to send',
                'message' => 'Unable to send this email. please contact developer to fix this.',
                // 'data' => $mailBody
            ]);
            info('Custom MAIL not sent: '. $e->getMessage());
        }

    }

    public function contact(Request $request){

        $subject = $request->has('form_subject') ? $request->form_subject : 'New '.capWords($request->type).' Mail From Customer';

        $mailBody = (object) [
            'name'=>$request->form_email,
            'phone'=>$request->form_phone,
            'subject' => $subject,
            'email' => $request->email,
            'message' => $request->has('form_message') ? $request->form_message : 'Loan Request',
            'type' => $request->mail_type, /* loan | contact */
        ];

        try{

            Mail::to(config('settings.site_email'))->send(new GeneralMail($subject,$mailBody));

            return response()->json([
                'status' => 'success',
                'data' => $request->all()
            ]);

        }catch(\Exception $e){

            info('Unable to send contact mail: '.$e->getMessage());

            return response()->json([
                'status' => 'error',
                'data' => $request->all()
            ]);

        }
    }
}
