<?php
ob_clean();
header("Content-Type: application/json");

// 🔥 HANDLE FATAL
register_shutdown_function(function () {
    $error = error_get_last();
    if ($error !== NULL) {
        echo json_encode([
            "success" => false,
            "message" => "FATAL: " . $error['message']
        ]);
    }
});

error_reporting(E_ALL);
ini_set('display_errors', 0);

require_once __DIR__ . '/../config/koneksi.php';
require_once __DIR__ . '/../config/jwt.php';

// ================= AUTH =================
function getAuthHeader() {
    return $_SERVER['HTTP_AUTHORIZATION'] 
        ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] 
        ?? '';
}

$auth = getAuthHeader();

if (!$auth) {
    echo json_encode(["success"=>false,"message"=>"Unauthorized"]);
    exit;
}

$token = str_replace("Bearer ", "", $auth);
$userData = verifyJWT($token);

if (!$userData) {
    echo json_encode(["success"=>false,"message"=>"Token invalid"]);
    exit;
}

$userId = $userData['user_id'] ?? null;

if (!$userId) {
    echo json_encode(["success"=>false,"message"=>"User tidak valid"]);
    exit;
}

// ================= INPUT =================
$input = json_decode(file_get_contents("php://input"), true);

// 🔥 FIX UTAMA
if (!$input || !isset($input['id'])) {
    echo json_encode([
        "success"=>false,
        "message"=>"ID tidak ditemukan"
    ]);
    exit;
}

$id = $input['id'];

// ================= UPDATE =================
$stmt = $conn->prepare("
    UPDATE notifications 
    SET is_read=1
    WHERE id=? AND user_id=?
");

if (!$stmt) {
    echo json_encode([
        "success"=>false,
        "message"=>"Prepare error: ".$conn->error
    ]);
    exit;
}

$stmt->bind_param("ss", $id, $userId);

if (!$stmt->execute()) {
    echo json_encode([
        "success"=>false,
        "message"=>"Execute error: ".$stmt->error
    ]);
    exit;
}

echo json_encode([
    "success"=>true,
    "message"=>"Berhasil dibaca"
]);