<?php
// Mencegah output karakter liar
ob_start();
session_start();
// --- TAMBAHKAN KODE INI ---
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
// -------------------------
// Panggil koneksi database
require_once '../config/database.php';

// Cek apakah user sudah login
if (!isset($_SESSION['user_id'])) {
    header('Content-Type: application/json');
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

$user_id = $_SESSION['user_id'];

// --- [CSRF PROTECTION: TAMBAHKAN BLOK INI] ---
$client_token = $_POST['csrf_token'] ?? '';
$server_token = $_SESSION['csrf_token'] ?? '';

if (empty($client_token) || !hash_equals($server_token, $client_token)) {
    ob_clean();
    header('Content-Type: application/json');
    http_response_code(403); // Status Forbidden
    echo json_encode(['status' => 'error', 'message' => 'Permintaan tidak sah (CSRF terdeteksi).']);
    exit;
}
// ---------------------------------------------

// Hapus riwayat chat hanya milik user yang sedang login
// Menggunakan Prepared Statement agar lebih aman
// --- [SMART DELETE: BISA HAPUS SEMUA ATAU SATU SESI] ---
$session_id = $_POST['session_id'] ?? ''; // Tangkap session_id dari titik tiga

if (!empty($session_id)) {
    // 1. Jika tombol titik tiga di-klik (Hapus 1 Obrolan Saja)
    $query = "DELETE FROM chat_history WHERE user_id = ? AND session_id = ?";
    $stmt = mysqli_prepare($conn, $query);
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, "is", $user_id, $session_id);
    }
} else {
    // 2. Jika tombol "Hapus Histori" merah di bawah di-klik (Hapus Semua)
    $query = "DELETE FROM chat_history WHERE user_id = ?";
    $stmt = mysqli_prepare($conn, $query);
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, "i", $user_id);
    }
}

if ($stmt) {
    mysqli_stmt_execute($stmt);
   
    // Jika berhasil
    ob_clean();
    header('Content-Type: application/json');
    echo json_encode(['status' => 'success', 'message' => 'Riwayat chat berhasil dihapus.']);
} else {
    // Jika gagal query
    ob_clean();
    header('Content-Type: application/json');
    echo json_encode(['status' => 'error', 'message' => 'Gagal menghapus database.']);
}

mysqli_stmt_close($stmt);
mysqli_close($conn);
exit;