<?php
// Constant Definition
$TEAM_COLOR = '#7c3aed';
$CLIENT_COLOR = '#0277bd';
$BROKER_COLOR = '#3b82f6';
$ADMIN_COLOR = '#f59e0b';

$CURRENT_USER_ID = get_staff_user_id();
$CURRENT_USER_ROLE = get_staff_role($this, get_current_staff_role($this, get_staff_user_id()));
$CURRENT_USER_NAME = get_staff_full_name();
$CURRENT_USER_PROFILE_PATH = staff_profile_image_url($CURRENT_USER_ID);

?>

<div class="comment-section">
    <!-- Header -->
    <div class="header">
        <div class="header-title">
            <svg class="header-icon" viewBox="0 0 24 24">
                <path d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
            </svg>
            Comments
        </div>
    </div>

    <!-- Comment Input -->
    <div class="comment-input-container">

        <div class="sender-selection">
            <label class="sender-label">Send to:</label>
            <div class="sender-options">

                <?php if ($CURRENT_USER_ROLE === 'LD-Team' || $CURRENT_USER_ROLE === 'Broker') { ?>
                    <label class="radio-option">
                        <input type="checkbox" name="recipient_role[]" value="admin">
                        <span class="radio-custom"></span>
                        <span class="role-badge admin">
                            <svg class="role-icon" viewBox="0 0 24 24">
                                <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
                            </svg>
                            Admin
                        </span>
                    </label>
                <?php }; ?>

                <?php if ($CURRENT_USER_ROLE === 'LD-Team' || $CURRENT_USER_ROLE === 'Admin') { ?>
                    <label class="radio-option">
                        <input type="checkbox" name="recipient_role[]" value="broker">
                        <span class="radio-custom"></span>
                        <span class="role-badge broker">
                            <svg class="role-icon" viewBox="0 0 24 24">
                                <path d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                            </svg>
                            Broker
                        </span>
                    </label>
                <?php }; ?>

                <?php if ($CURRENT_USER_ROLE === 'Broker' || $CURRENT_USER_ROLE === 'Admin') { ?>
                    <label class="radio-option">
                        <input type="checkbox" name="recipient_role[]" value="ld-team">
                        <span class="radio-custom"></span>
                        <span class="role-badge team">
                            <svg class="role-icon" viewBox="0 0 24 24">
                                <path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
                            </svg>
                            Team
                        </span>
                    </label>
                <?php }; ?>

                <?php if ($CURRENT_USER_ROLE === 'LD-Team' || $CURRENT_USER_ROLE === 'Admin') { ?>
                    <label class="radio-option">
                        <input type="checkbox" name="recipient_role[]" value="client">
                        <span class="radio-custom"></span>
                        <span class="role-badge client">
                            <svg class="role-icon" viewBox="0 0 24 24">
                                <path d="M5.121 17.804A13.937 13.937 0 0112 16c2.5 0 4.847.655 6.879 1.804M15 10a3 3 0 11-6 0 3 3 0 016 0zm6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                            Client
                        </span>
                    </label>
                <?php }; ?>

            </div>
        </div>

        <div class="comment-input-wrapper">
            <textarea name="comment" class="comment-input" placeholder="Write a comment..."></textarea>
            <button class="send-button" title="Send message">
                <svg class="send-icon" viewBox="0 0 24 24">
                    <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z" />
                </svg>
            </button>
        </div>

    </div>
    <!-- Comments List -->
    <div class="comments-list">
        <!-- Comment Item -->
    </div>
</div>


