<?php
session_start();
include '../../function/connect.php';

mysqli_set_charset($koneksi, "utf8mb4");

// ==========================
// SESSION USER
// ==========================
$user = $_SESSION['username'] ?? null;

// ==========================
// DELETE CHAT SENDIRI
// ==========================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {

    if (!$user) {
        http_response_code(403);
        exit;
    }

    $chatId = intval($_POST['delete_id']);

    // pastikan chat milik user ini
    $cek = mysqli_query(
        $koneksi,
        "SELECT id FROM tb_chatpublic 
         WHERE id='$chatId' AND user='$user'
         LIMIT 1"
    );

    if (mysqli_num_rows($cek) === 1) {
        mysqli_query(
            $koneksi,
            "DELETE FROM tb_chatpublic WHERE id='$chatId'"
        );
        echo json_encode(['status' => 'ok']);
    } else {
        http_response_code(403);
    }
    exit;
}

// ==========================
// UPLOAD VOICE NOTE
// ==========================
if (isset($_FILES['voice'])) {

    if ($_FILES['voice']['error'] === UPLOAD_ERR_OK && $user) {

        $uploadDir = __DIR__ . '/temp/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $fileName   = 'voice_' . time() . '_' . rand(100,999) . '.webm';
        $uploadFile = $uploadDir . $fileName;
        $filePathDB = 'public/temp/' . $fileName;

        if (move_uploaded_file($_FILES['voice']['tmp_name'], $uploadFile)) {

            $stmt = mysqli_prepare(
                $koneksi,
                "INSERT INTO tb_chatpublic (user, msg, type)
                 VALUES (?, ?, 'voice')"
            );
            mysqli_stmt_bind_param($stmt, "ss", $user, $filePathDB);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_close($stmt);
        }
    }
    exit;
}

// ==========================
// POST TEXT MESSAGE
// ==========================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['message'])) {

    if (!$user) exit;

    $msg = trim($_POST['message']);

    if ($msg !== '') {
        $stmt = mysqli_prepare(
            $koneksi,
            "INSERT INTO tb_chatpublic (user, msg, type)
             VALUES (?, ?, 'text')"
        );
        mysqli_stmt_bind_param($stmt, "ss", $user, $msg);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_close($stmt);
    }
    exit;
}

// ==========================
// GET CHAT MESSAGES
// ==========================
header('Content-Type: application/json');

$result = mysqli_query(
    $koneksi,
    "SELECT 
        id,
        user,
        msg,
        type,
        DATE_FORMAT(time, '%H:%i') AS time
     FROM tb_chatpublic
     ORDER BY id DESC
     LIMIT 1000"
);

$data = [];
while ($row = mysqli_fetch_assoc($result)) {
    $data[] = $row;
}

echo json_encode(array_reverse($data));