<?php

declare(strict_types=1);

namespace App\Services;

use App\Core\FileStore;

class SettingsService
{
    private FileStore $store;

    public function __construct()
    {
        $this->store = new FileStore(storage_path('data/settings.json'));
        $this->seedDefaults();
    }

    public function get(string $key, mixed $default = null): mixed
    {
        foreach ($this->store->all() as $setting) {
            if (($setting['key'] ?? null) === $key) {
                return $setting['value'];
            }
        }

        return $default;
    }

    public function group(string $group): array
    {
        $settings = [];

        foreach ($this->store->all() as $setting) {
            if (($setting['group'] ?? '') === $group) {
                $settings[(string) $setting['key']] = $setting['value'];
            }
        }

        return $settings;
    }

    public function updateMany(array $values, string $group, int $adminId): void
    {
        $records = $this->store->all();
        $known = array_column($records, 'key');

        foreach ($values as $key => $value) {
            $updated = false;

            foreach ($records as $index => $setting) {
                if (($setting['key'] ?? '') === $key) {
                    $records[$index]['value'] = is_string($value) ? trim($value) : $value;
                    $records[$index]['group'] = $setting['group'] ?? $group;
                    $updated = true;
                    break;
                }
            }

            if (!$updated && !in_array($key, $known, true)) {
                $records[] = [
                    'id' => $this->nextId($records),
                    'key' => $key,
                    'value' => is_string($value) ? trim($value) : $value,
                    'group' => $group,
                ];
            }
        }

        $this->store->save($records);
        (new ActivityLogService())->log('settings_updated', "Configuracoes {$group} actualizadas.", $adminId);
    }

    public function paymentMethods(): array
    {
        return [
            [
                'key' => 'bank',
                'label' => 'Transferencia bancaria',
                'enabled' => $this->get('payment_bank_enabled', '1') === '1',
                'lines' => [
                    'Banco: ' . $this->get('payment_bank_name', 'Definir no admin'),
                    'Conta: ' . $this->get('payment_bank_account', '000000000'),
                    'Titular: ' . $this->get('payment_bank_holder', 'Moz Cursos'),
                    'NIB/IBAN: ' . $this->get('payment_bank_nib', '-'),
                ],
            ],
            [
                'key' => 'mpesa',
                'label' => 'M-Pesa manual',
                'enabled' => $this->get('payment_mpesa_enabled', '1') === '1',
                'lines' => [
                    'Numero: ' . $this->get('payment_mpesa_number', '+258 84 000 0000'),
                    'Nome: ' . $this->get('payment_mpesa_holder', 'Moz Cursos'),
                ],
            ],
            [
                'key' => 'emola',
                'label' => 'e-Mola manual',
                'enabled' => $this->get('payment_emola_enabled', '1') === '1',
                'lines' => [
                    'Numero: ' . $this->get('payment_emola_number', '+258 86 000 0000'),
                    'Nome: ' . $this->get('payment_emola_holder', 'Moz Cursos'),
                ],
            ],
            [
                'key' => 'mkesh',
                'label' => 'mKesh manual',
                'enabled' => $this->get('payment_mkesh_enabled', '0') === '1',
                'lines' => [
                    'Numero: ' . $this->get('payment_mkesh_number', '+258 82 000 0000'),
                    'Nome: ' . $this->get('payment_mkesh_holder', 'Moz Cursos'),
                ],
            ],
        ];
    }

    private function seedDefaults(): void
    {
        if ($this->store->all()) {
            return;
        }

        $this->store->save([
            ['id' => 1, 'key' => 'app_name', 'value' => env('APP_NAME', 'Moz Cursos'), 'group' => 'general'],
            ['id' => 2, 'key' => 'currency', 'value' => env('DEFAULT_CURRENCY', 'MZN'), 'group' => 'finance'],
            ['id' => 3, 'key' => 'platform_commission_percentage', 'value' => env('PLATFORM_COMMISSION_PERCENTAGE', '20'), 'group' => 'finance'],
            ['id' => 4, 'key' => 'payment_bank_enabled', 'value' => '1', 'group' => 'payments'],
            ['id' => 5, 'key' => 'payment_bank_name', 'value' => 'Definir no admin', 'group' => 'payments'],
            ['id' => 6, 'key' => 'payment_bank_account', 'value' => '000000000', 'group' => 'payments'],
            ['id' => 7, 'key' => 'payment_bank_holder', 'value' => 'Moz Cursos', 'group' => 'payments'],
            ['id' => 8, 'key' => 'payment_bank_nib', 'value' => '-', 'group' => 'payments'],
            ['id' => 9, 'key' => 'payment_mpesa_enabled', 'value' => '1', 'group' => 'payments'],
            ['id' => 10, 'key' => 'payment_mpesa_number', 'value' => '+258 84 000 0000', 'group' => 'payments'],
            ['id' => 11, 'key' => 'payment_mpesa_holder', 'value' => 'Moz Cursos', 'group' => 'payments'],
            ['id' => 12, 'key' => 'payment_emola_enabled', 'value' => '1', 'group' => 'payments'],
            ['id' => 13, 'key' => 'payment_emola_number', 'value' => '+258 86 000 0000', 'group' => 'payments'],
            ['id' => 14, 'key' => 'payment_emola_holder', 'value' => 'Moz Cursos', 'group' => 'payments'],
            ['id' => 15, 'key' => 'payment_mkesh_enabled', 'value' => '0', 'group' => 'payments'],
            ['id' => 16, 'key' => 'payment_mkesh_number', 'value' => '+258 82 000 0000', 'group' => 'payments'],
            ['id' => 17, 'key' => 'payment_mkesh_holder', 'value' => 'Moz Cursos', 'group' => 'payments'],
            ['id' => 18, 'key' => 'payment_manual_instructions', 'value' => 'Depois de pagar, envie o comprovativo nesta pagina usando a referencia do pedido.', 'group' => 'payments'],
        ]);
    }

    private function nextId(array $records): int
    {
        $ids = array_column($records, 'id');

        return $ids ? max($ids) + 1 : 1;
    }
}
