<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Mail\ContactFormMail;
use App\Mail\ContactResponseMail;
use Illuminate\Support\Facades\Mail;
use Inertia\Inertia;
use DB;
use App\Traits\DeleteModelTrait; 
use App\Models\Contact;
use Illuminate\Support\Facades\Http;
use Illuminate\Validation\ValidationException;

class ContactController extends Controller
{
    //
    use DeleteModelTrait;
    public function submitContactForm(Request $request)
    {
        try{
            DB::beginTransaction();

            // Validate form input
            $validated = $request->validate([
                'name' => 'required|string|max:255',
                'email' => 'required|email',
                'phone' => 'nullable|string|max:255',
                'subject' =>'required|string|max:255',
                'message' => 'required|string',
                'turnstile_token' => 'required|string',
            ]);

            // Verify the Turnstile token with Cloudflare
            $turnstileSecretKey = config('services.turnstile.secret');
            $response = Http::asForm()->post('https://challenges.cloudflare.com/turnstile/v0/siteverify', [
                'secret' => $turnstileSecretKey,
                'response' => $validated['turnstile_token'],
                'remoteip' => $request->ip(),
            ]);

            $responseBody = $response->json();

            if (!$responseBody['success']) {
                // If Turnstile verification fails, throw a validation exception
                throw ValidationException::withMessages([
                    'turnstile' => 'CAPTCHA verification failed.',
                ]);
            }

            $contact = new Contact();
            $contact->name = $validated['name'];
            $contact->email = $validated['email'];
            $contact->phone = $validated['phone'] ?? null;
            $contact->subject = $validated['subject'];
            $contact->message = $validated['message'];

            $contact->save();

            // Send the email
            Mail::to('info@matergohotel.bi')->send(new ContactFormMail($validated));
            DB::commit();
            return back()->with('success',[
                'message' => 'Message sent successfuly, we shall respond to you as soon as possible!',
                'check'   => false
            ]);

        } catch (\Exception $e) {
            return redirect()->back()->with('error', [
                'message' => 'An error occurred:' . $e->getMessage(),
                'check'   => false
            ]);
        }

    }

    public function fetchMessages(){
        // Fetch all messages
        $messages = Contact::orderBy('created_at', 'desc')->get();
        return Inertia::render('messages/Message', [
            'messages' => $messages->map(function ($message) {
                return $message->only('id','name','email','phone','subject','message','is_read','created_at');
            }),
        ]);
    }

    public function read_message($id)
    {
        $contact_message = Contact::findOrFail($id);
        if (!$contact_message->is_read) {
            $contact_message->update(['is_read' => true]);
        }
        return response()->json($contact_message);
    }

    public function sendResponse(Request $request)
    {
        // Validate the incoming data
        $data = $request->validate([
            'response_to_message' => 'required|string',
            'email'               => 'required|email',
            'subject'             => 'required|string',
            'message'             => 'required|string',
        ]);

        // Prepare the data for the email view
        $emailData = [
            'response_to_message' => $data['response_to_message'],
            'original_subject'    => $data['subject'],
            'subject'    => $data['subject'],
            'original_message'    => $data['message'],
        ];

        // Send the email
        Mail::to($data['email'])->send(new ContactResponseMail($emailData));

        return back()->with('success', [
            'message' => 'Your reply has been sent successfully',
            'check'   => false
        ]);
    }

    public function destroy($id)
    {
        return $this->deleteModel($id, new Contact());
    }
}
