<?php
// /elms/includes/elms_notifications.php
declare(strict_types=1);

if (!function_exists('lms_table_exists')) {
    function lms_table_exists(mysqli $db, string $table): bool {
        $safe = $db->real_escape_string($table);
        $res = $db->query("SHOW TABLES LIKE '{$safe}'");
        $ok = $res && $res->num_rows > 0;
        if ($res) $res->free();
        return $ok;
    }
}

if (!function_exists('lms_notifications_ensure_table')) {
    function lms_notifications_ensure_table(mysqli $db): void {
        $db->query("
            CREATE TABLE IF NOT EXISTS lms_notifications (
                id INT AUTO_INCREMENT PRIMARY KEY,

                user_type ENUM('student','lecturer','coordinator','admin') NOT NULL,
                user_id INT NOT NULL,

                title VARCHAR(255) NOT NULL,
                message TEXT NULL,

                link_url VARCHAR(500) NULL,
                icon VARCHAR(80) NULL DEFAULT 'bi-bell',
                type VARCHAR(50) NULL DEFAULT 'info',

                is_read TINYINT(1) NOT NULL DEFAULT 0,
                read_at DATETIME NULL,

                created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,

                KEY idx_user (user_type, user_id),
                KEY idx_read (is_read),
                KEY idx_created (created_at)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
        ");
    }
}

if (!function_exists('lms_notify')) {
    function lms_notify(
        mysqli $db,
        string $userType,
        int $userId,
        string $title,
        string $message = '',
        string $linkUrl = '',
        string $icon = 'bi-bell',
        string $type = 'info'
    ): bool {
        if ($userId <= 0) {
            return false;
        }

        $allowedTypes = ['student', 'lecturer', 'coordinator', 'admin'];

        if (!in_array($userType, $allowedTypes, true)) {
            return false;
        }

        lms_notifications_ensure_table($db);

        $stmt = $db->prepare("
            INSERT INTO lms_notifications
                (user_type, user_id, title, message, link_url, icon, type)
            VALUES
                (?, ?, ?, ?, ?, ?, ?)
        ");

        if (!$stmt) {
            return false;
        }

        $stmt->bind_param(
            'sisssss',
            $userType,
            $userId,
            $title,
            $message,
            $linkUrl,
            $icon,
            $type
        );

        $ok = $stmt->execute();
        $stmt->close();

        return $ok;
    }
}

if (!function_exists('lms_unread_notification_count')) {
    function lms_unread_notification_count(mysqli $db, string $userType, int $userId): int {
        if ($userId <= 0 || !lms_table_exists($db, 'lms_notifications')) {
            return 0;
        }

        $stmt = $db->prepare("
            SELECT COUNT(*) AS total
            FROM lms_notifications
            WHERE user_type = ?
              AND user_id = ?
              AND is_read = 0
        ");

        if (!$stmt) {
            return 0;
        }

        $stmt->bind_param('si', $userType, $userId);
        $stmt->execute();

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

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

if (!function_exists('lms_recent_notifications')) {
    function lms_recent_notifications(mysqli $db, string $userType, int $userId, int $limit = 8): array {
        if ($userId <= 0 || !lms_table_exists($db, 'lms_notifications')) {
            return [];
        }

        $limit = max(1, min(30, $limit));

        $stmt = $db->prepare("
            SELECT id, title, message, link_url, icon, type, is_read, created_at
            FROM lms_notifications
            WHERE user_type = ?
              AND user_id = ?
            ORDER BY id DESC
            LIMIT {$limit}
        ");

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

        $stmt->bind_param('si', $userType, $userId);
        $stmt->execute();

        $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();

        return $rows ?: [];
    }
}

if (!function_exists('lms_mark_notification_read')) {
    function lms_mark_notification_read(mysqli $db, string $userType, int $userId, int $notificationId): bool {
        if ($userId <= 0 || $notificationId <= 0 || !lms_table_exists($db, 'lms_notifications')) {
            return false;
        }

        $stmt = $db->prepare("
            UPDATE lms_notifications
            SET is_read = 1,
                read_at = NOW()
            WHERE id = ?
              AND user_type = ?
              AND user_id = ?
            LIMIT 1
        ");

        if (!$stmt) {
            return false;
        }

        $stmt->bind_param('isi', $notificationId, $userType, $userId);
        $stmt->execute();

        $ok = $stmt->affected_rows >= 0;
        $stmt->close();

        return $ok;
    }
}

if (!function_exists('lms_mark_all_notifications_read')) {
    function lms_mark_all_notifications_read(mysqli $db, string $userType, int $userId): bool {
        if ($userId <= 0 || !lms_table_exists($db, 'lms_notifications')) {
            return false;
        }

        $stmt = $db->prepare("
            UPDATE lms_notifications
            SET is_read = 1,
                read_at = NOW()
            WHERE user_type = ?
              AND user_id = ?
              AND is_read = 0
        ");

        if (!$stmt) {
            return false;
        }

        $stmt->bind_param('si', $userType, $userId);
        $stmt->execute();

        $ok = $stmt->affected_rows >= 0;
        $stmt->close();

        return $ok;
    }
}