<?php

namespace Mtc\Plugins\MembersMessaging\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Mtc\Core\Permissions;
use Mtc\Plugins\MembersMessaging\Models\Message;

class SatisfactoryController extends Controller
{

    public static $satisfactory_options = [
        1 => 'Great',
        2 => 'Okay',
        3 => 'Not Good',
    ];
    
    public function displayOption($option): string
    {
        return self::$satisfactory_options[$option] ?? 'Unknown';
    }

    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $selected_satisfactory = $request->query('satisfactory', 0);

        $messages = Message::query()
            ->where('satisfactory', '>', 0);

        if (!empty($selected_satisfactory)) {
            $messages->where('satisfactory', (int)$selected_satisfactory);
        }

        $satisfactory_options = self::$satisfactory_options;

        $messages_result = $messages
            ->with('thread')
            ->has('thread')
            ->orderBy('updated_at', 'DESC')
            ->paginate(25);

        if ($selected_satisfactory > 0) {
            $satisfactory_name = self::$satisfactory_options[(int)$selected_satisfactory];
            session()->flash('success', 'Messages filtered by satisfactory rating: ' . $satisfactory_name);
        }

        return app('twig')->render('membersmessaging/admin/satisfactory.twig', [
            'can_edit_templates' => Permissions::can(Permissions::EDIT_MESSAGE_TEMPLATES),
            'current_path' => $request->url(),
            'messages' => $messages_result->items(),
            'messages_result' => $messages_result,
            'satisfactory_options' => $satisfactory_options,
            'selected_satisfactory' => $selected_satisfactory,
            'success' => session('success'),
            'error' => session('error'),
            'warning' => session('warning'),
        ]);
    }


    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'satisfactory' => 'required|integer',
        ]);

        $message = Message::find($request->message_id);

        if (!$message) {
            return response()->json(['error' => 'Message not found'], 404);
        }

        $message->satisfactory = $request->satisfactory;
        $message->comment = $request->comment;
        $message->save();

        return response()->json([
            'message_id' => $message->id,
            'success' => '<p class="success">Thanks for your feedback!</p>',
        ]);
    }
}
