<?php

namespace App\Http\Controllers\V1;

use App\Http\Controllers\Controller;
use App\Models\Newsletter;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Gate;

class NewsletterController extends Controller
{
    /**
     * Store a new newsletter email
     */
    public function store(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'email' => ['required', 'email', 'unique:newsletters,email'],
        ]);

        if ($validator->fails()) {
            return api_response(
                data: null,
                message: $validator->errors()->first(),
                status: 422
            );
        }

        $newsletter = Newsletter::create([
            'email' => $request->email,
        ]);

        return api_response(
            data: [
                'id' => $newsletter->id,
                'email' => $newsletter->email,
                'reference' => 'Project: NewsletterModule' // ممكن تحط أي ريفرنس تحبه
            ],
            message: 'Subscribed successfully',
            status: 201
        );
    }

    /**
     * Get all newsletters
     */
    public function index(): JsonResponse
    {
        Gate::authorize('view-all-newsletter');
        return api_response(
            data: Newsletter::all(),
            message: 'Success',
            status: 200
        );
    }

    /**
     * Show newsletter by ID (full row)
     */
    public function show(int $id): JsonResponse
    {
        Gate::authorize('view-newsletter');

        $newsletter = Newsletter::find($id);

        if (!$newsletter) {
            return api_response(
                data: null,
                message: 'Newsletter not found',
                status: 404
            );
        }

        return api_response(
            data: $newsletter,
            message: 'Success',
            status: 200
        );
    }

    /**
     * Get email only by ID
     */
    public function getEmailById(int $id): JsonResponse
    {
        $newsletter = Newsletter::find($id);

        if (!$newsletter) {
            return api_response(
                data: null,
                message: 'Newsletter not found',
                status: 404
            );
        }

        return api_response(
            data: [
                'email' => $newsletter->email,
                'reference' => 'Project: NewsletterModule'
            ],
            message: 'Success',
            status: 200
        );
    }
}
