<?php

namespace App\Http\Controllers\Pages;

use App\Http\Controllers\Controller;
use App\Mail\Admin\ReceiverMail;
use App\Mail\ContactSubmitted;
use App\Models\Admin;
use App\Models\Contact;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;

class ContactController extends Controller
{
    public function send() {
        $validation = Validator::make(request()->all(), [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255',
            'subject' => 'required|max:255',
            'phone' => 'max:255',
            'message' => 'required'
        ]);

        if($validation->fails()) {
            return response()->json([
                'ok' => 0,
                'data' =>  $validation->errors(),
            ], 422);
        }

        $contact = Contact::create(request()->all());
        
        $admins = Admin::all();
        foreach ($admins as $admin) {
            Mail::to($admin->email)->send(new ContactSubmitted($contact));
        }

        return response()->json([
            'ok' => 1,
            'data' => 'Your message has been received. We\'ll get back to you soon.'
        ]);
    }

    public function send_notice() {
        $validation = Validator::make(request()->all(), [
            'subject' =>'required|max:255',
            'content' => 'required',
            'name' => 'required|max:255',
            'email' => 'required|email'
        ]);

        if($validation->fails()) {
            return response()->json([
                'ok' => 0,
                'data' => $validation->errors(),
            ], 422);
        }

        try {
            Mail::to(request('email'))->send(new ReceiverMail((object) request()->all()));
            
            return response()->json([
                'ok' => 1,
                'data' => 'Mail sent successfully.',
            ]);
        } catch (\Throwable $th) {
            $response = [
                'others' => [$th->getMessage()]
            ];
            return response()->json([
                'ok' => 0,
                'data' => (object) $response
            ], 422);
        }

    }

    public function contact_messages() {
        return view('admin.contact-message.all', [
            'contacts' => Contact::all(),
        ]);
    }

    public function single(Contact $contact) {
        return view('admin.contact-message.single', [
            'contact' => $contact,
        ]);
    }

    public function delete(Contact $contact) {
        try {
            $contact->delete();

            session()->flash('success', 'Contact deleted successfully.');
            return response()->json([
                'ok' => 1,
                'data' => 'Contact deleted successfully.'
            ]);
        } catch (\Throwable $th) {
            return response()->json([
                'ok' => 1,
                'data' => 'Something went wrong, please try again.'
            ], 419);
        }
    }
}
