<?php
require_once APP_PATH . '/Core/BaseController.php';
require_once APP_PATH . '/Models/Message.php';
require_once APP_PATH . '/Models/Notification.php';
require_once APP_PATH . '/Core/CSRF.php';

class MessageController extends BaseController {

    private Message $msgModel;
    private Notification $notifModel;

    public function __construct() {
        $this->msgModel   = new Message();
        $this->notifModel = new Notification();
    }

    // ── GET /messages ─────────────────────────────────────────────
    public function index(): void {
        $conversations = $this->msgModel->getConversations(Auth::id());
        $this->view('messages.index', [
            'title'         => 'Messages — BOAFO',
            'conversations' => $conversations,
        ]);
    }

    // ── GET /messages/{conversationId} ───────────────────────────
    public function conversation(string $conversationId): void {
        $convId = (int) $conversationId;
        if (!$this->msgModel->canAccessConversation($convId, Auth::id())) {
            http_response_code(403);
            $this->view('errors.403', ['title'=>'Forbidden']);
            return;
        }

        $messages      = $this->msgModel->getMessages($convId);
        $conversations = $this->msgModel->getConversations(Auth::id());

        // Mark as read
        $this->msgModel->markRead($convId, Auth::id());

        // Get conversation details
        $db   = Database::getInstance();
        $stmt = $db->prepare("SELECT c.*, s.first_name AS s_first, s.last_name AS s_last, s.avatar AS s_avatar, m.first_name AS m_first, m.last_name AS m_last, m.avatar AS m_avatar FROM conversations c JOIN users s ON s.id = c.student_id JOIN users m ON m.id = c.mentor_id WHERE c.id = ?");
        $stmt->execute([$convId]);
        $conversation = $stmt->fetch();

        $this->view('messages.conversation', [
            'title'           => 'Messages — BOAFO',
            'conversations'   => $conversations,
            'active_conv'     => $conversation,
            'messages'        => $messages,
            'conversation_id' => $convId,
        ]);
    }

    // ── POST /api/messages/send ───────────────────────────────────
    public function send(): void {
        CSRF::check();

        $convId = (int) $this->input('conversation_id', 0);
        $body   = trim($this->input('body', ''));

        if (!$convId || empty($body)) {
            $this->json(['success'=>false,'message'=>'Invalid request.'], 400);
        }

        if (!$this->msgModel->canAccessConversation($convId, Auth::id())) {
            $this->json(['success'=>false,'message'=>'Access denied.'], 403);
        }

        $messageId = $this->msgModel->sendMessage($convId, Auth::id(), $this->sanitize($body));

        // Get message with sender info
        $db   = Database::getInstance();
        $stmt = $db->prepare(
            "SELECT m.*, u.first_name, u.last_name, u.avatar, u.role
             FROM messages m JOIN users u ON u.id = m.sender_id
             WHERE m.id = ?"
        );
        $stmt->execute([$messageId]);
        $message = $stmt->fetch();

        // Notify the other person
        $db2 = Database::getInstance();
        $stmt2 = $db2->prepare("SELECT * FROM conversations WHERE id = ?");
        $stmt2->execute([$convId]);
        $conv = $stmt2->fetch();
        $recipientId = Auth::id() === $conv['student_id'] ? $conv['mentor_id'] : $conv['student_id'];
        $sender = Auth::user();
        $this->notifModel->send(
            $recipientId, 'new_message', 'New Message',
            "{$sender['name']} sent you a message.",
            APP_URL . "/messages/{$convId}"
        );

        $this->json(['success'=>true,'message'=>$message]);
    }

    // ── POST /api/messages/mark-read ─────────────────────────────
    public function markRead(): void {
        $convId = (int) $this->input('conversation_id', 0);
        if ($this->msgModel->canAccessConversation($convId, Auth::id())) {
            $this->msgModel->markRead($convId, Auth::id());
        }
        $this->json(['success'=>true]);
    }

    // ── GET /api/messages/unread-count ───────────────────────────
    public function unreadCount(): void {
        $count = $this->msgModel->getTotalUnread(Auth::id());
        $this->json(['count'=>$count]);
    }
}
