<?php

    // read file contents of '../userChats'
    $path = '../ChatRoom/userChats';
    $files = array_diff(scandir($path), array('.', '..'));
    $messages = [];
    foreach($files as $file) {
        $data = json_decode(file_get_contents($path.'/'.$file), true);
        // if (isset($data['ip']) && $data['ip'] != '') {
            $data['filename'] = $file;
            // make sure all keys are set for array sorting
            $data['chat_status'] = isset($data['chat_status']) ? $data['chat_status'] : '';
            $data['user'] = isset($data['user']) ? $data['user'] : '';
            $data['customer_id'] = isset($data['customer_id']) ? $data['customer_id'] : '';
            $data['last_visited'] = isset($data['last_visited']) ? $data['last_visited'] : '';
            $data['device'] = isset($data['device']) ? $data['device'] : '';
            $data['chat_start_date'] = isset($data['chat_start_date']) ? $data['chat_start_date'] : date("Y-m-d h:i:s A", time());
            $data['ip'] = isset($data['ip']) ? $data['ip'] : $file;
            $data['location'] = isset($data['location']) ? $data['location'] : '';
            $data['messages'] = isset($data['messages']) ? $data['messages'] : [];
            $data['last_updated'] = isset($data['last_updated']) ? $data['last_updated'] : date("Y-m-d h:i:s A", time());
            array_push($messages, $data);
        // }
    }
    // sort chats by last_updated
    $sort_col = array_column($messages, 'last_updated');
    array_multisort($sort_col, SORT_DESC, $messages);

?>

<div id="ChatRoom">

    <link rel="stylesheet" href="/ChatRoom/chat.css" type="text/css">
    <div class="contain">

        <div class="content" id="chat_rows">
            <div id="top_row"></div>
            <!-- on row click, show chat log, add class 'selected-chat' -->
            <?php
                foreach($messages as $message) {
                    if ( (isset($message['customer_id']) && $message['customer_id'] != '') || 
                        (isset($message['ip']) && $message['ip'] != '') ) {
                        $row_id = isset($message['customer_id']) && $message['customer_id'] != '' ? $message['customer_id'] :
                        $message['ip'];
                        $dateFromDatabase = strtotime($message['last_updated']);
                        $TimeToDelete = strtotime("-48 hours");

                        // add class based on chat content and status
                        if (count($message['messages']) > 0) {
                            // customer sent messages - indicate if they are in-chat/browsing or off site
                            $div_class = $message['chat_status'] == "in_chat" || $message['chat_status'] == "browsing" ? "in-chat" : "left-chat";
                        } else if ($dateFromDatabase >= $TimeToDelete) {
                            // customer did not send messages - indicate if they are browsing or off site
                            $div_class = $message['chat_status'] == "browsing" ? "browsing-chat" : "";
                        }

                        if (count($message['messages']) > 0 || $dateFromDatabase >= $TimeToDelete) {
                            // truncate last_visited value to just the last part of the url
                            $parts = explode("/", $message['last_visited']);
                            $last_visited_text = $parts[count($parts)-2];
                            echo '<div class="chat-row-outer">
                            <div class="chat-row '.$div_class.'" id="row_'.$row_id.'" customer_id="'.$row_id.'">
                            <p class="user" id="row_'.$row_id.'_user">'.($message['user'] == "" ? $row_id : $message['user'] ).'</p>
                            <p class="location" id="row_'.$row_id.'_location">'.($message['location'] != '' ? $message['location'] : '').'</p>
                            <p class="device" id="row_'.$row_id.'_device">'.$message['device'].'</p>
                            <p class="last-visited"><a id="row_'.$row_id.'_last_visited" href="https://www.bodi4life.com/'.$message['last_visited'].'" target="_blank">'.$last_visited_text.'</a></p>
                            </div>
                            <button id="'.$row_id.'" class="delete-chat" type="button">X</button>
                            </div>';
                        } else {
                            echo '<span class="dummy-row" id="'.$row_id.'"></span>';
                        }
                    }
                }
            ?>
        </div>
            <div id="customer_locations"></div>

        <div class="chat-box">

            <p id="current_time" hidden></p>
            <input type="hidden" id="chat_id">
            <div class="chat-box-body">
                <div class="chat-box-overlay">

                </div>
                <div class="chat-logs">
                    <div class="chat-input">
                    </div>
                </div>
            </div>
            <form>
                <div>
                    <input type="text" id="chat-input"  placeholder="Type a message..." disabled />
                    <button type="submit" class="chat-submit" id="chat-submit">
                        Send
                    </button>
                </div>
            </form>

        </div>

    </div>
</div>

<script src="/ChatRoom/chat.js?v=<?php echo time();?>"></script>
<script>

    var messageLogs = <?php echo json_encode($messages); ?>;
    console.log(messageLogs);

</script>