<?php
// Customer Messages Page
session_start();
require_once '../app/Core/init.php';

// Authentication check
if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_type']) || $_SESSION['user_type'] !== 'customer') {
    header('Location: ../index.php');
    exit();
}


// Page variables
$page_title = "Messages";
$active_menu = "messages";


$customer_id = $_SESSION['user_id'];
$message = new Message();
$customer = new Customer();

// Handle message sending
if ($_POST && isset($_POST['action']) && $_POST['action'] === 'send_message') {
    $recipient_type = $_POST['recipient_type'] ?? 'individual_vendor';
    $subject = $_POST['subject'] ?? '';
    $content = $_POST['content'] ?? '';
    $recipient_name = $_POST['recipient_name'] ?? '';
    
    if (!empty($content)) {
        $messageData = [
            'subject' => $subject ?: 'Customer Inquiry',
            'content' => $content,
            'recipient_type' => $recipient_type,
            'recipient_name' => $recipient_name,
            'sender_id' => $customer_id,
            'status' => 'sent'
        ];
        
        if ($message->create($messageData)) {
            $success_message = 'Message sent successfully!';
        } else {
            $error_message = 'Failed to send message. Please try again.';
        }
    }
}

// Get messages for the customer
$customer_messages = $message->getAll(50, 0, ['recipient_type' => 'individual_customer']);

// Get customer info
$customer_info = $customer->find($customer_id);

// Get unread message count
$unread_count = 0;
foreach ($customer_messages as $msg) {
    if ($msg['status'] === 'sent') {
        $unread_count++;
    }
}

// Get recent conversations (grouped by recipient/sender)
$conversations = [];
foreach ($customer_messages as $msg) {
    $key = $msg['sender_id'] == $customer_id ? 'outgoing_' . $msg['recipient_name'] : 'incoming_' . $msg['sender_id'];
    if (!isset($conversations[$key])) {
        $conversations[$key] = [
            'id' => $key,
            'name' => $msg['sender_id'] == $customer_id ? $msg['recipient_name'] : 'Support Agent',
            'last_message' => $msg['content'],
            'last_time' => $msg['sent_at'],
            'unread' => 0,
            'is_outgoing' => $msg['sender_id'] == $customer_id
        ];
    }
    if ($msg['sender_id'] != $customer_id && $msg['status'] === 'sent') {
        $conversations[$key]['unread']++;
    }
}

// Sort conversations by last message time
usort($conversations, function($a, $b) {
    return strtotime($b['last_time']) - strtotime($a['last_time']);
});

include('../templates/layouts/customer/head.php');
?>
    
</head>

