<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Models\Newsletter;
use Exception;

class NewsletterController extends Controller
{
    public function joinEmailSubscription(Request $request)
    {
        try {
            $validation = Validator::make($request->all(), [
                'email' => 'required|string|email|max:255|unique:newsletters',
            ], [
                'email.unique' => 'You have already subscribed with this email.',
            ]);

            if ($validation->fails()) {
                return response()->json([
                    'validation_errors' => $validation->messages(),
                    'response_status' => 400,
                ], 200);
            }

            $newsletter = Newsletter::create([
                'email' => $request->email,
            ]);

            $data = ['newsletter' => $newsletter];
            return response([
                'response_status' => 200,
                'response_message' => ['success' => ['You have successfully subscribed.']],
                'data' => $data
            ], 200);
        } catch (Exception $e) {
            return response()->json([
                'validation_errors' => $e->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }
}
