<?php

namespace App\Http\Controllers;

use App\Models\Subscriber;
use Illuminate\Http\Request;

class SubscriberController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([
            'email' => ['required', 'email', 'max:255'],
        ]);

        $exists = Subscriber::where('email', $request->email)->exists();

        if ($exists) {
            if ($request->wantsJson()) {
                return response()->json(['message' => 'This email is already subscribed.'], 409);
            }
            return back()->with('info', 'This email is already subscribed.');
        }

        Subscriber::create(['email' => $request->email]);

        if ($request->wantsJson()) {
            return response()->json(['message' => 'Subscribed successfully!']);
        }

        return back()->with('success', 'Thank you for subscribing!');
    }
}