<?php

namespace Maestro\Core\Http\Controllers;

use Maestro\Core\Models\OrganizationSetting;
use Illuminate\Routing\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class OrganizationSettingController extends Controller
{
    /**
     * Default attributes for the single organization row (used when creating).
     */
    private function defaults(): array
    {
        return [
            'company_name' => '',
            'street' => null,
            'house_number' => null,
            'postal_code' => null,
            'city' => null,
            'country' => 'Nederland',
            'website' => null,
            'phone' => null,
            'email' => null,
            'invoice_email' => null,
            'kvk_number' => null,
            'vat_number' => null,
            'iban' => null,
            'contact_name' => null,
        ];
    }

    /**
     * Return the single organization settings row. Create with defaults if missing.
     */
    public function show(): JsonResponse
    {
        $setting = OrganizationSetting::first();

        if (! $setting) {
            $setting = OrganizationSetting::create($this->defaults());
        }

        return response()->json($setting);
    }

    /**
     * Update the organization settings.
     */
    public function update(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'company_name' => 'required|string|max:255',
            'street' => 'nullable|string|max:255',
            'house_number' => 'nullable|string|max:255',
            'postal_code' => 'nullable|string|max:255',
            'city' => 'nullable|string|max:255',
            'country' => 'nullable|string|max:255',
            'website' => 'nullable|url|max:255',
            'phone' => 'nullable|string|max:50',
            'email' => 'nullable|email|max:255',
            'invoice_email' => 'nullable|email|max:255',
            'kvk_number' => 'nullable|string|max:50',
            'vat_number' => 'nullable|string|max:50',
            'iban' => 'nullable|string|max:50',
            'contact_name' => 'nullable|string|max:255',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation failed',
                'errors' => $validator->errors(),
            ], 422);
        }

        $setting = OrganizationSetting::first();

        if (! $setting) {
            $setting = OrganizationSetting::create($this->defaults());
        }

        $setting->update($validator->validated());

        return response()->json([
            'message' => __('messages.updated', ['model' => __('models.company')]),
            'settings' => $setting,
        ]);
    }
}
