<?php

class NotificationController {

    // ─── GET NOTIFICATIONS (for logged-in user) ─────────────────────────
    public static function getNotifications(): void {
        $user = AuthController::requireAuth();
        $userId = $user['id'];
        $db = getDb();

        $page  = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
        $limit = isset($_GET['limit']) ? min(50, max(1, (int)$_GET['limit'])) : 20;
        $offset = ($page - 1) * $limit;

        // Total count
        $countStmt = $db->prepare(
            "SELECT COUNT(*) as total FROM user_notifications WHERE user_id = ?"
        );
        $countStmt->bind_param("i", $userId);
        $countStmt->execute();
        $total = $countStmt->get_result()->fetch_assoc()['total'];
        $countStmt->close();

        // Fetch notifications with read status
        // COALESCE checks n.title/message (broadcasts) vs un.title/message (direct alerts)
        $stmt = $db->prepare(
            "SELECT 
                un.id as user_notif_id,
                un.notification_id,
                COALESCE(n.title, un.title, 'Notification') as title,
                COALESCE(n.message, un.message) as message,
                COALESCE(n.created_at, un.created_at) as created_at,
                un.is_read,
                un.read_at
             FROM user_notifications un
             LEFT JOIN notifications n ON n.id = un.notification_id
             WHERE un.user_id = ?
             ORDER BY created_at DESC
             LIMIT ? OFFSET ?"
        );
        $stmt->bind_param("iii", $userId, $limit, $offset);
        $stmt->execute();
        $result = $stmt->get_result();

        $notifications = [];
        while ($row = $result->fetch_assoc()) {
            $row['is_read'] = (bool)$row['is_read'];
            // For Flutter app compatibility, ensure id is the one expected
            $row['id'] = $row['notification_id'] ?? $row['user_notif_id'];
            $notifications[] = $row;
        }
        $stmt->close();

        sendSuccess([
            'notifications' => $notifications,
            'page'          => $page,
            'limit'         => $limit,
            'total'         => (int)$total,
        ]);
    }

    // ─── UNREAD COUNT ────────────────────────────────────────────────────
    public static function getUnreadCount(): void {
        $user = AuthController::requireAuth();
        $userId = $user['id'];
        $db = getDb();

        $stmt = $db->prepare(
            "SELECT COUNT(*) as unread FROM user_notifications WHERE user_id = ? AND is_read = 0"
        );
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $count = $stmt->get_result()->fetch_assoc()['unread'];
        $stmt->close();

        sendSuccess(['unread_count' => (int)$count]);
    }

    // ─── MARK ONE AS READ ────────────────────────────────────────────────
    public static function markAsRead(): void {
        $user = AuthController::requireAuth();
        $userId = $user['id'];
        $db = getDb();
        $data  = json_decode(file_get_contents("php://input"), true);

        $notificationId = $data['notification_id'] ?? null;
        if (!$notificationId) {
            sendError("notification_id is required", 400);
            return;
        }

        // We check both notification_id (for broadcasts) and id (for local alerts)
        $stmt = $db->prepare(
            "UPDATE user_notifications 
             SET is_read = 1, read_at = NOW() 
             WHERE user_id = ? AND (notification_id = ? OR id = ?)"
        );
        $stmt->bind_param("iii", $userId, $notificationId, $notificationId);
        $stmt->execute();
        $stmt->close();

        sendSuccess(['message' => 'Notification marked as read']);
    }

    // ─── MARK ALL AS READ ────────────────────────────────────────────────
    public static function markAllAsRead(): void {
        $user = AuthController::requireAuth();
        $userId = $user['id'];
        $db = getDb();

        $stmt = $db->prepare(
            "UPDATE user_notifications SET is_read = 1, read_at = NOW() WHERE user_id = ? AND is_read = 0"
        );
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $affected = $stmt->affected_rows;
        $stmt->close();

        sendSuccess(['message' => "$affected notifications marked as read"]);
    }

    // ─── DELETE NOTIFICATION ─────────────────────────────────────────────
    public static function deleteNotification(): void {
        $user = AuthController::requireAuth();
        $userId = $user['id'];
        $db = getDb();
        $data  = json_decode(file_get_contents("php://input"), true);

        $notificationId = $data['notification_id'] ?? null;
        if (!$notificationId) {
            sendError("notification_id is required", 400);
            return;
        }

        // Delete from user_notifications for this user
        $stmt = $db->prepare(
            "DELETE FROM user_notifications 
             WHERE user_id = ? AND (notification_id = ? OR id = ?)"
        );
        $stmt->bind_param("iii", $userId, $notificationId, $notificationId);
        $stmt->execute();
        $stmt->close();

        sendSuccess(['message' => 'Notification deleted successfully']);
    }
}

