<?php
/**
 * @package   Essentials YOOtheme Pro 2.2.16 build 0813.1608
 * @author    ZOOlanders https://www.zoolanders.com
 * @copyright Copyright (C) Joolanders, SL
 * @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
 */

namespace ZOOlanders\YOOessentials\Form\Action\Mailchimp;

use YOOtheme\Http\Request;
use YOOtheme\Http\Response;

class MailchimpController
{
    use HasApiRequest;

    public const LISTS_ENDPOINT = 'yooessentials/form/actions/mailchimp/lists';
    public const MERGE_FIELDS_ENDPOINT = 'yooessentials/form/actions/mailchimp/merge-fields';
    public const INTERESTS_ENDPOINT = 'yooessentials/form/actions/mailchimp/interests';
    public const MARKETING_PERMISSIONS_ENDPOINT = 'yooessentials/form/actions/mailchimp/marketing-permissions';

    public function lists(Request $request, Response $response)
    {
        $form = $request->getParam('form');
        $auth = $form['auth'] ?? '';

        if (!$auth) {
            return $response->withJson('Auth argument is missing.', 400);
        }

        try {
            $lists = self::api($auth)->getAllLists();
        } catch (\Exception $e) {
            return $response->withJson($e->getMessage(), 400);
        }

        $items = array_map(function ($list) {
            return [
                'text' => $list['name'],
                'value' => $list['id'],
                'meta' => $list['id'],
            ];
        }, $lists);

        return $response->withJson($items);
    }

    public function mergeFields(Request $request, Response $response)
    {
        $form = $request->getParam('form');
        $list = $form['list'] ?? null;
        $auth = $form['auth'] ?? '';

        if (!$auth) {
            return $response->withJson('Auth argument is missing.', 400);
        }

        if (!$list) {
            return $response->withJson('List argument is missing.', 400);
        }

        try {
            $result = self::api($auth)->getMergeFields($list);

            $fields = array_map(function ($field) {
                return [
                    'id' => $field['tag'],
                    'title' => $field['name'] . ($field['required'] ? ' *' : ''),
                    'type' => $field['type'],
                    'meta' => ['tag' => $field['tag'], 'type' => $field['type']],
                    'data' => [
                        'tag' => $field['tag'],
                        'title' => $field['name'] . ($field['required'] ? ' *' : '')
                    ]
                ];
            }, $result['merge_fields'] ?? []);
        } catch (\Exception $e) {
            return $response->withJson($e->getMessage(), 400);
        }

        return $response->withJson($fields);
    }

    public function interests(Request $request, Response $response)
    {
        $form = $request->getParam('form');
        $list = $form['list'] ?? null;
        $auth = $form['auth'] ?? '';
        $api = self::api($auth);

        try {
            $categories = $api->getInterestCategories($list, [
                'exclude_fields' => 'list_id, total_items, _links'
            ]);

            $fields = [];

            foreach ($categories['categories'] ?? [] as $category) {
                $fields[] = [
                    'label' => $category['title'],
                    'name' => "_{$category['id']}",
                    'type' => 'yooessentials-info',
                ];

                $result = $api->getInterestsInCategory($list, $category['id'] ?? '', [
                    'fields' => 'interests'
                ]);

                $result = array_map(function ($interest) {
                    return [
                        'name' => "member_interests_{$interest['id']}",
                        'type' => 'checkbox',
                        'label' => $interest['name'],
                        'text' => 'Enabled',
                        'source' => true
                    ];
                }, $result['interests'] ?? []);

                $fields = array_merge($fields, $result);

                if ($category !== end($categories['categories'])) {
                    $fields[] = [
                        'name' => "{$category['id']}_",
                        'type' => 'yooessentials-info',
                        'divider' => true
                    ];
                }
            }
        } catch (\Exception $e) {
            return $response->withJson($e->getMessage(), 400);
        }

        return $response->withJson($fields);
    }

    public function marketingPermissions(Request $request, Response $response)
    {
        $form = $request->getParam('form');
        $list = $form['list'] ?? null;
        $auth = $form['auth'] ?? '';

        try {
            // Get marketing permissions from the first member found
            $result = self::api($auth)->getListMembers($list, [
                'fields' => 'members.marketing_permissions',
                'count' => 1
            ]);

            $members = $result['members'] ?? [];

            if (!count($members)) {
                throw new \Exception('No members found. The Audience needs to have at least one member.');
            }

            $fields = array_map(function ($field) {
                return [
                    'name' => "member_marketing_permissions_{$field['marketing_permission_id']}",
                    'type' => 'checkbox',
                    'label' => $field['text'],
                    'text' => 'Granted',
                    'source' => true
                ];
            }, $members[0]['marketing_permissions'] ?? []);
        } catch (\Exception $e) {
            return $response->withJson($e->getMessage(), 400);
        }

        return $response->withJson($fields);
    }
}
