<?php

declare(strict_types=1);

namespace App\Http\Controllers\Support;

use App\Enums\UserActions;
use App\Http\Controllers\Helpers\Permissions\UserPermissions;
use App\Http\Controllers\Helpers\ResponseHelper;
use App\Models\Announcement;
use Hypervel\Http\Request;
use Hypervel\Support\Facades\Auth;
use Hypervel\Support\Facades\Validator;

class AnnouncementController
{
    /**
     * Get active announcements for general use (e.g. home page)
     */
    public function latest()
    {
        $announcements = Announcement::active()
            ->orderBy('created_at', 'desc')
            ->get();

        return response()->json($announcements);
    }

    /**
     * List all announcements (Admin view)
     */
    public function index()
    {
        if (!UserPermissions::isActionPermitted(Auth::user()->acct_type, UserActions::ViewAllAnnouncements)) {
            return ResponseHelper::returnUnauthorized();
        }

        $announcements = Announcement::orderBy('created_at', 'desc')->get();
        return response()->json($announcements);
    }

    /**
     * Store a new announcement
     */
    public function store(Request $request)
    {
        if (!UserPermissions::isActionPermitted(Auth::user()->acct_type, UserActions::CreateAnnouncement)) {
            return ResponseHelper::returnUnauthorized();
        }

        $validator = Validator::make($request->all(), [
            'title' => 'required|string|max:255',
            'content' => 'required|string',
            'photo' => 'nullable|string',
            'type' => 'required|string|in:info,success,warning,danger',
            'is_active' => 'boolean',
            'starts_at' => 'nullable|date',
            'ends_at' => 'nullable|date',
        ]);

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

        $data = $validator->validated();
        $data['created_by'] = Auth::id();

        // Convert boolean to integer for DB
        $data['is_active'] = isset($data['is_active']) ? (bool)$data['is_active'] : true;

        $announcement = Announcement::create($data);

        return response()->json([
            'success' => true,
            'message' => 'Announcement created successfully',
            'announcement' => $announcement
        ]);
    }

    /**
     * Update an announcement
     */
    public function update(Request $request)
    {
        if (!UserPermissions::isActionPermitted(Auth::user()->acct_type, UserActions::ModifyAnnouncement)) {
            return ResponseHelper::returnUnauthorized();
        }

        $hash = $request->input('target');
        $announcement = Announcement::where('hashkey', $hash)->first();
        if (!$announcement) {
            return response()->json(['success' => false, 'message' => 'Announcement not found'], 404);
        }

        $validator = Validator::make($request->all(), [
            'title' => 'required|string|max:255',
            'content' => 'required|string',
            'photo' => 'nullable|string',
            'type' => 'required|string|in:info,success,warning,danger',
            'is_active' => 'boolean',
            'starts_at' => 'nullable|date',
            'ends_at' => 'nullable|date',
        ]);

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

        $data = $validator->validated();
        $data['is_active'] = isset($data['is_active']) ? (bool)$data['is_active'] : $announcement->is_active;

        $announcement->update($data);

        return response()->json([
            'success' => true,
            'message' => 'Announcement updated successfully',
            'announcement' => $announcement
        ]);
    }

    /**
     * Delete an announcement
     */
    public function destroy(Request $request)
    {
        if (!UserPermissions::isActionPermitted(Auth::user()->acct_type, UserActions::DeleteAnnouncement)) {
            return ResponseHelper::returnUnauthorized();
        }

        $hash = $request->input('target');
        $announcement = Announcement::where('hashkey', $hash)->first();
        if ($announcement) {
            $announcement->delete();
        }

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

    /**
     * Toggle active status
     */
    public function toggleStatus(Request $request)
    {
        if (!UserPermissions::isActionPermitted(Auth::user()->acct_type, UserActions::ModifyAnnouncement)) {
            return ResponseHelper::returnUnauthorized();
        }

        $hash = $request->input('target');
        $announcement = Announcement::where('hashkey', $hash)->first();
        if (!$announcement) {
            return response()->json(['success' => false, 'message' => 'Announcement not found'], 404);
        }

        $announcement->is_active = !$announcement->is_active;
        $announcement->save();

        return response()->json([
            'success' => true,
            'is_active' => $announcement->is_active,
            'message' => 'Status updated'
        ]);
    }
}
