<?php
    error_reporting(E_ALL & ~E_NOTICE);
    date_default_timezone_set("Europe/Oslo");

    function IsJsonString($string) {
        if(substr($string,0,1)=="{" || substr($string,0,1)=="[") {
            return true;
        } else {
            return false;
        }
    }

    $_POST = json_decode(file_get_contents('php://input'), true);

    if(isset($_POST['setting'])) {
        $setting=stripslashes(htmlspecialchars($_POST['setting']));
        $value=base64_decode(stripslashes(htmlspecialchars($_POST['value'])));
        $key=base64_decode(stripslashes(htmlspecialchars($_POST['key'])),true);

        $output="";
        $tnow=time();

        switch($setting) {
            case "update": //
                $newObj=array(
                    "author" => "twily.info",
                    "time" => $tnow,
                    "date" => date("Y M jS D h:i:s A"),
                    "data" => array(
                        "value" => $value,
                        "key" => $key,
                    ),
                );
                $output=json_encode($newObj,JSON_FORCE_OBJECT);
                break;
            case "getchats":
                $f1="./chats.json";
                if (!file_exists($f1)) return;

                $chats = json_decode(file_get_contents($f1), true) ?: [];
				
				usort($chats, function($a, $b) { return $b['time'] - $a['time']; });
				
				$output = json_encode($chats);
                break;
				
			case "getchat":
				$id=$value;
				$f2="./chats/".$id.".log";
				if (!file_exists($f2)) return;

				$data = file_get_contents($f2);
				
				$lines=explode("\n",$data);
				
				$chat = array();
				for($i=0;$i<count($lines);$i++) {
					if(IsJsonString($lines[$i])) {
						$obj = json_decode($lines[$i], true);
						if(strlen($obj['content'])>50) $obj['content']=substr($obj['content'],0,50);
						
						array_push($chat, $obj);
					}
				}
				
				//usort($chats, function($a, $b) { return $b['time'] - $a['time']; });
				
				$output = json_encode($chat);
				break;
				
            default:
        }

        echo $output;
        exit;
    }
?>
<!DOCTYPE html>
<!--

    Author:        Twily  2015 - 2021
    Website:       http://twily.info/

-->
<html>
<head>
<title>&gt;_</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />

<!--<link id="favicon" rel="shortcut icon" href="http://twily.info/favicon.ico" />-->
<!--<link rel="stylesheet" type="text/css" href="./css/style.css?v=1" />-->
<style type="text/css">
html,body {
    width: 100%; height: 100%; margin: 0; padding: 0; overflow: auto;
    font-family: "Droid Sans", "Liberation Sans", "DejaVu Sans", "Segoe UI", Sans;
    font-size: 12pt; font-weight: bold;
    background: #17181A; color: #AAABAD;
}
* { box-sizing: border-box; }
*:focus { outline: none !important; }

