<?php

class MessageController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        Auth::checkAuthentication();
    }

    private function isAjaxRequest()
    {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
               strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
    }

    public function send()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $receiver_id = isset($_POST['receiver_id']) ? $_POST['receiver_id'] : null;
            $subject = isset($_POST['subject']) ? $_POST['subject'] : 'No Subject';
            $message = isset($_POST['message']) ? $_POST['message'] : null;

            if (!$receiver_id || !$message) {
                if ($this->isAjaxRequest()) {
                    header('Content-Type: application/json');
                    echo json_encode(['success' => false, 'message' => 'Receiver and message are required']);
                    return;
                }

                Session::add('feedback_negative', 'Receiver and message are required');
                Redirect::to('message');
                return;
            }

            $sender_id = Session::get('user_id');
            $success = MessageModel::sendToUser($sender_id, $receiver_id, $subject, $message);

            if ($this->isAjaxRequest()) {
                header('Content-Type: application/json');
                if ($success) {
                    echo json_encode(['success' => true, 'message' => 'Message sent successfully']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Failed to send message']);
                }
                return;
            }

            if ($success) {
                Session::add('feedback_positive', 'Message sent successfully');
            } else {
                Session::add('feedback_negative', 'Failed to send message');
            }

            if (isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], 'conversation') !== false) {
                Redirect::to('message/conversation/' . $receiver_id);
            } else {
                Redirect::to('message');
            }
            return;
        }

        // GET request: message/send/{receiver_id}/{subject}/{message}
        $url_parts = explode('/', trim($_SERVER['REQUEST_URI'], '/'));
        $receiver_id = isset($url_parts[2]) ? $url_parts[2] : null;
        $subject = isset($url_parts[3]) ? urldecode($url_parts[3]) : null;
        $message = isset($url_parts[4]) ? urldecode($url_parts[4]) : null;

        if (!$receiver_id || !$subject || !$message) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => 'Missing parameters. Use: message/send/{receiver_id}/{subject}/{message}']);
            return;
        }

        $receiver = UserModel::getPublicProfileOfUser($receiver_id);
        if (!$receiver) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => 'Receiver not found']);
            return;
        }

        $sender_id = Session::get('user_id');
        $success = MessageModel::sendToUser($sender_id, $receiver_id, $subject, $message);

        header('Content-Type: application/json');
        if ($success) {
            echo json_encode(['success' => true, 'message' => 'Message sent successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to send message']);
        }
    }

    public function sendgroup()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $group_type = isset($_POST['group_type']) ? $_POST['group_type'] : null;
            $subject = isset($_POST['subject']) ? $_POST['subject'] : 'No Subject';
            $message = isset($_POST['message']) ? $_POST['message'] : null;

            if (!$group_type || !$message) {
                Session::add('feedback_negative', 'Group type and message are required');
                Redirect::to('message');
                return;
            }

            if (!in_array($group_type, ['admins', 'moderators', 'all_users'])) {
                Session::add('feedback_negative', 'Invalid group type');
                Redirect::to('message');
                return;
            }

            $sender_id = Session::get('user_id');
            $success = MessageModel::sendToGroup($sender_id, $group_type, $subject, $message);

            if ($success) {
                Session::add('feedback_positive', 'Message sent to group successfully');
            } else {
                Session::add('feedback_negative', 'Failed to send message to group');
            }

            Redirect::to('message');
            return;
        }

        // GET request: message/sendgroup/{group_type}/{subject}/{message}
        $url_parts = explode('/', trim($_SERVER['REQUEST_URI'], '/'));
        $group_type = isset($url_parts[2]) ? $url_parts[2] : null;
        $subject = isset($url_parts[3]) ? urldecode($url_parts[3]) : null;
        $message = isset($url_parts[4]) ? urldecode($url_parts[4]) : null;

        if (!$group_type || !$subject || !$message) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => 'Missing parameters. Use: message/sendgroup/{group_type}/{subject}/{message}']);
            return;
        }

        if (!in_array($group_type, ['admins', 'moderators', 'all_users'])) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => 'Invalid group type. Must be: admins, moderators, or all_users']);
            return;
        }

        $sender_id = Session::get('user_id');
        $success = MessageModel::sendToGroup($sender_id, $group_type, $subject, $message);

        header('Content-Type: application/json');
        if ($success) {
            echo json_encode(['success' => true, 'message' => 'Message sent to group successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to send message to group']);
        }
    }

    public function reply()
    {
        while (ob_get_level()) ob_end_clean();

        header('Content-Type: application/json');

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            echo json_encode(['success' => false, 'message' => 'Invalid request method']);
            exit();
        }

        $receiver_id = isset($_POST['receiver_id']) ? $_POST['receiver_id'] : null;
        $message = isset($_POST['message']) ? $_POST['message'] : null;

        if (!$receiver_id || !$message) {
            echo json_encode(['success' => false, 'message' => 'Receiver and message are required']);
            exit();
        }

        $sender_id = Session::get('user_id');
        if (!$sender_id) {
            echo json_encode(['success' => false, 'message' => 'Not logged in']);
            exit();
        }

        $success = MessageModel::sendToUser($sender_id, $receiver_id, 'Direct Message', $message);

        if ($success) {
            echo json_encode(['success' => true, 'message' => 'Reply sent successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to send reply']);
        }
        exit();
    }

    public function global()
    {
        Redirect::to('message#load-global');
    }

    public function index()
    {
        $user_id = Session::get('user_id');

        $conversations = MessageModel::getConversations($user_id);
        $unread_count = MessageModel::getUnreadCount($user_id);

        $this->View->render('message/index', array(
            'conversations' => $conversations,
            'unread_count' => $unread_count,
            'all_users' => MessageModel::getAllUsers($user_id)
        ));
    }

    public function conversation()
    {
        $user_id = Session::get('user_id');
        $url_parts = explode('/', trim($_SERVER['REQUEST_URI'], '/'));
        $other_user_id = isset($url_parts[2]) ? $url_parts[2] : null;

        if (!$other_user_id) {
            Redirect::to('message');
            return;
        }

        $other_user = UserModel::getPublicProfileOfUser($other_user_id);
        if (!$other_user) {
            Redirect::to('message');
            return;
        }

        Redirect::to('message#load-conversation-' . $other_user_id);
    }

    public function getConversationMessages()
    {
        while (ob_get_level()) ob_end_clean();

        $user_id = Session::get('user_id');
        $url_parts = explode('/', trim($_SERVER['REQUEST_URI'], '/'));
        $other_user_id = isset($url_parts[2]) ? $url_parts[2] : null;

        header('Content-Type: application/json');

        if (!$other_user_id) {
            echo json_encode(['success' => false, 'message' => 'Missing user ID']);
            exit();
        }

        $messages = MessageModel::getMessagesWithUser($user_id, $other_user_id);
        MessageModel::markAsRead($user_id, $other_user_id);

        echo json_encode(['success' => true, 'messages' => $messages]);
        exit();
    }

    public function getGlobalMessages()
    {
        while (ob_get_level()) ob_end_clean();

        header('Content-Type: application/json');
        $messages = MessageModel::getGlobalMessages();
        echo json_encode(['success' => true, 'messages' => $messages]);
        exit();
    }

    public function sendToGlobal()
    {
        while (ob_get_level()) ob_end_clean();

        header('Content-Type: application/json');

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            echo json_encode(['success' => false, 'message' => 'Invalid request method']);
            exit();
        }

        $message = isset($_POST['message']) ? $_POST['message'] : null;
        $sender_id = Session::get('user_id');

        if (!$message) {
            echo json_encode(['success' => false, 'message' => 'Message is required']);
            exit();
        }

        if (!$sender_id) {
            echo json_encode(['success' => false, 'message' => 'Not logged in']);
            exit();
        }

        $success = MessageModel::sendToGlobal($sender_id, $message);

        if ($success) {
            echo json_encode(['success' => true, 'message' => 'Message sent to global chat']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to send message']);
        }
        exit();
    }

    public function unreadcount()
    {
        while (ob_get_level()) ob_end_clean();

        $user_id = Session::get('user_id');
        $unread_count = MessageModel::getUnreadCount($user_id);

        header('Content-Type: application/json');
        echo json_encode(['unread_count' => $unread_count]);
        exit();
    }
}
