<?php
class Notification {
    private $db;
    private $table = 'notifications';

    public function __construct($db) {
        $this->db = $db;
    }

    public function create($data) {
        try {
            $query = "INSERT INTO {$this->table} (user_id, type, title, message) VALUES (:user_id, :type, :title, :message)";
            $stmt = $this->db->prepare($query);
            
            // Convert null to actual null if needed
            $userId = !empty($data['user_id']) ? (int)$data['user_id'] : null;
            
            // Use bindValue instead of bindParam to avoid reference issues
            $stmt->bindValue(':user_id', $userId, $userId === null ? PDO::PARAM_NULL : PDO::PARAM_INT);
            $stmt->bindValue(':type', $data['type'] ?? 'info', PDO::PARAM_STR);
            $stmt->bindValue(':title', $data['title'] ?? '', PDO::PARAM_STR);
            $stmt->bindValue(':message', $data['message'] ?? '', PDO::PARAM_STR);
            
            $result = $stmt->execute();
            
            if (!$result) {
                $errorInfo = $stmt->errorInfo();
                error_log("Failed to create notification: " . ($errorInfo[2] ?? 'Unknown error'));
                return false;
            }
            
            return $this->db->lastInsertId();
        } catch (PDOException $e) {
            error_log("Database error in Notification::create: " . $e->getMessage());
            return false;
        }
    }

    public function getByUserId($userId, $limit = 10, $offset = 0) {
        $query = "SELECT * FROM {$this->table} WHERE user_id = :user_id OR user_id IS NULL ORDER BY created_at DESC LIMIT :limit OFFSET :offset";
        $stmt = $this->db->prepare($query);
        
        $stmt->bindValue(':user_id', $userId, PDO::PARAM_INT);
        $stmt->bindValue(':limit', (int)$limit, PDO::PARAM_INT);
        $stmt->bindValue(':offset', (int)$offset, PDO::PARAM_INT);
        
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function markAsRead($notificationId, $userId) {
        $query = "UPDATE {$this->table} SET is_read = 1 WHERE id = :id AND (user_id = :user_id OR user_id IS NULL)";
        $stmt = $this->db->prepare($query);
        
        $stmt->bindParam(':id', $notificationId, PDO::PARAM_INT);
        $stmt->bindParam(':user_id', $userId, PDO::PARAM_INT);
        
        return $stmt->execute();
    }

    public function getUnreadCount($userId) {
        $query = "SELECT COUNT(*) as count FROM {$this->table} WHERE (user_id = :user_id OR user_id IS NULL) AND is_read = 0";
        $stmt = $this->db->prepare($query);
        
        $stmt->bindParam(':user_id', $userId, PDO::PARAM_INT);
        $stmt->execute();
        
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result ? (int)$result['count'] : 0;
    }
}
