<?php
register_shutdown_function(function () {
    $err = error_get_last();
    if ($err && in_array($err['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR], true)) {
        echo json_encode(['status' => 'error', 'message' => 'Fatal: ' . $err['message']]);
    }
});

try {
require_once '../config/database.php';
require_once '../app/helpers/api_security.php';
header('Content-Type: application/json; charset=utf-8');
    requireApiLogin();
    enforceCsrfForUnsafeRequest();

    $userId = (int)($_SESSION['user_id'] ?? 0);
    if ($userId <= 0) {
        apiRespond(['status' => 'error', 'message' => 'Unauthorized'], 401);
    }
    $action = $_GET['action'] ?? '';

    switch ($action) {

    case 'list':

        $stmt = $pdo->prepare("
            SELECT id, user_id, title, message, type, url, reference_id, is_read, created_at
            FROM notifications
            WHERE user_id=? AND deleted_at IS NULL
            ORDER BY id DESC
            LIMIT 10
        ");
        $stmt->execute([$userId]);

        apiRespond(['status' => 'success', 'data' => $stmt->fetchAll()]);
        break;

    case 'count':

        $count = $pdo->prepare("
            SELECT COUNT(*) FROM notifications
            WHERE user_id=? AND is_read=0 AND deleted_at IS NULL
        ");
        $count->execute([$userId]);

        apiRespond(['status' => 'success', 'data' => ['count' => (int)$count->fetchColumn()]]);
        break;

    case 'mark_read':

        $pdo->prepare("
            UPDATE notifications SET is_read=1 WHERE user_id=?
        ")->execute([$userId]);

        apiRespond(['status' => 'success']);
        break;

    case 'mark_one':

        $stmt = $pdo->prepare("
            UPDATE notifications
            SET is_read=1
            WHERE id=? AND user_id=?
        ");
        $stmt->execute([(int)($_POST['id'] ?? 0), $userId]);

        apiRespond(['status' => 'success']);
        break;

    default:
        apiRespond(['status' => 'error', 'message' => 'Unknown action']);
    }
} catch (Throwable $e) {
    apiRespond(['status' => 'error', 'message' => $e->getMessage()], 500);
}
