<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Services\SettingsService;

class AdminSettingsController extends Controller
{
    private SettingsService $settings;

    public function __construct()
    {
        $this->settings = new SettingsService();
    }

    public function payments(): string
    {
        require_role('admin');

        return $this->view('admin/settings/payments', [
            'title' => 'Configuracoes de pagamento',
            'settings' => $this->settings->group('payments'),
            'methods' => $this->settings->paymentMethods(),
        ]);
    }

    public function updatePayments(Request $request): void
    {
        require_role('admin');

        if (!verify_csrf((string) $request->post('_csrf_token', ''))) {
            flash('error', 'Sessao expirada. Tente novamente.');
            app()->response()->back();
        }

        $checkboxes = [
            'payment_bank_enabled',
            'payment_mpesa_enabled',
            'payment_emola_enabled',
            'payment_mkesh_enabled',
        ];
        $values = [
            'payment_bank_name' => (string) $request->post('payment_bank_name', ''),
            'payment_bank_account' => (string) $request->post('payment_bank_account', ''),
            'payment_bank_holder' => (string) $request->post('payment_bank_holder', ''),
            'payment_bank_nib' => (string) $request->post('payment_bank_nib', ''),
            'payment_mpesa_number' => (string) $request->post('payment_mpesa_number', ''),
            'payment_mpesa_holder' => (string) $request->post('payment_mpesa_holder', ''),
            'payment_emola_number' => (string) $request->post('payment_emola_number', ''),
            'payment_emola_holder' => (string) $request->post('payment_emola_holder', ''),
            'payment_mkesh_number' => (string) $request->post('payment_mkesh_number', ''),
            'payment_mkesh_holder' => (string) $request->post('payment_mkesh_holder', ''),
            'payment_manual_instructions' => (string) $request->post('payment_manual_instructions', ''),
        ];

        foreach ($checkboxes as $key) {
            $values[$key] = $request->post($key) ? '1' : '0';
        }

        $this->settings->updateMany($values, 'payments', (int) current_user()['id']);
        flash('success', 'Configuracoes de pagamento actualizadas.');
        app()->response()->redirect('/admin/settings/payments');
    }
}
