<?php

namespace EasyLinkAutomations\HTTP\Controllers\Actions;

if (!defined('ABSPATH')) {
    exit;
}

use EasyLinkAutomations\Actions\Sendy\SendyRequestHelper;
use EasyLinkAutomations\HTTP\Request\Request;
use EasyLinkAutomations\HTTP\Response;

/**
 * Controller for Sendy related API calls.
 *
 * Populates the brand and list dropdowns. Sendy list IDs are opaque hashed
 * strings that users would otherwise have to copy out of the Sendy dashboard.
 */
final class SendyController
{
    /**
     * Fetch the brands on the connected Sendy installation.
     */
    public function brands(Request $request): Response
    {
        $connectionId = (int) $request->get('connection_id');
        if (!$connectionId) {
            return Response::error('Connection ID is required', 400);
        }

        $response = SendyRequestHelper::post($connectionId, '/api/brands/get-brands.php', []);
        if (!$response['success']) {
            return Response::error($response['message']);
        }

        $decoded = SendyRequestHelper::decodeList($response['body']);
        if (is_string($decoded)) {
            // "No brands found" is an empty result, not a failure.
            if (strcasecmp($decoded, 'No brands found') === 0) {
                return Response::success(['brands' => []]);
            }

            return Response::error('Sendy: ' . $decoded);
        }

        $brands = [];
        foreach ($decoded as $brand) {
            if (!is_array($brand)) {
                continue;
            }

            $id = trim((string) ($brand['id'] ?? ''));
            if ($id === '') {
                continue;
            }

            $brands[] = [
                'value' => $id,
                'label' => trim((string) ($brand['name'] ?? '')) ?: $id,
            ];
        }

        return Response::success(['brands' => $brands]);
    }

    /**
     * Fetch the lists belonging to a brand on the connected Sendy installation.
     */
    public function lists(Request $request): Response
    {
        $connectionId = (int) $request->get('connection_id');
        if (!$connectionId) {
            return Response::error('Connection ID is required', 400);
        }

        $brandId = trim((string) $request->get('brand_id'));
        if ($brandId === '') {
            return Response::error('Brand ID is required', 400);
        }

        $response = SendyRequestHelper::post(
            $connectionId,
            '/api/lists/get-lists.php',
            ['brand_id' => $brandId, 'include_hidden' => 'no']
        );
        if (!$response['success']) {
            return Response::error($response['message']);
        }

        $decoded = SendyRequestHelper::decodeList($response['body']);
        if (is_string($decoded)) {
            if (strcasecmp($decoded, 'No lists found') === 0) {
                return Response::success(['lists' => []]);
            }

            return Response::error('Sendy: ' . $decoded);
        }

        $lists = [];
        foreach ($decoded as $list) {
            if (!is_array($list)) {
                continue;
            }

            $id = trim((string) ($list['id'] ?? ''));
            if ($id === '') {
                continue;
            }

            $lists[] = [
                'value' => $id,
                'label' => trim((string) ($list['name'] ?? '')) ?: $id,
            ];
        }

        return Response::success(['lists' => $lists]);
    }
}
