<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Profile;
use App\Http\Resources\ProfileResource;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class ProfileController extends Controller
{
    /**
     * Get the organization profile (singleton - always returns the first record).
     * GET /api/profile
     */
    public function show(): JsonResponse
    {
        $profile = Profile::first();

        if (!$profile) {
            return response()->json([
                'success' => true,
                'data' => null,
                'message' => 'Profile not yet configured.',
            ]);
        }

        return response()->json([
            'success' => true,
            'data' => new ProfileResource($profile),
        ]);
    }

    /**
     * Create or update the organization profile.
     * POST /api/profile
     */
    public function storeOrUpdate(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'history'      => 'nullable|string',
            'history_image'=> 'nullable|image|max:2048',
            'vision'       => 'nullable|string',
            'mission'      => 'nullable|string',
            'contact_info' => 'nullable|string',
        ]);

        $profile = Profile::first();
        if (!$profile) {
            $profile = new Profile();
        }

        $profile->fill([
            'history' => $validated['history'] ?? $profile->history,
            'vision' => $validated['vision'] ?? $profile->vision,
            'mission' => $validated['mission'] ?? $profile->mission,
            'contact_info' => $validated['contact_info'] ?? $profile->contact_info,
        ]);

        if ($request->hasFile('history_image')) {
            if ($profile->history_image) {
                \Illuminate\Support\Facades\Storage::disk('public')->delete($profile->history_image);
            }
            $path = $request->file('history_image')->store('profiles', 'public');
            $profile->history_image = $path;
        }

        $profile->save();

        return response()->json([
            'success' => true,
            'message' => 'Profile saved successfully.',
            'data'    => new ProfileResource($profile),
        ]);
    }
}
