<?php

namespace App\Helpers;

use App\Models\Company;

class ExpenseDocumentSettings
{
    public static function config(): array
    {
        return config('expense.document_settings', []);
    }

    public static function defaultOptions(): array
    {
        $options = [];
        foreach (self::config()['options'] ?? [] as $key => $meta) {
            $options[$key] = (bool) ($meta['default'] ?? false);
        }

        return $options;
    }

    public static function defaultLabels(): array
    {
        $labels = [];
        foreach (self::config()['labels'] ?? [] as $key => $meta) {
            $labels[$key] = $meta['default'] ?? '';
        }

        return $labels;
    }

    public static function forCompany(?int $companyId = null): array
    {
        return [
            'options' => self::optionsForCompany($companyId),
            'labels' => self::labelsForCompany($companyId),
        ];
    }

    public static function optionsForCompany(?int $companyId = null): array
    {
        return array_merge(
            self::defaultOptions(),
            self::stored($companyId)['options'] ?? []
        );
    }

    public static function labelsForCompany(?int $companyId = null): array
    {
        return array_merge(
            self::defaultLabels(),
            self::stored($companyId)['labels'] ?? []
        );
    }

    public static function option(string $key, ?int $companyId = null): bool
    {
        $options = self::optionsForCompany($companyId);

        return (bool) ($options[$key] ?? self::defaultOptions()[$key] ?? false);
    }

    public static function label(string $key, ?int $companyId = null): string
    {
        $labels = self::labelsForCompany($companyId);

        return (string) ($labels[$key] ?? self::defaultLabels()[$key] ?? '');
    }

    public static function title(?int $companyId = null): string
    {
        return self::label('title_expense', $companyId) ?: config('expense.title', 'EXPENSE');
    }

    public static function update(int $companyId, array $options, array $labels): Company
    {
        $company = Company::findOrFail($companyId);
        $settings = is_array($company->settings) ? $company->settings : [];

        $settings['expense_documents'] = [
            'options' => collect($options)->only(array_keys(self::defaultOptions()))->all(),
            'labels' => collect($labels)->only(array_keys(self::defaultLabels()))->all(),
        ];

        $company->settings = $settings;
        $company->save();

        return $company->fresh();
    }

    private static function stored(?int $companyId): array
    {
        if (! $companyId) {
            return [];
        }

        $company = Company::find($companyId);

        if (! $company || ! is_array($company->settings)) {
            return [];
        }

        return is_array($company->settings['expense_documents'] ?? null)
            ? $company->settings['expense_documents']
            : [];
    }
}
