<?php

namespace Inside\DESK\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Inside\Content\Models\Contents\Users;
use Laravel\Lumen\Routing\Controller;

class NewsletterController extends Controller
{
    public function send(Request $request): JsonResponse
    {
        if (!$request->has('email')) {
            return response()->json(['error' => 'email is required']);
        }

        $email = $request->get('email');

        $user = Users::query()->where('email', $email)->where('status', 1)->first();

        if (!$user) {
            return response()->json(['error' => 'there is no user ' . $email]);
        }

        $today = date('Y-m-d') . ' 00:00:00';

        DB::table('desk_newsletters_sent')->where('date_sent', $today)->where('user_uuid', $user->uuid)->delete();

        Artisan::call('desk:send-newsletters', ['--email' => $email]);

        return response()->json(['status' => 'success']);
    }
}
