<?php
/**
 * AdminCP settings controller for MakePay.
 */

namespace IPS\makepay\modules\admin\settings;

use IPS\makepay\OAuth\OAuth;
use IPS\makepay\Storage\Storage;

if (!\defined('\IPS\SUITE_UNIQUE_KEY')) {
    exit;
}

class _manage extends \IPS\Dispatcher\Controller
{
    protected function manage(): void
    {
        $connected = (bool) Storage::getSecret('oauth_refresh_token');
        $companyId = Storage::get('company_id') ?: 'Not connected';
        $siteUrl = rtrim((string) \IPS\Settings::i()->base_url, '/');
        $webhookUrl = $siteUrl . '/index.php?/makepay/webhook/notify';
        $connectUrl = \IPS\Http\Url::internal('app=makepay&module=settings&controller=manage&do=connect', 'admin');
        $disconnectUrl = \IPS\Http\Url::internal('app=makepay&module=settings&controller=manage&do=disconnect', 'admin');

        $html = \IPS\Theme::i()->getTemplate('global', 'core')->block(
            'MakePay',
            sprintf(
                '<p><strong>Status:</strong> %s</p><p><strong>Company:</strong> %s</p><p><strong>Webhook URL:</strong> <code>%s</code></p><p><a class="ipsButton ipsButton_primary" href="%s">Connect MakePay</a> <a class="ipsButton ipsButton_light" href="%s">Disconnect</a></p>',
                $connected ? 'Connected to MakePay' : 'Not connected',
                htmlspecialchars($companyId, ENT_QUOTES, 'UTF-8'),
                htmlspecialchars($webhookUrl, ENT_QUOTES, 'UTF-8'),
                htmlspecialchars((string) $connectUrl, ENT_QUOTES, 'UTF-8'),
                htmlspecialchars((string) $disconnectUrl, ENT_QUOTES, 'UTF-8'),
            ),
        );

        \IPS\Output::i()->title = 'MakePay';
        \IPS\Output::i()->output = $html;
    }

    protected function connect(): void
    {
        \IPS\Output::i()->redirect(\IPS\Http\Url::external(OAuth::startUrl()));
    }

    protected function disconnect(): void
    {
        OAuth::disconnect();
        \IPS\Output::i()->redirect(\IPS\Http\Url::internal('app=makepay&module=settings&controller=manage', 'admin'));
    }
}
