<?php

require_once APP_ROOT . '/models/Listing.php';
require_once APP_ROOT . '/models/Message.php';
require_once APP_ROOT . '/models/User.php';

class MessagesController
{
    private PDO $db;
    
    public function __construct()
    {
        $this->db = Database::getInstance();
    }
    
    public function index(): void
    {
        if (!Session::isLoggedIn()) {
            header('Location: ' . APP_URL . '/login');
            exit;
        }

        $messageModel = new Message();
        $messages = $messageModel->getConversationList(Session::getUserId());
        
        // Group messages by item and fetch listing images
        $groupedMessages = [];
        $listingIds = [];
        
        // First collect all listing IDs
        foreach ($messages as $message) {
            if ($message['listing_id']) {
                $listingIds[] = $message['listing_id'];
            }
        }
        
        // Fetch first images for all listings
        $listingImages = [];
        if (!empty($listingIds)) {
            require_once APP_ROOT . '/models/ListingImage.php';
            $imageModel = new ListingImage();
            $uniqueListingIds = array_unique($listingIds);
            
            foreach ($uniqueListingIds as $listingId) {
                $images = $imageModel->getByListing((int)$listingId);
                if (!empty($images)) {
                    $listingImages[$listingId] = $images[0]; // Get first image
                }
            }
        }
        
        // Group messages by item
        foreach ($messages as $message) {
            $itemKey = $message['listing_id'] ? 'item_' . $message['listing_id'] : 'direct_' . $message['id'];
            
            if (!isset($groupedMessages[$itemKey])) {
                $groupedMessages[$itemKey] = [
                    'listing_id' => $message['listing_id'],
                    'listing_title' => $message['listing_title'],
                    'listing_slug' => $message['listing_slug'],
                    'listing_status' => $message['listing_status'],
                    'listing_image' => $message['listing_id'] ? ($listingImages[$message['listing_id']] ?? null) : null,
                    'messages' => [],
                    'last_message' => $message,
                    'unread_count' => 0
                ];
            }
            
            $groupedMessages[$itemKey]['messages'][] = $message;
            
            // Count unread messages
            if ((int)$message['recipient_id'] === Session::getUserId() && !(int)$message['is_read']) {
                $groupedMessages[$itemKey]['unread_count']++;
            }
        }

        $pageTitle = Lang::get('messages') . ' | ' . Lang::get('app_name');
        $robotsMeta = 'noindex, nofollow';

        require APP_ROOT . '/views/layouts/header.php';
        require APP_ROOT . '/views/messages/index.php';
        require APP_ROOT . '/views/layouts/footer.php';
    }

    public function conversation(string $id): void
    {
        if (!Session::isLoggedIn()) {
            header('Location: ' . APP_URL . '/login');
            exit;
        }

        $messageModel = new Message();
        
        // Check if this is a direct message or item conversation
        if (strpos($id, 'direct_') === 0) {
            // Direct message - get all messages between two users
            $messageId = (int)str_replace('direct_', '', $id);
            $message = $messageModel->findForUser($messageId, Session::getUserId());
            
            if (!$message) {
                http_response_code(404);
                require APP_ROOT . '/views/pages/404.php';
                return;
            }
            
            $otherUserId = (int)$message['sender_id'] === Session::getUserId() 
                ? (int)$message['recipient_id'] 
                : (int)$message['sender_id'];
                
            $messages = $messageModel->getConversationBetweenUsers(Session::getUserId(), $otherUserId);
            $listingInfo = null;
        } else {
            // Item conversation - get all messages for this listing
            $listingId = (int)$id;
            $messages = $messageModel->getConversationForListing(Session::getUserId(), $listingId);
            
            if (empty($messages)) {
                http_response_code(404);
                require APP_ROOT . '/views/pages/404.php';
                return;
            }
            
            $listingInfo = [
                'id' => $messages[0]['listing_id'],
                'title' => $messages[0]['listing_title'],
                'slug' => $messages[0]['listing_slug']
            ];
        }

        // Mark all messages as read
        foreach ($messages as $msg) {
            if ((int)$msg['recipient_id'] === Session::getUserId() && !(int)$msg['is_read']) {
                $messageModel->markRead((int)$msg['id'], Session::getUserId());
            }
        }

        $pageTitle = ($listingInfo ? $listingInfo['title'] : Lang::get('conversation')) . ' | ' . Lang::get('messages') . ' | ' . Lang::get('app_name');
        $robotsMeta = 'noindex, nofollow';

        require APP_ROOT . '/views/layouts/header.php';
        require APP_ROOT . '/views/messages/conversation.php';
        require APP_ROOT . '/views/layouts/footer.php';
    }

