<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Mail;
use Illuminate\Mail\Message;
use Illuminate\Support\Str;
use App\Models\Newsletter;
use Exception;


class NewsletterController extends Controller
{
    // All Subscribed Emails
    public function index()
    {
        try {
            $newsletters = Newsletter::latest()->get();
            $data = ['newsletters' => $newsletters];
            return response()->json([
                'data' => $data,
                'response_status' => 200
            ], 200);
        } catch (Exception $e) {
            return response()->json([
                'validation_errors' => $e->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }

    // Send Email to Subscribed Emails
    public function sendEmailSubscribed(Request $request)
    {
        // dd($request->all());
        try {
            $validation = Validator::make($request->all(), [
                'email' => 'required|array',
                'email.*' => 'email|exists:newsletters,email',
                'subject' => 'required|string|max:255',
                'message' => 'required|string',
            ]);

            if ($validation->fails()) {
                return response()->json([
                    'validation_errors' => $validation->messages(),
                    'response_status' => 400,
                ], 200);
            }

            $emails = $request->email;
            $subject = $request->subject;
            $messageContent = $request->message;

            foreach ($emails as $email) {
                // Retrieve the subscription if needed
                $subscription = Newsletter::where('email', $email)->first();
                if ($subscription) {
                    $subscription->subject = $subject;
                    $subscription->message = $messageContent;
                    $subscription->save();
                }

                // Sending email
                Mail::send('subscribed_email', ['emailMessage' => $messageContent], function (Message $message) use ($email, $subject) {
                    $message->subject($subject);
                    $message->to($email);
                    $message->from(env('MAIL_FROM_ADDRESS'), env('MAIL_FROM_NAME'));
                });
            }

            return response()->json([
                'response_message' => ['success' => ['Emails have been sent successfully.']],
                'response_status' => 200
            ], 200);
        } catch (Exception $e) {
            return response()->json([
                'validation_errors' => $e->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }
    
    public function newsletterImageUpload(Request $request)
    {
        try {
            // Validate the image
            $validation = Validator::make($request->all(), [
                'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            ]);
    
            if ($validation->fails()) {
                return response()->json([
                    'validation_errors' => $validation->messages(),
                    'response_status' => 400,
                ], 200);
            }
    
            $filename = null;
    
            if ($request->hasFile('image')) {
                $file = $request->file('image');
                $extension = $file->getClientOriginalExtension();
                $filename = time() . '.' . $extension;
    
                $path = public_path('uploads/newsletters/');
                $file->move($path, $filename);
            }
    
            $imageUrl = $filename ? asset('uploads/newsletters/' . $filename) : null;
    
            return response()->json([
                'response_status' => 200,
                'data' => [
                    'image' => $filename,
                    'url' => $imageUrl,
                ],
            ], 200);
    
        } catch (Exception $e) {
            return response()->json([
                'validation_errors' => $e->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }


    // Delete Subscribed Email
    public function destroy(string $id)
    {
        try {
            $newsletter = Newsletter::find($id);
            if (!$newsletter) {
                return response()->json([
                    'validation_errors' => ['not_found' => ['Subscription Email not found']],
                    'response_status' => 400
                ], 200);
            }

            $newsletter->delete();

            return response()->json([
                'response_message' => ['success' => ['Subscribed Email has been deleted successfully.']],
                'response_status' => 200
            ], 200);
        } catch (Exception $e) {
            return response()->json([
                'validation_errors' => $e->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }
}
