<?php

namespace App\Http\Controllers;

use App\Http\Handlers\SiteSettingsHandler;
use App\Mail\ContactMail;
use App\Models\Message;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class MessagesController extends Controller
{
    public function index() {
        $messages = Message::get();

        return view('admin.messages.index')->with(['messages' => $messages]);
    }

    public function show($message) {
        $message = Message::firstWhere('id', '=', $message);

        if(!$message) return view('admin.404');

        return view('admin.messages.show')->with(['message' => $message]);
    }

    public function store(Request $request) {
        $data = $request->all();
        $message = new Message([
            "name" => array_key_exists('name', $data)? $data["name"]: "",
            "email" => array_key_exists('email', $data)? $data["email"]: "",
            "phone" => array_key_exists('phone', $data)? $data["phone"]: "",
            "message" => array_key_exists('message', $data)? $data["message"]: "",
            "sent" => false
        ]);

        try{
            Mail::to(config("MAIL_FROM_ADDRESS"))->send(new ContactMail($message));
            if(!Mail::failures()) {
                $message->sent = true;
            }
        } catch (Exception $ex) {

        }

        $message->save();

        return redirect()->route("contact")->with(["message_sent" => $message->sent]);
    }

    public function settings(){
        $site_settings = (new SiteSettingsHandler('page', 'contact'))->getSiteSettings();

        return view('admin.site_settings.index')->with(['category' => 'page',
                                                        'sub_category' => 'contact',
                                                        'site_settings' => $site_settings]);

    }
}
