<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SystemMessage;
use Illuminate\Http\Request;
use Inertia\Inertia;

class SystemMessageController extends Controller
{
    /**
     * Display a listing of system messages
     */
    public function index()
    {
        $messages = SystemMessage::with('users')->orderBy('display_order')->get();

        return Inertia::render('admin/system-messages/index', [
            'messages' => $messages
        ]);
    }

    /**
     * Show the form for creating a new system message
     */
    public function create()
    {
        $users = \App\Models\User::where('role', 'user')->get();

        return Inertia::render('admin/system-messages/create', [
            'users' => $users
        ]);
    }

    /**
     * Store a newly created system message
     */
    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'message' => 'required|string|max:1000',
            'display_order' => 'nullable|integer|min:0',
            'user_ids' => 'array',
            'user_ids.*' => 'exists:users,id',
        ]);

        // Set display order if not provided
        if (!$request->display_order) {
            $maxOrder = SystemMessage::max('display_order') ?? 0;
            $request->merge(['display_order' => $maxOrder + 1]);
        }

        $message = SystemMessage::create($request->only(['title', 'message', 'display_order', 'is_active']));

        if (!empty($request->user_ids))
            $message->users()->attach($request->user_ids);

        return redirect()->route('admin.system-messages.index')
            ->with('success', 'Mesej sistem berjaya ditambah!');
    }

    /**
     * Show the form for editing the specified system message
     */
    public function edit(SystemMessage $systemMessage)
    {
        $users = \App\Models\User::where('role', 'user')->get();
        $systemMessage->load('users');

        return Inertia::render('admin/system-messages/edit', [
            'message' => $systemMessage,
            'users' => $users
        ]);
    }

    /**
     * Update the specified system message
     */
    public function update(Request $request, SystemMessage $systemMessage)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'message' => 'required|string|max:1000',
            'display_order' => 'nullable|integer|min:0',
            'user_ids' => 'required|array|min:1',
            'user_ids.*' => 'exists:users,id',
        ]);

        $systemMessage->update($request->only(['title', 'message', 'display_order', 'is_active']));

        // Sync users for the message
        $systemMessage->users()->sync($request->user_ids);

        return redirect()->route('admin.system-messages.index')
            ->with('success', 'Mesej sistem berjaya dikemas kini!');
    }

    /**
     * Toggle the active status of a system message
     */
    public function toggleStatus(SystemMessage $systemMessage)
    {
        $systemMessage->update(['is_active' => !$systemMessage->is_active]);

        $status = $systemMessage->is_active ? 'diaktifkan' : 'dinyahaktifkan';
        return redirect()->route('admin.system-messages.index')
            ->with('success', "Mesej sistem telah {$status}!");
    }

    /**
     * Update the display order of system messages
     */
    public function updateOrder(Request $request)
    {
        $request->validate([
            'messages' => 'required|array',
            'messages.*.id' => 'required|exists:system_messages,id',
            'messages.*.display_order' => 'required|integer|min:0',
        ]);

        foreach ($request->messages as $messageData) {
            SystemMessage::where('id', $messageData['id'])
                ->update(['display_order' => $messageData['display_order']]);
        }

        return response()->json(['success' => true]);
    }

    /**
     * Remove the specified system message
     */
    public function destroy(SystemMessage $systemMessage)
    {
        $systemMessage->delete();

        return redirect()->route('admin.system-messages.index')
            ->with('success', 'Mesej sistem berjaya dipadam!');
    }
}
