<?php

namespace App\Http\Controllers;

use App\Models\EmailMarketingSubscriber;
use Illuminate\View\View;

class PublicUnsubscribeController extends Controller
{
    public function show(string $token): View
    {
        $subscriber = EmailMarketingSubscriber::where('unsubscribe_token', $token)->firstOrFail();

        // PRC-622 Dalga C — auth'suz sayfa; boş context (token/PII taşınmaz).
        app(\App\Core\Hook\HookBridge::class)->fireAction('ClientAreaPageUnsubscribe', []);

        return view('public.unsubscribe', [
            'token' => $token,
            'email' => $subscriber->email,
            'alreadyUnsubscribed' => $subscriber->status === 'unsubscribed',
            'confirmed' => false,
        ]);
    }

    public function confirm(string $token): View
    {
        $subscriber = EmailMarketingSubscriber::where('unsubscribe_token', $token)->firstOrFail();

        if ($subscriber->status !== 'unsubscribed') {
            $subscriber->unsubscribe();

            // PRC-622 — 'Unsubscribe Confirmation' maili; alıcı client
            // olmayabilir → to_email_key ile explicit adres
            // (config/communication_events.php eşlemesi).
            app(\App\Core\Hook\HookBridge::class)->fireAction('SubscriberUnsubscribed', [
                'subscriber_id' => $subscriber->id,
                'email' => $subscriber->email,
            ]);
        }

        return view('public.unsubscribe', [
            'token' => $token,
            'email' => $subscriber->email,
            'alreadyUnsubscribed' => true,
            'confirmed' => true,
        ]);
    }
}
