<?php

namespace App\Http\Controllers;

use App\Models\MessageSetting;
use App\Models\Organization;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class NewsletterUnsubscribeController extends Controller
{
    /**
     * Handle newsletter unsubscribe requests
     */
    public function unsubscribe(Request $request)
    {
        $email = $request->get('email');
        $type = $request->get('type');
        $signature = $request->get('signature');

        // Verify the signature to prevent unauthorized unsubscribes
        $expectedSignature = hash_hmac('sha256', $email . $type, config('app.key'));

        if (!hash_equals($expectedSignature, $signature)) {
            return view('newsletter.unsubscribe-error', [
                'message' => 'Invalid unsubscribe link. Please contact support if you need help unsubscribing.'
            ]);
        }

        // Validate newsletter type
        if (!in_array($type, ['local_newsletter', 'general_newsletter', 'system_message'])) {
            return view('newsletter.unsubscribe-error', [
                'message' => 'Invalid newsletter type.'
            ]);
        }

        // Find the user or organization by email
        $recipient = $this->findRecipientByEmail($email);

        if (!$recipient) {
            return view('newsletter.unsubscribe-error', [
                'message' => 'Email address not found in our system.'
            ]);
        }

        // Get or create message settings
        $messageSettings = $recipient->messageSettings()->first();
        if (!$messageSettings) {
            $messageSettings = new MessageSetting();
            $messageSettings->message_settingable_id = $recipient->id;
            $messageSettings->message_settingable_type = get_class($recipient);
            // Set all newsletter types to true by default (assuming they were subscribed)
            $messageSettings->local_newsletter = true;
            $messageSettings->general_newsletter = true;
            $messageSettings->system_message = true;
        }

        // Unsubscribe from the specific newsletter type
        $messageSettings->{$type} = false;
        $messageSettings->save();

        return view('newsletter.unsubscribe-success', [
            'email' => $email,
            'type' => $type,
            'typeName' => $this->getNewsletterTypeName($type),
            'recipient' => $recipient
        ]);
    }

    /**
     * Find recipient (User or Organization) by email
     */
    protected function findRecipientByEmail(string $email)
    {
        // Try to find a User first
        $user = User::where('email', $email)->first();
        if ($user) {
            return $user;
        }

        // Try to find an Organization
        $organization = Organization::where('email', $email)->first();
        if ($organization) {
            return $organization;
        }

        return null;
    }

    /**
     * Get human-readable newsletter type name
     */
    protected function getNewsletterTypeName(string $type): string
    {
        return match ($type) {
            'local_newsletter' => 'Local Newsletter',
            'general_newsletter' => 'General Newsletter',
            'system_message' => 'System Messages',
            default => 'Newsletter'
        };
    }
}