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

    $msg = htmlentities(strip_tags($_POST['msg']));
    $ip = htmlentities(strip_tags($_POST['ip']));

    $timestamp = date("Y-m-d h:i:s A", time());
    $message = array("timestamp"=>$timestamp, "user"=>"Alan", "msg"=>$msg = str_replace("\n", " ", $msg), "recipient"=>$ip);

    if (($msg) != "\n") {
        $file = '../ChatRoom/manager_out.json';
        // $writable = is_writable($file);
        $file_exists = file_exists($file);

        // get current contents of manager output json file
        if ($file_exists) {
            $msg_content = json_decode(file_get_contents($file), true);
        } else {
            $msg_content = [];
        }
        array_push($msg_content, $message);
        
        // write new message to manager_out.json file
        $json = json_encode($msg_content, JSON_PRETTY_PRINT);
        file_put_contents($file, $json);

        // update contents of customer chat log
        $file = '../ChatRoom/userChats/'.str_replace('_', '.', $ip).'.json';
        // file should always exist - created by post_message.php - on data received from customer
        if (file_exists($file)) {
            $data = json_decode(file_get_contents($file), true);
            // update last_updated
            $data['last_updated'] = $timestamp;
            // add manager message to chat file
            array_push($data['messages'], $message);
            $json = json_encode($data, JSON_PRETTY_PRINT);
            file_put_contents($file, $json);
        }

        echo $json;
    }

?>