<?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 {
            $page = (int)$request->input('page', 1);
            $perPage = (int)$request->input('per_page', 15);

            $query = Announcement::where('employer_id', $employer->id)->latest();
            $total = $query->count();
            $offset = ($page - 1) * $perPage;

            $announcements = $query->skip($offset)->take($perPage)->get()
                ->map(function ($announcement) {
                    return [
                        'id' => $announcement->id,
                        'title' => $announcement->title,
                        'body' => $announcement->body,
                        'type' => $announcement->type,
                        'status' => $announcement->status ?? 'pending',
                        'remarks' => $announcement->remarks,
                        'created_at' => $announcement->created_at->toISOString(),
                        'time_ago' => $announcement->created_at->diffForHumans(),
                    ];
                });

            return response()->json([
                'success' => true,
                'data' => [
                    'announcements' => $announcements,
                    'pagination' => [
                        'total' => $total,
                        'per_page' => $perPage,
                        'current_page' => $page,
                        'last_page' => max(1, (int)ceil($total / $perPage)),
                    ]
                ]
            ], 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_without:content|string|max:5000',
            'content' => 'required_without:body|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 {
            $bodyText = $request->body ?? $request->content;
            
            // Append extra event details if they are provided
            $extras = [];
            if ($request->event_date) $extras[] = "Date: " . $request->event_date;
            if ($request->event_time) $extras[] = "Time: " . $request->event_time;
            if ($request->location_details) $extras[] = "Location: " . $request->location_details;
            if ($request->location_pin) $extras[] = "Map Pin: " . $request->location_pin;
            if ($request->provided_items) $extras[] = "Provided: " . $request->provided_items;
            
            if (!empty($extras)) {
                $bodyText .= "\n\n" . implode("\n", $extras);
            }

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

            return response()->json([
                'success' => true,
                'message' => 'Announcement posted successfully.',
                'data' => [
                    'announcement' => [
                        'id' => $announcement->id,
                        'title' => $announcement->title,
                        'body' => $announcement->body,
                        'type' => $announcement->type,
                        'status' => $announcement->status ?? 'pending',
                        'remarks' => $announcement->remarks,
                        '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);
        }
    }
}
