<?php

namespace App\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\NewsletterSubscriber; // Assuming model needs to be created or we use a table directly
use Illuminate\Support\Facades\Validator;

class NewsletterController extends Controller
{
    public function subscribe(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email|unique:newsletter_subscribers,email'
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'message' => $validator->errors()->first()], 422);
        }

        // Check if table exists, if not create migration later. For now assuming we need to create it.
        // Or we can just log it if no table. But plan implied storage.
        // Let's assume we need to create a migration for this.
        
        // For now, let's just return success to mock it if we don't want to create a full table yet, 
        // BUT the user asked for "implementation", so I should probably create the table.
        // I will create a migration in the next step.
        
        // Using DB facade if model doesn't exist yet
        \DB::table('newsletter_subscribers')->insert([
            'email' => $request->email,
            'created_at' => now(),
            'updated_at' => now()
        ]);

        return response()->json(['success' => true, 'message' => 'Thank you for subscribing!']);
    }
}
