<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Announcement;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class EmployerAnnouncementController extends Controller
{
    /**
     * Get all announcements posted by this employer.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAnnouncements(Request $request)
    {
        /** @var User $employer */
        $employer = $request->attributes->get('employer');

        try {
            $announcements = Announcement::where('employer_id', $employer->id)
                ->latest()
                ->get()
                ->map(function ($announcement) {
                    return [
                        'id' => $announcement->id,
                        'title' => $announcement->title,
                        'body' => $announcement->body,
                        'type' => $announcement->type,
                        'created_at' => $announcement->created_at->toISOString(),
                        'time_ago' => $announcement->created_at->diffForHumans(),
                    ];
                });

            return response()->json([
                'success' => true,
                'data' => [
                    'announcements' => $announcements
                ]
            ], 200);

        } catch (\Exception $e) {
            logger()->error('Mobile Employer Get Announcements Failure: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'An error occurred while fetching announcements.',
                'error' => app()->environment('local') ? $e->getMessage() : 'Internal Server Error'
            ], 500);
        }
    }

    /**
     * Create a new announcement for workers.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function createAnnouncement(Request $request)
    {
        /** @var User $employer */
        $employer = $request->attributes->get('employer');

        $validator = Validator::make($request->all(), [
            'title' => 'required|string|max:255',
            'body' => 'required|string|max:5000',
            'type' => 'nullable|string|in:info,warning,success',
        ]);

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

        try {
            $announcement = Announcement::create([
                'title' => $request->title,
                'body' => $request->body,
                'type' => $request->type ?? 'info',
                'employer_id' => $employer->id,
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Announcement posted successfully.',
                'data' => [
                    'announcement' => [
                        'id' => $announcement->id,
                        'title' => $announcement->title,
                        'body' => $announcement->body,
                        'type' => $announcement->type,
                        'created_at' => $announcement->created_at->toISOString(),
                        'time_ago' => $announcement->created_at->diffForHumans(),
                    ]
                ]
            ], 201);

        } catch (\Exception $e) {
            logger()->error('Mobile Employer Create Announcement Failure: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'An error occurred while creating the announcement.',
                'error' => app()->environment('local') ? $e->getMessage() : 'Internal Server Error'
            ], 500);
        }
    }

    /**
     * Delete an announcement.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteAnnouncement(Request $request, $id)
    {
        /** @var User $employer */
        $employer = $request->attributes->get('employer');

        try {
            $announcement = Announcement::where('employer_id', $employer->id)
                ->where('id', $id)
                ->first();

            if (!$announcement) {
                return response()->json([
                    'success' => false,
                    'message' => 'Announcement not found or unauthorized.'
                ], 404);
            }

            $announcement->delete();

            return response()->json([
                'success' => true,
                'message' => 'Announcement deleted successfully.'
            ], 200);

        } catch (\Exception $e) {
            logger()->error('Mobile Employer Delete Announcement Failure: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'An error occurred while deleting the announcement.',
                'error' => app()->environment('local') ? $e->getMessage() : 'Internal Server Error'
            ], 500);
        }
    }
}