<body class="fixed sidebar-mini">
    <div class="wrapper">
        <!-- Sidebar -->
        <nav class="sidebar">
            <div class="sidebar-header">
                <?php include '../templates/layouts/customer/navbar.php'; ?>
            </div>
        </nav>

        <!-- Page Content -->
        <div class="content-wrapper">
            <div class="main-content">
                <!-- Navbar -->
                <?php include '../templates/layouts/customer/header.php'; ?>

                <!-- Body Content -->
                <div class="body-content">
                    <div class="decoration blur-2"></div>
                    <div class="decoration blur-3"></div>
                    <div class="container-xxl">
                        <div class="row g-3">
                            <!-- Messages Interface -->
                            <div class="col-12">
                                <div class="card">
                                    <div class="card-header">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <h6 class="fs-17 fw-semi-bold my-1">Messages</h6>
                                            <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#composeModal">
                                                <i class="bi bi-plus-circle me-1"></i>New Message
                                            </button>
                                        </div>
                                    </div>
                                    <div class="card-body p-0">
                                        <div class="row g-0">
                                            <!-- Chat List Sidebar -->
                                            <div class="col-lg-4">
                                                <div class="chat-list__sidebar--left border-end">
                                                    <div class="chat-list__header">
                                                        <ul class="nav nav-tabs" id="sidebarTab" role="tablist">
                                                            <li class="nav-item">
                                                                <a class="nav-link active" id="chat-tab" data-bs-toggle="tab" href="#chat" role="tab" aria-controls="chat" aria-selected="true">
                                                                    <div class="position-relative">
                                                                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-chat-left-text" viewBox="0 0 16 16">
                                                                            <path d="M14 1a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H4.414A2 2 0 0 0 3 11.586l-2 2V2a1 1 0 0 1 1-1zM2 0a2 2 0 0 0-2 2v12.793a.5.5 0 0 0 .854.353l2.853-2.853A1 1 0 0 1 4.414 12H14a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2z" />
                                                                            <path d="M3 3.5a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5M3 6a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9A.5.5 0 0 1 3 6m0 2.5a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 0 1h-5a.5.5 0 0 1-.5-.5" />
                                                                        </svg>
                                                                        <div class="counts"><?php echo count($conversations); ?></div>
                                                                    </div><span class="d-block fs-11 fw-semibold text-truncate">Conversations</span>
                                                                </a>
                                                            </li>
                                                        </ul>
                                                    </div>
                                                    <div class="tab-content" id="sidebarTabContent">
                                                        <div class="tab-pane fade show active" id="chat" role="tabpanel" aria-labelledby="chat-tab">
                                                            <div class="chat-list__in position-relative">
                                                                <h2>Recent Conversations</h2>
                                                                <div class="nav chat-list" role="tablist">
                                                                    <?php if (!empty($conversations)): ?>
                                                                        <?php foreach ($conversations as $conv): ?>
                                                                            <a class="item-list item-list__chat d-flex align-items-start <?php echo $conv['unread'] > 0 ? 'unseen' : 'seen'; ?>" 
                                                                               href="#" onclick="openConversation('<?php echo $conv['id']; ?>', '<?php echo htmlspecialchars($conv['name']); ?>')">
                                                                                <div class="avatar">
                                                                                    <img src="assets/dist/img/avatar/01.jpg" alt="avatar">
                                                                                    <div class="status online"></div>
                                                                                    <?php if ($conv['unread'] > 0): ?>
                                                                                        <div class="new bg-success"><span><?php echo $conv['unread']; ?></span></div>
                                                                                    <?php endif; ?>
                                                                                </div>
                                                                                <div class="info-text">
                                                                                    <h5><?php echo htmlspecialchars($conv['name']); ?></h5>
                                                                                    <span><?php echo date('M j', strtotime($conv['last_time'])); ?></span>
                                                                                    <p><?php echo htmlspecialchars(substr($conv['last_message'], 0, 50)); ?><?php echo strlen($conv['last_message']) > 50 ? '...' : ''; ?></p>
                                                                                </div>
                                                                            </a>
                                                                        <?php endforeach; ?>
                                                                    <?php else: ?>
                                                                        <div class="text-center py-4 text-muted">
                                                                            <p>No conversations yet</p>
                                                                            <small>Start a new conversation to begin messaging</small>
                                                                        </div>
                                                                    <?php endif; ?>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- Chat Area -->
                                            <div class="col-lg-8">
                                                <div class="chatting_area">
                                                    <div class="chat-header d-flex align-items-center">
                                                        <button type="button" class="btn chat-sidebar-collapse d-block d-xl-none">
                                                            <svg xmlns="http://www.w3.org/2000/svg" width="21" height="21" fill="currentColor" class="bi bi-grid" viewBox="0 0 16 16">
                                                                <path d="M1 2.5A1.5 1.5 0 0 1 2.5 1h3A1.5 1.5 0 0 1 7 2.5v3A1.5 1.5 0 0 1 5.5 7h-3A1.5 1.5 0 0 1 1 5.5zM2.5 2a.5.5 0 0 0-.5.5v3a.5.5 0 0 0 .5.5h3a.5.5 0 0 0 .5-.5v-3a.5.5 0 0 0-.5-.5zm6.5.5A1.5 1.5 0 0 1 10.5 1h3A1.5 1.5 0 0 1 15 2.5v3A1.5 1.5 0 0 1 13.5 7h-3A1.5 1.5 0 0 1 9 5.5zm1.5-.5a.5.5 0 0 0-.5.5v3a.5.5 0 0 0 .5.5h3a.5.5 0 0 0 .5-.5v-3a.5.5 0 0 0-.5-.5zM1 10.5A1.5 1.5 0 0 1 2.5 9h3A1.5 1.5 0 0 1 7 10.5v3A1.5 1.5 0 0 1 5.5 15h-3A1.5 1.5 0 0 1 1 13.5zm1.5-.5a.5.5 0 0 0-.5.5v3a.5.5 0 0 0 .5.5h3a.5.5 0 0 0 .5-.5v-3a.5.5 0 0 0-.5-.5zm6.5.5A1.5 1.5 0 0 1 10.5 9h3a1.5 1.5 0 0 1 1.5 1.5v3a1.5 1.5 0 0 1-1.5 1.5h-3A1.5 1.5 0 0 1 9 13.5zm1.5-.5a.5.5 0 0 0-.5.5v3a.5.5 0 0 0 .5.5h3a.5.5 0 0 0 .5-.5v-3a.5.5 0 0 0-.5-.5z"></path>
                                                            </svg>
                                                        </button>
                                                        <div class="meta-info data">
                                                            <h5 id="chatTitle">Select a conversation</h5>
                                                            <span id="chatStatus">Choose a conversation to start messaging</span>
                                                        </div>
                                                    </div>
                                                    <div class="messenger-dialog row m-0">
                                                        <div class="messenger-dialog__area p-0">
                                                            <div class="message-content message-content-scroll" id="messageArea">
                                                                <div class="position-relative">
                                                                    <div class="text-center py-5 text-muted">
                                                                        <i class="bi bi-chat-dots fs-1 mb-3"></i>
                                                                        <h5>No conversation selected</h5>
                                                                        <p>Select a conversation from the left to start messaging</p>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <div class="chat-area-bottom border-top">
                                                                <div class="chat-input">
                                                                    <input type="text" class="form-control" id="messageInput" placeholder="Type a message..." disabled>
                                                                    <button class="btn btn-primary" type="button" id="sendButton" disabled>
                                                                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-send" viewBox="0 0 16 16">
                                                                            <path d="M15.854.146a.5.5 0 0 1 .11.54L13.026 15.466a.5.5 0 0 1-.796-.192L11.5 12.903A.5.5 0 0 1 12 12.5V12h-.5a.5.5 0 0 1-.5-.5V11a.5.5 0 0 1 .5-.5H12a.5.5 0 0 1 .5.5v.5l.096.006.707-.707a.5.5 0 0 1 .708-.708l-.5.5a.5.5 0 0 0 0 .708z"/>
                                                                            <path d="M2.978.842a2.28 2.28 0 0 1 4.104 0h-.002a2.28 2.28 0 0 1 4.104 0l-.706.707a2.28 2.28 0 0 1-1.586 1.207L8.5 3.207A2.5 2.5 0 0 1 9 5.5c0 .133-.011.265-.031.393L9 5.5c0-.133.011-.265.031-.393l.031.031a2.5 2.5 0 0 1 .5 1.207L9.5 7.293A2.28 2.28 0 0 1 8 7.5c.61 0 1.18-.235 1.605-.64l.707-.707a2.28 2.28 0 0 1 1.586-1.207l.5-.5a.5.5 0 0 0 0-.708L12.586 2.5A2.28 2.28 0 0 1 11 2.5c-.61 0-1.18.235-1.605.64L8.293 3.293a2.28 2.28 0 0 1-1.586 1.207l-.5.5a.5.5 0 0 0 0 .708z"/>
                                                                        </svg>
                                                                    </button>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Compose Message Modal -->
    <div class="modal fade" id="composeModal" tabindex="-1" aria-labelledby="composeModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="composeModalLabel">New Message</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST" action="">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="send_message">
                        <div class="mb-3">
                            <label for="recipientType" class="form-label">Send To</label>
                            <select class="form-select" id="recipientType" name="recipient_type" required>
                                <option value="individual_vendor">Individual Vendor</option>
                                <option value="individual_customer">Individual Customer</option>
                                <option value="all_vendors">All Vendors</option>
                                <option value="all_admins">Support Team</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="recipientName" class="form-label">Recipient Name (optional)</label>
                            <input type="text" class="form-control" id="recipientName" name="recipient_name" placeholder="Enter specific recipient name">
                        </div>
                        <div class="mb-3">
                            <label for="subject" class="form-label">Subject (optional)</label>
                            <input type="text" class="form-control" id="subject" name="subject" placeholder="Message subject">
                        </div>
                        <div class="mb-3">
                            <label for="content" class="form-label">Message</label>
                            <textarea class="form-control" id="content" name="content" rows="5" required placeholder="Type your message here..."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Send Message</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="assets/plugins/jQuery/jquery.min.js"></script>
    <script src="assets/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/plugins/metisMenu/metisMenu.min.js"></script>
    <script src="assets/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script>
    <script src="assets/dist/js/app.min.js"></script>
    <!-- Toastr JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>

    <script>
        $(document).ready(function() {
            // Toastr notifications
            <?php if (isset($success_message)): ?>
                toastr.success('<?php echo addslashes($success_message); ?>');
            <?php endif; ?>
            <?php if (isset($error_message)): ?>
                toastr.error('<?php echo addslashes($error_message); ?>');
            <?php endif; ?>

            // Conversation opening functionality
            window.openConversation = function(convId, convName) {
                $('#chatTitle').text(convName);
                $('#chatStatus').text('Online');
                $('#messageInput').prop('disabled', false);
                $('#sendButton').prop('disabled', false);
                
                // Simulate conversation loading
                const conversationData = {
                    '<?php echo implode("', '", array_column($conversations, 'id')); ?>': [
                        {
                            sender: '<?php echo htmlspecialchars($customer_info['first_name']); ?>',
                            time: '10:30 AM',
                            message: 'Hello! I have a question about your service.',
                            isMe: true
                        },
                        {
                            sender: convName,
                            time: '10:32 AM',
                            message: 'Hi there! I\'d be happy to help. What can I assist you with?',
                            isMe: false
                        },
                        {
                            sender: '<?php echo htmlspecialchars($customer_info['first_name']); ?>',
                            time: '10:35 AM',
                            message: 'I wanted to inquire about the availability of your services next weekend.',
                            isMe: true
                        }
                    ]
                };

                const messages = conversationData[convId] || [
                    {
                        sender: convName,
                        time: 'Just now',
                        message: 'Welcome! Start the conversation.',
                        isMe: false
                    }
                ];

                let messageHtml = '<div class="position-relative">';
                
                messages.forEach(msg => {
                    const messageClass = msg.isMe ? 'message me' : 'message';
                    const avatarHtml = msg.isMe ? '' : '<img class="avatar" src="assets/dist/img/avatar/01.jpg" alt="avatar">';
                    
                    messageHtml += `
                        <div class="${messageClass}">
                            ${avatarHtml}
                            <div class="text-main">
                                <span class="time-ago">${msg.time}</span>
                                <div class="text-group ${msg.isMe ? 'me' : ''}">
                                    <div class="text ${msg.isMe ? 'me' : ''}">
                                                                <p>${msg.message}</p>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                    `;
                });
                
                messageHtml += '</div>';
                $('#messageArea').html(messageHtml);
                
                // Scroll to bottom
                $('.message-content-scroll').scrollTop($('.message-content-scroll')[0].scrollHeight);
            };

            // Send message functionality
            $('#sendButton').click(function() {
                const message = $('#messageInput').val().trim();
                if (message) {
                    // Simulate sending message
                    const now = new Date();
                    const timeStr = now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
                    
                    const messageHtml = `
                        <div class="message me">
                            <div class="text-main">
                                <span class="time-ago">${timeStr}</span>
                                <div class="text-group me">
                                    <div class="text me">
                                        <p>${message}</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;
                    
                    $('#messageArea').append(messageHtml);
                    $('#messageInput').val('');
                    
                    // Scroll to bottom
                    $('.message-content-scroll').scrollTop($('.message-content-scroll')[0].scrollHeight);
                    
                    // Simulate typing indicator and response
                    setTimeout(() => {
                        $('#chatStatus').text('Typing...');
                        setTimeout(() => {
                            $('#chatStatus').text('Online');
                        }, 2000);
                    }, 500);
                }
            });

            // Enter key to send message
            $('#messageInput').keypress(function(e) {
                if (e.which === 13) {
                    $('#sendButton').click();
                }
            });

            // Sidebar toggle
            $('#sidebarCollapse').on('click', function() {
                $('.wrapper').toggleClass('sidebar-collapsed');
            });
        });
    </script>
</body>
</html>