<?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\SaveGoogleSheet;

use function YOOtheme\app;
use ZOOlanders\YOOessentials\Api\Google\GoogleSheetApi;
use ZOOlanders\YOOessentials\Api\Google\GoogleSheetApiInterface;
use ZOOlanders\YOOessentials\Auth\AuthManager;

trait InteractsWithSheet
{
    protected static function api(string $authId): ?GoogleSheetApiInterface
    {
        $auth = app(AuthManager::class)->auth($authId);

        if (!$auth) {
            throw new \RuntimeException('Invalid Account.');
        }

        /** @var GoogleSheetApi $api */
        $api = app(GoogleSheetApiInterface::class);

        return $api->withToken($auth->accessToken());
    }

    private static function saveSheet(array $data, object $config): void
    {
        $inputOptions = [
            'INPUT_TYPE_RAW' => GoogleSheetApi::INPUT_TYPE_RAW,
            'INPUT_TYPE_USER_ENTERED' => GoogleSheetApi::INPUT_TYPE_USER_ENTERED,
        ];

        $sheet = $config->sheet_name ?? '';
        $sheetId = $config->sheet_id;
        $valueInput = $config->value_input ?? 'INPUT_TYPE_RAW';

        $header = self::getSheetHeader($config->account, $sheetId, $sheet);
        $interval = self::interval($sheet, $header);

        $data = self::sortDataFromHeaders($header, $data);

        $params = [
            'valueInputOption' => $inputOptions[$valueInput],
        ];

        self::api($config->account)->append($sheetId, array_values($data), $interval, $params);
    }

    private static function getSheetHeader(string $account, string $sheetId, string $sheetName)
    {
        if (!$account) {
            throw new \RuntimeException('Account must be specified.');
        }

        if (!$sheetId) {
            throw new \RuntimeException('Spreadsheet must be specified.');
        }

        if ($sheetName) {
            $header = self::api($account)->values($sheetId, "{$sheetName}!1:1")['values'][0] ?? [];
        } else {
            $header = self::api($account)->values($sheetId, '1:1')['values'][0] ?? [];
        }

        if (!$header) {
            throw new \RuntimeException('No columns found. At least one column has to be set in the header.');
        }

        return array_map(
            function (string $headerCell, int $index) {
                $headerCell = trim($headerCell);
                if (strlen($headerCell) === 0) {
                    throw new \RuntimeException(
                        sprintf('Column at position %s is missing a header. All columns must have a header.', ++$index)
                    );
                }

                return $headerCell;
            },
            $header,
            array_keys($header)
        );
    }

    private static function interval(string $sheet, array $headers): string
    {
        $endColumn = 'A';

        for ($i = 1; $i < count($headers); $i++) {
            $endColumn = ++$endColumn;
        }

        return "{$sheet}!A1:{$endColumn}1";
    }
}
