<?php

namespace App\Http\Controllers\Api;

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

class AnnouncementController extends Controller
{
    // Public: active messages only
    public function index(): JsonResponse
    {
        $messages = AnnouncementMessage::where('is_active', true)
            ->orderBy('sort_order')
            ->orderBy('id')
            ->get(['id', 'text', 'link']);

        return response()->json(['data' => $messages]);
    }

    // Admin: all messages
    public function adminIndex(): JsonResponse
    {
        $messages = AnnouncementMessage::orderBy('sort_order')->orderBy('id')->get();
        return response()->json(['data' => $messages]);
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'text'       => 'required|string|max:255',
            'link'       => 'nullable|string|max:500',
            'is_active'  => 'sometimes|boolean',
            'sort_order' => 'sometimes|integer',
        ]);

        $msg = AnnouncementMessage::create($data);
        return response()->json(['data' => $msg], 201);
    }

    public function update(Request $request, int $id): JsonResponse
    {
        $msg = AnnouncementMessage::findOrFail($id);

        $data = $request->validate([
            'text'       => 'sometimes|string|max:255',
            'link'       => 'nullable|string|max:500',
            'is_active'  => 'sometimes|boolean',
            'sort_order' => 'sometimes|integer',
        ]);

        $msg->update($data);
        return response()->json(['data' => $msg]);
    }

    public function destroy(int $id): JsonResponse
    {
        AnnouncementMessage::findOrFail($id)->delete();
        return response()->json(['message' => 'Deleted']);
    }

    public function reorder(Request $request): JsonResponse
    {
        $request->validate(['ids' => 'required|array', 'ids.*' => 'integer']);
        foreach ($request->ids as $i => $id) {
            AnnouncementMessage::where('id', $id)->update(['sort_order' => $i]);
        }
        return response()->json(['message' => 'Reordered']);
    }
}