<script>
    // Constant definiation Admin, Broker
    var current_role = <?= json_encode($CURRENT_USER_ROLE) ?>;

    // Helper function
    function capitalize(str) {
        return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
    }

    function setActiveRoleCheckbox(current_active_role) {
        const roleMap = {
            'Admin': 'broker',
            'Broker': 'admin',
            'LD-Team': 'admin'
        };

        const valueToCheck = roleMap[current_active_role] || 'client';

        $(`input[name='recipient_role[]'][value='${valueToCheck}']`).prop("checked", true);
    }

    setActiveRoleCheckbox(current_role);



    $(document).ready(function() {

        // Handle send button click
        $('.send-button').on('click', function(e) {
            e.preventDefault();
            sendComment();
        });

        // Ajax for sending comment
        function sendComment() {
            // Get form data
            var comment_content = $('.comment-input').val().trim();
            var recipient_role = $('input[name="recipient_role[]"]:checked').map(function() {
                return this.value;
            }).get(); // return an array

            // Basic validation
            if (comment_content === '') {
                alert('Please enter a comment', 'error');
                $('.comment-input').focus();
                return;
            }

            // Disable send button to prevent double submission
            var $send_button = $('.send-button');
            var $text_area = $('.comment-input');

            $send_button.prop('disabled', true).addClass('loading');
            $text_area.prop('disabled', true);

            // Prepare AJAX data
            var ajaxData = {
                comments: comment_content,
                recipient_selected_role: recipient_role,
            };

            // Make AJAX request
            $.ajax({
                url: "<?php echo admin_url('Comment/add_comment/' . $lead->id); ?>",
                type: 'POST',
                data: ajaxData,
                dataType: 'json',
                beforeSend: function() {
                    $('.full-page-loader').show();
                },
                success: function(response) {
                    console.log(response.success);
                    if (response.success) {
                        showComments();
                        // Success - clear the textarea and show success message
                        $text_area.val('');
                        console.log("Comment added successfully.");

                    } else {
                        console.log(response.errors);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX Error:', error);
                },
                complete: function() {
                    // Re-enable controls
                    $send_button.prop('disabled', false).removeClass('loading');
                    $text_area.prop('disabled', false);
                    $('.full-page-loader').hide();
                }
            });
        }

        // Ajax for fetching from DB
        function showComments() {
            $.ajax({
                url: "<?php echo admin_url('Comment/get_comments/' . $lead->id); ?>",
                type: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        var container = $('.comments-list');
                        container.empty();
                        response.comments.forEach(function(c) {

                            // Build full name
                            var fullname = "<?php echo $CURRENT_USER_NAME ?>".split(" ");
                            var firstname = fullname[0];
                            var lastname = fullname[1];
                            var name = firstname + ' ' + lastname;

                            // Map role to readable label & color
                            var currentRole = c.sender_role;
                            var color = '';

                            if (currentRole === 'Broker') {
                                displayRole = 'Broker';
                                color = '<?php echo $BROKER_COLOR; ?>';
                            } else if (currentRole === 'LD-Team') {
                                displayRole = 'Team';
                                color = '<?php echo $TEAM_COLOR; ?>';
                            } else {
                                displayRole = 'Admin';
                                color = '<?php echo $ADMIN_COLOR; ?>';
                            }

                            // Get initials for avatar
                            var initials = name.charAt(0) + name.split(' ').pop().charAt(0);

                            // Created time
                            var created_at = c.created_at;

                            // Profile Path
                            var current_user_profile_path = c.sender_profile_path ?? ' ';

                            // Recipients Roles
                            var recipients_role = c.send_to;
                            // Check if recipients_role is null before splitting
                            if (recipients_role === null) {
                                recipients_role = ''; // Assign an empty string or handle as needed
                            }
                            recipients_role = recipients_role.split(",");

                            // Comment HTML
                            var html = `
                        <div class="comment-item">
                            <div class="comment-header">
                                <div class="avatar" style="background-color:${current_user_profile_path ? `white` : color };">
                                    ${current_user_profile_path ? `<img src="${current_user_profile_path}" alt="Profile Image" width="40px" height="40px" class="avatar">` : initials }
                                </div>
                                <div class="comment-content">
                                    <div class="comment-meta">
                                        <span class="username">${c.sender_name}</span>
                                        <span class="user-role ${displayRole.toLowerCase()}">${displayRole}</span>
                                        <a href="#" class="timestamp">
                                            ${created_at}
                                        </a>
                                    </div>
                                    <div class="comment-text">
                                        ${Array.isArray(recipients_role) && recipients_role.filter(role => role.trim() !== "").length > 0 ? recipients_role.map(role => `<span class="mention recipient">@${role}</span>`).join(' ')  : ' ' }
                                        ${c.comment_text}
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;

                            container.append(html);
                        });
                    } else {
                        console.error('Error fetching comments:', response.message);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX Error:', error);
                },
                complete: function() {
                    $('.full-page-loader').hide();
                }
            });
        }

        showComments();


    });
</script>