<?php

namespace App\Http\Controllers;

use App\Mail\SubscriberConfirmMail;
use App\Models\Subscriber;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class NewsletterController extends Controller
{
    public function subscribe(Request $request)
    {
        // Honeypot — bots fill everything.
        if (filled($request->input('company_website'))) {
            return back()->with('subscribed', true);
        }

        $data = $request->validate([
            'email' => ['required', 'email:rfc', 'max:190'],
            'name'  => ['nullable', 'string', 'max:120'],
        ]);

        $subscriber = Subscriber::firstOrCreate(
            ['email' => strtolower($data['email'])],
            [
                'name'   => $data['name'] ?? null,
                'source' => $request->input('source', 'coming-soon'),
                'ip'     => $request->ip(),
            ],
        );

        // Rejoining after unsubscribing.
        if ($subscriber->unsubscribed_at) {
            $subscriber->update(['unsubscribed_at' => null]);
        }

        if (! $subscriber->confirmed_at) {
            if (setting('newsletter_double_opt_in', true)) {
                Mail::to($subscriber->email)->queue(new SubscriberConfirmMail($subscriber));
            } else {
                $subscriber->update(['confirmed_at' => now()]);
            }
        }

        return back()->with('subscribed', true);
    }

    public function confirm(Subscriber $subscriber)
    {
        $subscriber->update(['confirmed_at' => $subscriber->confirmed_at ?? now()]);

        return view('newsletter-status', [
            'title' => "You're on the list",
            'message' => "Thanks — your email is confirmed. We'll let you know the moment FarmPilot opens its gates.",
        ]);
    }

    public function unsubscribe(Subscriber $subscriber)
    {
        $subscriber->update(['unsubscribed_at' => now()]);

        return view('newsletter-status', [
            'title' => 'Unsubscribed',
            'message' => "You won't hear from us again. Change your mind any time from the site footer.",
        ]);
    }
}
