<?php
// public_html/datapesan/api_chat.php
header('Content-Type: application/json');
$folder = "./"; // Folder penyimpanan

$action = $_GET['action'] ?? $_POST['action'] ?? '';
$uid = $_GET['uid'] ?? $_POST['uid'] ?? '';

if ($action == 'send') {
    $pesan = $_POST['pesan'];
    $pengirim = $_POST['pengirim']; // 'user' atau 'admin'
    $nama = $_POST['nama'] ?? 'User';
    $file = $folder . "chat_" . $uid . ".json";
    
    $data = [];
    if (file_exists($file)) {
        $data = json_content_decode(file_get_contents($file));
    }
    
    $data[] = [
        "id" => uniqid(),
        "sender" => $pengirim,
        "name" => $nama,
        "text" => $pesan,
        "time" => date("H:i")
    ];
    
    file_put_contents($file, json_encode($data));
    echo json_encode(["status" => "success"]);
} 

elseif ($action == 'get_messages' && $uid) {
    $file = $folder . "chat_" . $uid . ".json";
    if (file_exists($file)) {
        echo file_get_contents($file);
    } else {
        echo json_encode([]);
    }
}

elseif ($action == 'get_users') {
    $files = glob($folder . "chat_*.json");
    $users = [];
    foreach ($files as $f) {
        $id = str_replace(["chat_", ".json", "./"], "", $f);
        $content = json_decode(file_get_contents($f), true);
        $last_msg = end($content);
        $users[] = ["uid" => $id, "last_msg" => $last_msg['text'] ?? '', "name" => $last_msg['name'] ?? 'User'];
    }
    echo json_encode($users);
}

elseif ($action == 'delete_all' && $uid) {
    $file = $folder . "chat_" . $uid . ".json";
    if (file_exists($file)) {
        unlink($file);
    }
    echo json_encode(["status" => "success"]);
}

elseif ($action == 'delete') {
    $id_del = $_POST['id'] ?? '';
    if ($id_del && $id_del !== 'undefined') {
        $files = glob($folder . "chat_*.json");
        foreach ($files as $f) {
            if (file_exists($f)) {
                $content = json_decode(file_get_contents($f), true);
                if (is_array($content)) {
                    foreach ($content as $key => $msg) {
                        if (isset($msg['id']) && $msg['id'] == $id_del) {
                            array_splice($content, $key, 1);
                            if (empty($content)) {
                                unlink($f);
                            } else {
                                file_put_contents($f, json_encode($content));
                            }
                            break 2;
                        }
                    }
                }
            }
        }
    }
    echo json_encode(["status" => "success"]);
}


function json_content_decode($str) {
    return json_decode($str, true) ?: [];
}
?>