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

    // useful to rebuild a lost chats log file in case of ie drive full situation
    // chat log files are not affected by full drive as is line breaked append based
    // chats and queue are full array encoded read all/write all
    // (recommend some manual backup keeping still but images can still be programatically rebound if lost as well x))
    //
    // this will rebuild chats.json with original titles based on existing chat logs: (write is enabled, just open the file url in browser. if existing chats.json will be moved to chats.json_copyN)

    $files=ListFilesInFolder("./chats");
    $arr=[];
    for($i=0;$i<count($files);$i++) {
        $ext=substr($files[$i],strrpos($files[$i],".")+1);
        if(strtolower($ext)=="log") {
            $arr[]=$files[$i];
        }
    }

    $chats=[];
    for($i=0;$i<count($arr);$i++) {
        $chatId=substr($arr[$i],0,strrpos($arr[$i],".")); // id

        $chatfile="./chats/".$arr[$i];
        $lastmtime=filemtime($chatfile); // time

        $fdata=file_get_contents($chatfile);
        $flist=explode("\n",$fdata);
        $title="New Chat"; // title
        for($j=0;$j<count($flist);$j++) {
            if(IsJsonString($flist[$j])) {
                $msg=json_decode($flist[$j],true);
                if($msg['role']=="user") {
                    $userText=$msg['content'];
                    $title=strlen($userText) > 25 ? substr($userText, 0, 25) . '...' : $userText;
                    break;
                }
            }
        }

        $obj=[
            "id" => $chatId,
            "title" => $title,
            "time" => $lastmtime
            //"status" => "idle"
        ];

        $chats[]=$obj;
    } 

    // preview
    //echo json_encode($arr);
    echo '<pre>'.json_encode($chats, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)."</pre>";

    // write with backup
    $write=true;
    if($write) { 
        if(file_exists("./chats.json")) {
            $num=1;
            while(file_exists("./chats.json_copy".$num)) {
                $num++;
            }
            rename("./chats.json","./chats.json_copy".$num);
        }
        file_put_contents("./chats.json",json_encode($chats, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), LOCK_EX);
    }

    exit;

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

    function ListFoldersInFolder($dir="./chats") {
        $filesAndFolders = scandir($dir);
        $folders = [];

        foreach ($filesAndFolders as $item) {
            // Exclude relative pointers and check if it's a directory
            if ($item !== '.' && $item !== '..' && is_dir($dir . '/' . $item)) {
                $folders[] = $item;
            }
        }

        return $folders;
    }

    function ListFilesInFolder($dir="./chats") {
        $filesAndFolders = scandir($dir);
        $files = [];

        foreach ($filesAndFolders as $item) {
            // Exclude relative pointers and check if it's a directory
            if ($item !== '.' && $item !== '..' && is_file($dir . '/' . $item)) {
                $files[] = $item;
            }
        }

        return $files;
    }
?>
