<?php

function createNotification($conn, $userId, $senderId, $orderId, $type, $title, $message, $link = null)
{
    $stmt = $conn->prepare("
        INSERT INTO notifications (
            user_id,
            sender_id,
            order_id,
            notification_type,
            title,
            message,
            link,
            is_read,
            created_at
        )
        VALUES (?, ?, ?, ?, ?, ?, ?, 0, NOW())
    ");

    if (!$stmt) {
        return false;
    }

    $stmt->bind_param(
        "iiissss",
        $userId,
        $senderId,
        $orderId,
        $type,
        $title,
        $message,
        $link
    );

    return $stmt->execute();
}

function getUnreadNotificationCount($conn, $userId)
{
    $stmt = $conn->prepare("
        SELECT COUNT(*) AS total
        FROM notifications
        WHERE user_id = ?
        AND is_read = 0
    ");

    if (!$stmt) {
        return 0;
    }

    $stmt->bind_param("i", $userId);
    $stmt->execute();

    $result = $stmt->get_result();
    $row = $result->fetch_assoc();

    return (int)($row["total"] ?? 0);
}

function getRecentNotifications($conn, $userId, $limit = 10)
{
    $stmt = $conn->prepare("
        SELECT 
            n.*,
            u.first_name,
            u.last_name
        FROM notifications n
        LEFT JOIN users u ON n.sender_id = u.id
        WHERE n.user_id = ?
        ORDER BY n.created_at DESC
        LIMIT ?
    ");

    if (!$stmt) {
        return [];
    }

    $stmt->bind_param("ii", $userId, $limit);
    $stmt->execute();

    $result = $stmt->get_result();
    $notifications = [];

    while ($row = $result->fetch_assoc()) {
        $notifications[] = $row;
    }

    return $notifications;
}