<?php

namespace App\Http\Controllers;

use App\Facades\Settings;
use App\Http\Requests\StoreNewsletterRequest;
use App\Newsletter\CampaignMonitor;
use App\Newsletter\MailChimp;
use App\Repositories\NewsletterRepository;
use Illuminate\Support\Facades\App;

class NewsletterController extends Controller
{
    /**
     * Submit a new newsletter subscriber
     *
     * @param StoreNewsletterRequest $request
     * @param NewsletterRepository $repository
     * @return array
     */
    public function store(StoreNewsletterRequest $request)
    {
        $repository = new NewsletterRepository(App::make($this->getProvider()));
        return [
            'success' => $repository->checkIfExists($request->input('email'))
                ? true
                : $repository->signUp($request->input('email'))
        ];
    }

    private function getProvider(): string
    {
        return collect([
            MailChimp::class => Settings::get('newsletters-mailchimp-enabled'),
            CampaignMonitor::class => Settings::get('newsletters-campaign-monitor-enabled'),
        ])
            ->filter()
            ->keys()
            ->firstOrFail();
    }
}
