<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\DiscountCode;
use App\Models\EmailSubscriber;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class NewsletterController extends Controller
{
    public function subscribe(Request $request): JsonResponse
    {
        $data = $request->validate([
            'email' => 'required|email|max:255',
        ]);

        $email = strtolower(trim($data['email']));

        // Check if already subscribed
        $existing = EmailSubscriber::where('email', $email)->first();

        if ($existing && $existing->unsubscribed_at === null) {
            // Already subscribed — return their code if they have one, otherwise generate
            $code = $this->findOrCreateWelcomeCode($email);
            return response()->json([
                'message' => 'You are already subscribed.',
                'already_subscribed' => true,
                'discount_code' => $code,
            ]);
        }

        if ($existing) {
            // Re-subscribing after unsubscribe
            $existing->update(['unsubscribed_at' => null, 'subscribed_at' => now()]);
        } else {
            EmailSubscriber::create([
                'email'         => $email,
                'subscribed_at' => now(),
                'source'        => 'homepage_newsletter',
            ]);
        }

        // Also sync user account consent if a user with this email exists
        \App\Models\User::where('email', $email)
            ->where('email_marketing_consent', false)
            ->update(['email_marketing_consent' => true]);

        $code = $this->findOrCreateWelcomeCode($email);

        return response()->json([
            'message'      => 'Thank you for subscribing!',
            'discount_code' => $code,
        ], 201);
    }

    private function findOrCreateWelcomeCode(string $email): string
    {
        // Look for an existing WELCOME15 code tied to this email via metadata in code name
        $prefix = 'WELCOME15-' . strtoupper(substr(md5($email), 0, 6));

        $existing = DiscountCode::where('code', $prefix)->first();
        if ($existing) {
            return $existing->code;
        }

        // Create a unique welcome code
        $code = $prefix;

        // Ensure uniqueness (extremely unlikely collision but safe)
        while (DiscountCode::where('code', $code)->exists()) {
            $code = 'WELCOME15-' . strtoupper(Str::random(6));
        }

        DiscountCode::create([
            'code'             => $code,
            'type'             => 'percentage',
            'value'            => 15.00,
            'min_order_amount' => null,
            'max_uses'         => 1,
            'uses_count'       => 0,
            'is_active'        => true,
            'expires_at'       => now()->addYear(),
        ]);

        return $code;
    }
}
