<?php
    // write the contents of user chat message to user_out.json

    $user = htmlentities(strip_tags($_POST['user']));
    $msg = htmlentities(strip_tags($_POST['msg']));
    $ip = htmlentities(strip_tags($_POST['ip']));
    $location = htmlentities(strip_tags($_POST['location']));
    $last_visited = htmlentities(strip_tags($_POST['last_visited']));
    $device = htmlentities(strip_tags($_POST['device']));
    $chat_status = htmlentities(strip_tags($_POST['chat_status']));
    $timestamp = htmlentities(strip_tags($_POST['timestamp']));

    if (($msg) != "\n") {
        $message = array("timestamp"=>$timestamp, "user"=>$user, "msg"=>$msg);
        $file = '../ChatRoom/userChats/'.$ip.'.json';
        // $writable = is_writable($file);
        $file_exists = file_exists($file);

        // get current contents of json file
        if ($file_exists) {
            $data = json_decode(file_get_contents($file), true);
            // make sure dictionary values aren't empty
            $data['ip'] = $data['ip'] == "" ? $ip : $data['ip'];
            $data['location'] = $data['location'] == "" ? $location : $data['location'];
            $data['last_visited'] = $data['last_visited'] == "" ? $last_visited : $data['last_visited'];
            $data['device'] = $data['device'] == "" ? $device : $data['device'];
            $data['user'] = $data['user'] == "" ? $user : $data['user'];
        } else {
            // if first message, set chat_started value from timestamp
            $data = array("chat_start_date"=>$timestamp, "ip"=>$ip, "user"=>$user, "location"=>$location, "last_visited"=>$last_visited, "device"=>$device, "last_updated"=>$timestamp);
            $data['messages'] = [];
        }
        // always update chat_status, last_updated, last_visited, device, user
        $data['chat_status'] = $chat_status;
        $data['last_updated'] = $timestamp;
        $data['user'] = $user;
        $data['last_visited'] = $last_visited;
        $data['device'] = $device;

        // push new message to message array
        array_push($data['messages'], $message);
        $json = json_encode($data, JSON_PRETTY_PRINT);
        
        // write data contents to json file
        file_put_contents($file, $json);
        // echo $json;
        echo json_encode($file_exists);
    }

?>