<?php

declare(strict_types=1);

namespace Admin\Controllers;

use App\Core\Controller;

/**
 * AdminChatController — Admin Chat Management
 *
 * Allows admins to view, reply to, and manage live chat conversations.
 */
class AdminChatController extends AdminController
{
    /**
     * List all chat conversations.
     */
    public function index(): never
    {
        $convModel = $this->model('ChatConversation');

        $conversations = $convModel->getAllWithLastMessage();
        $activeCount   = $convModel->getActiveCount();
        $totalUnread   = $convModel->getTotalAdminUnread();

        $this->adminView('chat', [
            'title'        => 'Live Chat',
            'currentPage'  => 'chat',
            'conversations' => $conversations,
            'activeCount'  => $activeCount,
            'totalUnread'  => $totalUnread,
        ]);
    }

    /**
     * View a specific conversation with messages.
     */
    public function show(int $id): never
    {
        $convModel = $this->model('ChatConversation');
        $msgModel  = $this->model('ChatMessage');

        $conversation = $convModel->find($id);

        if (!$conversation) {
            flash('error', 'Conversation not found.');
            redirect(BASE_PATH . '/admin/chat');
        }

        // Mark visitor messages as read by admin
        $msgModel->markVisitorMessagesRead($id);
        $convModel->resetAdminUnread($id);

        $messages = $msgModel->getByConversation($id);

        $this->adminView('chat_conversation', [
            'title'        => 'Chat — ' . ($conversation['visitor_name'] ?? 'Visitor'),
            'currentPage'  => 'chat',
            'conversation' => $conversation,
            'messages'     => $messages,
            'lastId'       => $msgModel->getLastId($id),
        ]);
    }

    /**
     * Send a reply from admin.
     */
    public function reply(int $id): never
    {
        $this->validateCsrf();

        $message = trim($_POST['message'] ?? '');

        if (empty($message)) {
            flash('error', 'Message cannot be empty.');
            redirect(BASE_PATH . '/admin/chat/' . $id);
        }

        $convModel = $this->model('ChatConversation');
        $msgModel  = $this->model('ChatMessage');

        $conversation = $convModel->find($id);
        if (!$conversation) {
            flash('error', 'Conversation not found.');
            redirect(BASE_PATH . '/admin/chat');
        }

        // Get current admin user
        $currentUser = getCurrentUser();
        $adminId = $currentUser['id'] ?? null;

        // Add admin message
        $msgModel->addMessage($id, 'admin', $message, $adminId);

        // Increment visitor unread count
        $convModel->incrementVisitorUnread($id);

        // Ensure conversation is active
        if ($conversation['status'] === 'pending') {
            $convModel->markActive($id);
        }

        flash('success', 'Reply sent successfully.');
        redirect(BASE_PATH . '/admin/chat/' . $id);
    }

    /**
     * Close a conversation.
     */
    public function close(int $id): never
    {
        $this->validateCsrf();

        $convModel = $this->model('ChatConversation');
        $convModel->closeConversation($id);

        flash('success', 'Conversation closed.');
        redirect(BASE_PATH . '/admin/chat');
    }

    /**
     * Delete a conversation.
     */
    public function delete(int $id): never
    {
        $this->validateCsrf();

        $convModel = $this->model('ChatConversation');
        $convModel->delete($id);

        flash('success', 'Conversation deleted.');
        redirect(BASE_PATH . '/admin/chat');
    }

    /**
     * Poll for new messages in a conversation (AJAX endpoint for admin).
     * GET /admin/chat/{id}/poll?after_id=Y
     */
    public function poll(int $id): never
    {
        $afterId = (int) ($_GET['after_id'] ?? 0);

        $convModel = $this->model('ChatConversation');
        $msgModel  = $this->model('ChatMessage');

        $conversation = $convModel->find($id);
        if (!$conversation) {
            $this->json(['success' => false, 'error' => 'Not found'], 404);
        }

        // Mark visitor messages as read
        $msgModel->markVisitorMessagesRead($id);
        $convModel->resetAdminUnread($id);

        $messages = $msgModel->getNewerThan($id, $afterId);

        $this->json([
            'success'  => true,
            'messages' => $messages,
            'last_id'  => $msgModel->getLastId($id),
        ]);
    }

    /**
     * Get unread count for admin notification badge (AJAX).
     * GET /admin/chat/unread-count
     */
    public function unreadCount(): never
    {
        $convModel = $this->model('ChatConversation');
        $count = $convModel->getTotalAdminUnread();

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