    public function show(string $id): void
    {
        if (!Session::isLoggedIn()) {
            header('Location: ' . APP_URL . '/login');
            exit;
        }

        $messageModel = new Message();
        $message = $messageModel->findForUser((int)$id, Session::getUserId());

        if (!$message) {
            http_response_code(404);
            require APP_ROOT . '/views/pages/404.php';
            return;
        }

        if ((int)$message['recipient_id'] === Session::getUserId() && !(int)$message['is_read']) {
            $messageModel->markRead((int)$message['id'], Session::getUserId());
            $message['is_read'] = 1;
        }

        $pageTitle = ($message['subject'] ?: Lang::get('message')) . ' | ' . Lang::get('messages') . ' | ' . Lang::get('app_name');
        $robotsMeta = 'noindex, nofollow';

        require APP_ROOT . '/views/layouts/header.php';
        require APP_ROOT . '/views/messages/show.php';
        require APP_ROOT . '/views/layouts/footer.php';
    }

    public function new(): void
    {
        if (!Session::isLoggedIn()) {
            header('Location: ' . APP_URL . '/login');
            exit;
        }

        $listingId = $_GET['listing_id'] ?? null;
        $toUserId = $_GET['to'] ?? null;

        if (!$listingId || !$toUserId) {
            http_response_code(404);
            require APP_ROOT . '/views/pages/404.php';
            return;
        }

        // Verify listing exists and get details
        $listingModel = new Listing();
        $listing = $listingModel->findById((int)$listingId);

        if (!$listing || (int)$listing['user_id'] !== (int)$toUserId) {
            http_response_code(404);
            require APP_ROOT . '/views/pages/404.php';
            return;
        }

        // Prevent users from messaging themselves
        if ((int)$toUserId === Session::getUserId()) {
            Session::flash('error', Lang::get('cannot_message_self'));
            header('Location: ' . APP_URL . '/marketplace/' . $listing['slug']);
            exit;
        }

        // Get recipient user info
        $userModel = new User();
        $recipient = $userModel->findById((int)$toUserId);

        if (!$recipient) {
            http_response_code(404);
            require APP_ROOT . '/views/pages/404.php';
            return;
        }

        $pageTitle = Lang::get('contact_seller') . ' | ' . Lang::get('app_name');
        $robotsMeta = 'noindex, nofollow';
        
        require APP_ROOT . '/views/layouts/header.php';
        require APP_ROOT . '/views/messages/new.php';
        require APP_ROOT . '/views/layouts/footer.php';
    }

    public function create(): void
    {
        if (!Session::isLoggedIn()) {
            header('Location: ' . APP_URL . '/login');
            exit;
        }

        $listingId = $_POST['listing_id'] ?? null;
        $toUserId = $_POST['to_user_id'] ?? null;
        $message = trim($_POST['body'] ?? '');

        if (!Session::verifyCsrfToken($_POST['csrf_token'] ?? '')) {
            Session::flash('error', Lang::get('invalid_request'));
            header('Location: ' . APP_URL . '/messages/new?listing_id=' . $listingId . '&to=' . $toUserId);
            exit;
        }

        if (!$listingId || !$toUserId || empty($message)) {
            Session::flash('error', Lang::get('message_required'));
            header('Location: ' . APP_URL . '/messages/new?listing_id=' . $listingId . '&to=' . $toUserId);
            exit;
        }

        // Verify listing exists (for replies, listing just needs to exist, not necessarily owned by recipient)
        $listingModel = new Listing();
        $listing = $listingModel->findById((int)$listingId);

        if (!$listing) {
            Session::flash('error', Lang::get('invalid_listing'));
            header('Location: ' . APP_URL . '/marketplace');
            exit;
        }

        // Prevent users from messaging themselves
        if ((int)$toUserId === Session::getUserId()) {
            Session::flash('error', Lang::get('cannot_message_self'));
            header('Location: ' . APP_URL . '/marketplace');
            exit;
        }

        $messageModel = new Message();
        $messageModel->create([
            'sender_id'    => Session::getUserId(),
            'recipient_id' => (int)$toUserId,
            'listing_id'   => (int)$listingId,
            'subject'      => $listing['title'],
            'body'         => $message,
        ]);

        Session::flash('success', Lang::get('message_sent'));
        
        // Check if this is a reply from conversation page
        $fromConversation = $_POST['from_conversation'] ?? null;
        if ($fromConversation) {
            // Redirect back to conversation page
            header('Location: ' . APP_URL . '/messages/conversation/' . $listingId);
        } else {
            // Redirect to marketplace listing (original behavior)
            header('Location: ' . APP_URL . '/marketplace/' . $listing['slug']);
        }
        exit;
    }

    public function delete(string $id): void
    {
        if (!Session::isLoggedIn()) {
            header('Location: ' . APP_URL . '/login');
            exit;
        }

        $messageId = (int)$id;
        $userId = Session::getUserId();

        require_once APP_ROOT . '/models/Message.php';
        $messageModel = new Message();

        // Verify message exists and user can delete it
        $message = $messageModel->findForUser($messageId, $userId);
        if (!$message) {
            Session::flash('error', Lang::get('message_not_found'));
            header('Location: ' . APP_URL . '/messages');
            exit;
        }

        // Delete the message
        $success = $messageModel->deleteForUser($messageId, $userId);
        
        if ($success) {
            Session::flash('success', Lang::get('message_deleted'));
        } else {
            Session::flash('error', Lang::get('message_delete_failed'));
        }

        header('Location: ' . APP_URL . '/messages');
        exit;
    }
}
