 <?php
ini_set('display_errors', 1);
include(__DIR__ . '/../includes/functions.php');
global $db;
$jsonData = file_get_contents('php://input');
$data = json_decode($jsonData, true);

createtable();

if (isset($data['action']) && $data['action'] === "get-announcements") {
    global $db;
    $deviceid = $data['deviceid'];
	//$notes = $db->select('note', '*', '', '');
	$notes = $db->select('note', '*', '', 'createdate DESC');
	
	$jdata = [];
	
	foreach ($notes as $note) {
	    
	    $readStatus = $db->select('read', '*', 'devices_id = :deviceid AND announcement_id = :announcement_id', '', [
            ':deviceid' => $deviceid,
            ':announcement_id' => $note['id']
        ]);

        $seen = empty($readStatus) ? 0 : 1; 
        
		$jdata[] = [
		    'id' => $note['id'], 
		    'title' => $note['note_title'], 
		    'message' => $note['note_content'], 
		    'created_on' => $note['createdate'],
		    'seen' => $seen];
	}
	
	
	echo json_encode([
        "result" => "success",
        "sc" => $data['sc'],
        "message" => count($jdata) > 0 ? "Announcements retrieved successfully!" : "No Announcements Available",
        "totalrecords" => count($jdata),
        "data" => $jdata
    ]);
}


if (isset($data['action']) && $data['action'] === "read-announcement") {
    global $db;
    $deviceid = $data['deviceid'];
    $announcement_id = $data['announcement_id'];
    
    $readstatus = $db->select('read', '*', 'devices_id = :deviceid AND announcement_id = :announcement_id', '', [
        ':deviceid' => $deviceid,
        ':announcement_id' => $announcement_id
    ]);

    if (empty($readstatus)) {
        $report_seen = '{"result":"success","sc":"' . $data['sc'] . '","message":"Report send sucessfully!"}';
        $table_name = 'read';
        $data = ['devices_id' => $deviceid,'announcement_id' => $announcement_id,'status' => '1'];
        $db->insert($table_name, $data);
	    $db->close();
	    
    }else{
        $report_seen = '{"result":"success","sc":"' . $data['sc'] . '","message":"Report not send sucessfully!"}';
    }
    
    
    echo  $report_seen;

}

if (isset($data['action']) && $data['action'] === "add-device") {
    global $db;
    $report_seen = '{"result":"success","sc":"' . $data['sc'] . '","message":"Report not send sucessfully!"}';

    echo  $report_seen;

}

function createtable(){
    global $db;
    $table_name = 'read';
    $data = ['devices_id' => '0000','announcement_id' => '0000','status' => '0'];
    $db->insertIfEmpty($table_name, $data);
}