<?php

namespace App\Services;

use App\Models\Business;
use App\Models\Setting;

class ManagementWorkSettings
{
    public const DEFAULTS = [
        'collection_tasks_enabled' => '0',
        'collection_task_overdue_days' => '1',
        'large_loan_threshold' => '0',
        'large_expense_threshold' => '0',
        'overdue_alert_days' => '30',
        'low_account_balance_threshold' => '0',
        'cash_shortage_threshold' => '0',
        'pending_approval_days' => '1',
        'document_expiry_days' => '30',
    ];

    public function values(Business|int $business): array
    {
        $business = $business instanceof Business ? $business : Business::findOrFail($business);
        $stored = Setting::query()->where('business_id', $business->id)->where('group', 'management')
            ->pluck('value', 'key')->all();
        $values = array_merge(self::DEFAULTS, $stored);

        if (! array_key_exists('large_loan_threshold', $stored) && (float) ($business->manager_approval_threshold ?? 0) > 0) {
            $values['large_loan_threshold'] = (string) $business->manager_approval_threshold;
        }

        return [
            'collection_tasks_enabled' => filter_var($values['collection_tasks_enabled'], FILTER_VALIDATE_BOOL),
            'collection_task_overdue_days' => max(1, (int) $values['collection_task_overdue_days']),
            'large_loan_threshold' => max(0, (float) $values['large_loan_threshold']),
            'large_expense_threshold' => max(0, (float) $values['large_expense_threshold']),
            'overdue_alert_days' => max(1, (int) $values['overdue_alert_days']),
            'low_account_balance_threshold' => max(0, (float) $values['low_account_balance_threshold']),
            'cash_shortage_threshold' => max(0, (float) $values['cash_shortage_threshold']),
            'pending_approval_days' => max(0, (int) $values['pending_approval_days']),
            'document_expiry_days' => max(0, (int) $values['document_expiry_days']),
        ];
    }

    public function store(int $businessId, array $values): void
    {
        foreach (self::DEFAULTS as $key => $default) {
            $value = $values[$key] ?? $default;
            Setting::updateOrCreate(
                ['business_id' => $businessId, 'group' => 'management', 'key' => $key],
                ['value' => is_bool($value) ? ($value ? '1' : '0') : (string) $value, 'type' => is_bool($value) ? 'boolean' : 'number']
            );
        }
    }
}