<?php
    // check the contents of user_out.json for new messages

    // TODO file url and ftp credentials will need to updated when moved to production site
    $host = "https://bodi4life.com";
    $ftp_user = "bodi4life";
    $ftp_password = "Alan'12an";

    // read user_out.json from bodi server
    $data = file_get_contents($host."/chat/user_out.json");
    if ($data === FALSE) {
        $msg_content = [];
    } else {
        $msg_content = json_decode($data, true);
    }
    
    // if user_out contains msg data, overwrite with empty file
    if (count($msg_content) > 0) {

        // clear file after read - upload an empty json file to replace existing file on server
        $file = '../ChatRoom/user_out.json';
        // create the file on the server if it doesn't exist
        if (!file_exists($file)) {
            file_put_contents($file, "[]");
        }

        $fp = fopen($file, 'r');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_USERPWD, $ftp_user.":".$ftp_password);
        curl_setopt($ch, CURLOPT_URL, 'ftp://162.213.248.101/public_html/chat/user_out.json');
        curl_setopt($ch, CURLOPT_UPLOAD, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 86400);
        curl_setopt($ch, CURLOPT_INFILE, $fp);
        curl_setopt($ch, CURLOPT_NOPROGRESS, false);
        curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);
        curl_setopt($ch, CURLOPT_INFILESIZE, filesize($file));
        curl_exec ($ch);
        curl_close ($ch);

    }
    
    // return message data
    echo json_encode($msg_content);

?>