<?php

namespace App\Newsletter;

use App\Contracts\NewsletterProvider;
use DrewM\MailChimp\MailChimp as DrewMailChimp;

class MailChimp implements NewsletterProvider
{
    /**
     * MailChimp constructor.
     * Initializes the connection with MailChimp API
     *
     * @param DrewMailChimp $api
     */
    public function __construct(private readonly DrewMailChimp $api)
    {
    }

    /**
     * Sign up method
     *
     * @param string $email email address to sign up
     * @param array $additional_params any additional params passed to interface
     * @return bool
     */
    public function signUp(string $email, array $additional_params = []): bool
    {
        $list_id = $this->getDefaultListId();
        return $this->api->post(
            "lists/$list_id/members",
            [
                'email_address' => $email,
                'status' => 'subscribed',
                'merge_fields' => [
                    'FNAME' => $additional_params['first_name'] ?? '',
                    'LNAME' => $additional_params['last_name'] ?? '',
                ],
            ]
        );
    }

    /**
     * Check if email already exists in the list
     *
     * @param string $email
     * @return bool
     */
    public function checkIfExists(string $email): bool
    {
        $response = $this->api->get('lists/' . $this->getDefaultListId() . '/members/' . md5(strtolower($email)));
        return ($response['status'] ?? false)  === "subscribed";
    }

    /**
     * Gets the default list ID, making sure it exists in the account.
     *
     * @return string The ID of the default list
     */
    private function getDefaultListId()
    {
        $lists = $this->api->get('lists');
        // TODO: Setting implementation for list selection
        //        if (in_array(config('newsletter.mailchimp_list_id'), array_column($lists['lists'], 'id'))) {
        //            return config('newsletter.mailchimp_list_id');
        //        }
        return (count($lists['lists']) > 0 ? $lists['lists'][0]['id'] : '');
    }
}
