<?php

namespace App\Http\Controllers;

use App\Models\NewsletterSubscriber;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class NewsletterController extends Controller
{
    // Public: Subscribe
    public function subscribe(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email|max:255',
            'name' => 'nullable|string|max:255',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'اطلاعات نامعتبر است',
                'errors' => $validator->errors()
            ], 422);
        }

        $subscriber = NewsletterSubscriber::updateOrCreate(
            ['email' => $request->email],
            [
                'name' => $request->name,
                'is_subscribed' => true,
                'subscribed_at' => now(),
                'unsubscribed_at' => null,
            ]
        );

        return response()->json([
            'message' => 'با موفقیت در خبرنامه عضو شدید!',
            'data' => $subscriber
        ], 201);
    }

    // Admin: Get all subscribers
    public function index(Request $request)
    {
        $query = NewsletterSubscriber::query()->orderBy('created_at', 'desc');

        if ($request->has('subscribed')) {
            $query->where('is_subscribed', $request->subscribed);
        }

        if ($request->has('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('email', 'like', "%{$search}%")
                  ->orWhere('name', 'like', "%{$search}%");
            });
        }

        $perPage = $request->get('per_page', 15);
        $subscribers = $query->paginate($perPage);

        return response()->json([
            'message' => 'لیست اعضای خبرنامه',
            'data' => $subscribers
        ]);
    }

    // Admin: Delete subscriber
    public function destroy($id)
    {
        $subscriber = NewsletterSubscriber::findOrFail($id);
        $subscriber->delete();

        return response()->json([
            'message' => 'عضو خبرنامه حذف شد'
        ]);
    }

    // Admin: Unsubscribe
    public function unsubscribe($id)
    {
        $subscriber = NewsletterSubscriber::findOrFail($id);
        $subscriber->update([
            'is_subscribed' => false,
            'unsubscribed_at' => now(),
        ]);

        return response()->json([
            'message' => 'اشتراک کاربر لغو شد',
            'data' => $subscriber
        ]);
    }

    // Admin: Export emails
    public function export()
    {
        $subscribers = NewsletterSubscriber::active()
            ->select('email', 'name')
            ->get();

        $emails = $subscribers->pluck('email')->implode(',');

        return response()->json([
            'message' => 'لیست ایمیل‌ها',
            'data' => [
                'count' => $subscribers->count(),
                'emails' => $emails,
                'subscribers' => $subscribers
            ]
        ]);
    }
}
