<?php

namespace Mtc\Plugins\NewsletterSignup\Classes;

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;

use DrewM\MailChimp\MailChimp as DrewMailChimp;

/**
 * NewsletterSignup Service provider
 *
 * Initializes the services for Newsletter Sign-up
 *
 * @author Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 * @version 0.4
 */
class NewsletterServiceProvider
{
    /**
     * Bind the integration which will be used to register newsletter sign-ups with the app instance
     * This is to ensure correct driver is used for actions
     */
    public static function register()
    {
        // Bind Campaign Monitor API to class name so we can inject it when needed
        App::bind(\CS_REST_Subscribers::class, function () {
            return new \CS_REST_Subscribers(NEWSLETTER_CM_LIST_ID, [
                'api_key' => NEWSLETTER_CM_API_KEY
            ]);
        });

        // Bind Campaign Monitor class to CM instance
        App::bind(CampaignMonitor::class, function () {
            return new CampaignMonitor(App::make(\CS_REST_Subscribers::class));
        });

        // Bind MailChimp API to class name so we can inject it when needed
        App::bind(DrewMailChimp::class, function () {
            return new DrewMailChimp(NEWSLETTER_MAILCHIMP_API_KEY);
        });

        // Bind Campaign Monitor class to CM instance
        App::bind(NewsletterSignUp::class, function () {
            $newsletter_list = EmailList::query()
                ->firstOrCreate([
                    'name' => NewsletterSignUp::$newsletter_list_name,
                ]);

            return new NewsletterSignUp($newsletter_list->id ?? 0);
        });

        // Bind the SMS interface
        App::bind(SignUpInterface::class, function () {
            switch (NEWSLETTER_DRIVER) {
                case 'campaign_montitor':
                    return App::make(CampaignMonitor::class);
                case 'mailchimp':
                    return App::make(MailChimp::class);
                default:
                    return App::make(NewsletterSignUp::class);
            }
        });

    }

}