a:link, a:visited { color: #606163; text-decoration: none; }
a:hover, a:active { color: #EA75BC; }

.tbl { display: table; width: 100%; height: 100%; }
.tr { display: table-row; }
.td { display: table-cell; vertical-align: top; border: 1px solid #606163; box-shadow: inset 0 0 2px 2px #000; }

.sides { width: 200px; min-width: 200px; vertical-align: middle; }

.green { color: #080; }
.red { color: #800; }

textarea, input[type="text"] {
    background: #000; color: #fff;
    border: 1px solid #666;
    width: 100%;
}

/*
#wrap { width: 100%; height: 100%; display: flex; position: absolute; z-index: 9; }
#wrap #box { padding: 128px; background: #111113; margin: auto; display: inline-block; position: relative; }*/

.user { background: #351c21; }
.assistant { background: #22224f;}
</style>

<!--<script type="text/javascript" src="./js/main.js?v=1"></script>-->
<script type="text/javascript">
var $=function(id) { return document.getElementById(id); };
var enableLS=(typeof(Storage)!=="undefined")?true:false;
var rndMinMax=function(min,max) { return Math.floor(Math.random()*(max-min+1)+min); }
var IsJsonString=function(str) { try { JSON.parse(str); } catch(e) { return false; } return true; }

function b64Enc(str) {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,function(match,p1) {
        return String.fromCharCode(parseInt(p1,16));
    }));
}
function b64Dec(str) {
    try {
        return decodeURIComponent(Array.prototype.map.call(atob(str),function(c) {
            return '%'+('00'+c.charCodeAt(0).toString(16)).slice(-2);
        }).join(''));
    } catch(e) {
        return str;
    }
}

var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var days=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
function getLocalTime(t=0) {
    if(t>0) {
        var d=new Date(t*1000);
    } else {
        var d=new Date();
    }
    var year=d.getFullYear();
    var month=months[d.getMonth()]; //Jan-Dec
    var day=days[d.getDay()];//Mon-Sun
    var dd=d.getDate(); //1-31
    var hh=d.getHours(); //0-23
    var mm=d.getMinutes(); //0-59
    var ss=d.getSeconds(); //0-59
    var ampm=(hh>=12)?"PM":"AM";
    hh=hh%12||12;
    hh=hh<10?"0"+hh:hh;
    mm=mm<10?"0"+mm:mm;
    ss=ss<10?"0"+ss:ss;
    var dth=dd.toString();
    dth=(((dth==1)?"st":dth==2)?"nd":dth==3)?"rd":"th";

    return year+" "+month+" "+dd+dth+" "+day+" "+hh+":"+mm+":"+ss+" "+ampm;
}

function ajaxThis(x,y,z,cb) {
    var xhr;
    if(window.XMLHttpRequest) xhr=new XMLHttpRequest();
    else                      xhr=new ActiveXObject("Microsoft.XMLHTTP");

    var data;
    xhr.onreadystatechange=function() {
        if(xhr.readyState==4 && xhr.status==200) {

            if(typeof cb==='function') {
                cb(xhr.responseText);
            }
        }
    }

    xhr.open("POST","./db-browser.php",true);
    //xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    //xhr.send("setting="+x+"&value="+b64Enc(y)+"&key="+b64Enc(z));

    // or with json to prevent issues with special chars and url encoding~

    xhr.setRequestHeader("Content-Type","application/json");
    xhr.send(JSON.stringify({setting: x, value: b64Enc(y), key: b64Enc(z)}));
}

function updateHeaderCustomCss(marker,css,add=false) {
	const head = document.head;

	// 1. Lookup and remove any existing <style> tag containing the pattern
	const existingStyles = head.querySelectorAll("style");
	existingStyles.forEach((styleTag) => {
		if (styleTag.textContent.includes(marker)) {
			styleTag.remove();
		}
	});

	if(add) {
		// 2. Create and add the new <style> tag to the header
		if (css && css.trim() !== "") {
			const newStyleTag = document.createElement("style");
			// Ensure the marker is included so future lookups can find it
			newStyleTag.textContent = css.includes(marker) 
			  ? css 
			  : `${marker}\n${css}`;
			  
			head.appendChild(newStyleTag);
		}
	}
}

var chatopen="";
function getchats() {
    ajaxThis('getchats','','',function(data) {
        $('div').innerHTML=data;
		if(IsJsonString(data)) {
			var obj=JSON.parse(data);
			var html="";
			for(let i=0;i<obj.length;i++) {
				if(!obj[i].hasOwnProperty('stats')) {
					html+="<a href=\"javascript:getchat('"+obj[i]['id']+"');\" target=\"_self\">";
					html+="chat entry missing stats -- (run recalculate-chat-count to fix) fallback:<br>";
					html+=obj[i]['time']+" | "+obj[i]['id']+" | "+obj[i]['title']+"";
					html+="</a><br>";
				} else {
					html+="<a href=\"javascript:getchat('"+obj[i]['id']+"');\" target=\"_self\">";
					html+=obj[i]['time']+" | "+obj[i]['id']+" | "+obj[i]['stats']['chats']+" chats + "+obj[i]['stats']['media']+" media | "+obj[i]['title']+"";
					html+="</a><br>";
				}
			}
			$("div").innerHTML=html;
		}
    });
	
		
	var custom_marker="/* custom sides css */";
	updateHeaderCustomCss(custom_marker, '', false);
}

function getchat(id) {
    ajaxThis('getchat',id,'',function(data) {
        //$('div').innerHTML=data;
		if(IsJsonString(data)) {
			var obj=JSON.parse(data);
			var html="";
			
			html+="<a href=\"javascript:getchats();\" target=\"_self\">";
			html+="--Back";
			html+="</a><br>";
			
			html+="<div class=\"tbl\">";
			
			html+="<div class=\"tr\">";
			html+="<div class=\"td\">time</div>";
			html+="<div class=\"td\">role</div>";
			html+="<div class=\"td\">content</div>";
			html+="<div class=\"td\">is_image</div>";
			html+="<div class=\"td\">attachment</div>";
			html+="<div class=\"td\">is_upload</div>";
			html+="<div class=\"td\">model</div>";
			html+="</div>";
			
			for(let i=0;i<obj.length;i++) {
				html+="<div class=\"tr "+obj[i]['role']+"\">";
				html+="<div class=\"td\">"+(obj[i]['time']?obj[i]['time']:'')+"</div>";
				html+="<div class=\"td\">"+(obj[i]['role']?obj[i]['role']:'')+"</div>";
				html+="<div class=\"td\">"+(obj[i]['content']?obj[i]['content']:'')+"</div>";
				html+="<div class=\"td\">"+(obj[i]['is_image']?obj[i]['is_image']:'')+"</div>";
				html+="<div class=\"td\">"+(obj[i]['attachment']?obj[i]['attachment']:'')+"</div>";
				html+="<div class=\"td\">"+(obj[i]['is_upload']?obj[i]['is_upload']:'')+"</div>";
				html+="<div class=\"td\">"+(obj[i]['model']?obj[i]['model']:'')+"</div>";
				html+="</div>";
			}
			
			html+="</div>";
			
			$("div").innerHTML=html;
			
			var custom_marker="/* custom sides css */";
			var custom_css=".sides { width: 0px; min-width: 0px };";
			
			updateHeaderCustomCss(custom_marker, custom_css, true);
		}
    });
}


function init() {
    getchats();
}
</script>
</head>
<body onload="init();">


<div class="tbl">
    <div class="tr" style="height: 50px;">
        <div class="td" style="text-align: center; vertical-align: middle;">
            db-browser
        </div>
    </div>
    <div class="tr">
        <div class="td">

        <div class="tbl">
            <div class="tr">
                <div class="td sides">

                &nbsp;

                </div>
                <div class="td" style="word-break: break-word;">

<div id="div"></div>

                </div>
                <div class="td sides">

                &nbsp;

                </div>
            </div>
        </div>

        </div>
    </div>
    <div class="tr" style="height: 50px;">
        <div class="td" style="text-align: center; vertical-align: middle;">
            
        </div>
    </div>
</div>


</body>
</html>

