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

// 🔥 TANGKAP FATAL ERROR
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;
}

// ================= QUERY =================
$stmt = $conn->prepare("
    SELECT id, title, message, type, reference_id, is_read, created_at
    FROM notifications
    WHERE user_id=? AND is_deleted=0
    ORDER BY created_at DESC
    LIMIT 100
");

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

$stmt->bind_param("s", $userId);

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

// 🔥 TANPA get_result (ANTI CRASH)
$stmt->bind_result($id, $title, $message, $type, $ref, $is_read, $created);

$data = [];

while ($stmt->fetch()) {
    $data[] = [
        "id" => $id,
        "title" => $title,
        "message" => $message,
        "type" => $type,
        "reference_id" => $ref,
        "is_read" => $is_read,
        "created_at" => $created
    ];
}

echo json_encode([
    "success" => true,
    "data" => $data
]);