<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\PartnerSetting;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class PartnerSettingController extends Controller
{
    /**
     * Get partner settings.
     */
    public function index(Request $request): JsonResponse
    {
        $user = $request->user();

        if (! $user || ! $user->isPartner()) {
            return response()->json([
                'error' => 'Unauthorized',
                'message' => 'Only partners can access this endpoint',
            ], 403);
        }

        $settings = $user->partnerSettings;

        return response()->json([
            'success' => true,
            'data' => [
                'settings' => $settings ? $settings->settings : [],
            ],
        ]);
    }

    /**
     * Update partner settings.
     */
    public function update(Request $request): JsonResponse
    {
        $user = $request->user();

        if (! $user || ! $user->isPartner()) {
            return response()->json([
                'error' => 'Unauthorized',
                'message' => 'Only partners can access this endpoint',
            ], 403);
        }

        $validated = $request->validate([
            'settings' => ['required', 'array'],
        ]);

        $partnerSetting = $user->partnerSettings;

        if ($partnerSetting) {
            $partnerSetting->update([
                'settings' => $validated['settings'],
            ]);
        } else {
            PartnerSetting::create([
                'partner_id' => $user->id,
                'settings' => $validated['settings'],
            ]);
        }

        return response()->json([
            'success' => true,
            'message' => 'Settings updated successfully',
            'data' => [
                'settings' => $validated['settings'],
            ],
        ]);
    }

    /**
     * Get a specific setting value.
     */
    public function show(Request $request, string $key): JsonResponse
    {
        $user = $request->user();

        if (! $user || ! $user->isPartner()) {
            return response()->json([
                'error' => 'Unauthorized',
                'message' => 'Only partners can access this endpoint',
            ], 403);
        }

        $settings = $user->partnerSettings;

        if (! $settings || ! isset($settings->settings[$key])) {
            return response()->json([
                'error' => 'Not Found',
                'message' => "Setting '{$key}' not found",
            ], 404);
        }

        return response()->json([
            'success' => true,
            'data' => [
                'key' => $key,
                'value' => $settings->settings[$key],
            ],
        ]);
    }
}

