<?php

namespace App\Controllers\Admin;

/**
 * Platform-level Hubtel credentials — used to collect subscription
 * payments FROM hotels (Admin\InvoiceController::requestHubtelPayment()).
 * Mirrors App\Controllers\SettingsController (a tenant's own Hubtel/
 * WhatsApp credentials) one layer up: written to platform_settings via
 * App\Libraries\PlatformSettings, never hardcoded, never in .env — same
 * rule, just the platform's own merchant account instead of a hotel's.
 */
class SettingsController extends BaseAdminController
{
    private const FIELDS = [
        'hubtel.client_id',
        'hubtel.client_secret',
        'hubtel.merchant_account_number',
    ];

    public function index()
    {
        $settings = service('platformSettings');
        $values   = [];

        foreach (self::FIELDS as $key) {
            $values[$key] = $settings->getGroupMasked(explode('.', $key)[0])[$key] ?? null;
        }

        return view('admin/settings/index', [
            'pageTitle' => 'Platform Settings',
            'activeNav' => 'settings',
            'values'    => $values,
        ]);
    }

    public function update()
    {
        $settings = service('platformSettings');

        foreach (self::FIELDS as $key) {
            $posted = $this->request->getPost(str_replace('.', '__', $key));

            // Same blank-keeps-secret / blank-clears-plain convention as
            // App\Controllers\SettingsController — see that class.
            $isSecretField = str_contains($key, 'secret') || str_contains($key, 'token');

            if ($isSecretField && ($posted === null || $posted === '')) {
                continue;
            }

            $settings->set($key, $posted);
        }

        $this->logAdminActivity('settings', 'Updated platform Hubtel settings.');

        return redirect()->to('admin/settings')->with('success', 'Settings saved.');
    }
}
