<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\Session;
use App\Models\Message;
use App\Models\User;

class MessageController extends Controller
{
    private Message $messageModel;
    private User $userModel;

    public function __construct()
    {
        $this->messageModel = new Message();
        $this->userModel = new User();
    }

    public function index(Request $request): Response
    {
        $dialogs = $this->messageModel->getInbox(Session::get('user_id'));
        return $this->render('user.messages', compact('dialogs'));
    }

    public function show(Request $request, int $id): Response
    {
        $otherUser = $this->userModel->find($id);
        if (!$otherUser) return new Response('User not found', 404);

        $messages = $this->messageModel->getConversation(Session::get('user_id'), $id);
        $this->messageModel->markRead($id, Session::get('user_id'));
        $dialogs = $this->messageModel->getInbox(Session::get('user_id'));

        return $this->render('user.messages', compact('messages', 'otherUser', 'dialogs'));
    }

    public function store(Request $request): Response
    {
        $receiverId = (int)$request->post('receiver_id', 0);
        $message = trim($request->post('message', ''));

        if (!$receiverId || empty($message)) {
            Session::flash('error', 'Message cannot be empty');
            return Response::redirect('/messages/' . $receiverId);
        }

        $this->messageModel->send(Session::get('user_id'), $receiverId, $message);
        return Response::redirect('/messages/' . $receiverId);
    }

    public function delete(Request $request, int $id): Response
    {
        $this->messageModel->deleteConversation(Session::get('user_id'), $id);
        Session::flash('success', 'Conversation deleted');
        return Response::redirect('/messages');
    }
}
