<?php
/**
 * Notifications API Endpoints
 * v1/notifications
 */

global $method, $input, $queryParams, $apiResponse, $user, $conn, $segments;

switch ($method) {
    case 'GET':
        // Get notifications
        $page = $queryParams['page'] ?? 1;
        $per_page = min($queryParams['per_page'] ?? 20, 100);
        $offset = ($page - 1) * $per_page;
        
        // Get member_id if user is a member
        $member_id = null;
        if ($user['role_name'] === 'MEMBER') {
            $memberSql = "SELECT member_id FROM members WHERE user_id = ?";
            $memberStmt = $conn->prepare($memberSql);
            $memberStmt->bind_param("i", $user['user_id']);
            $memberStmt->execute();
            $memberResult = $memberStmt->get_result();
            $member = $memberResult->fetch_assoc();
            $member_id = $member['member_id'] ?? null;
        }
        
        $where = ["n.user_id = ?"];
        $params = [$user['user_id']];
        $types = 'i';
        
        if (isset($queryParams['unread_only']) && $queryParams['unread_only'] == '1') {
            $where[] = "n.is_read = 0";
        }
        
        $whereClause = implode(' AND ', $where);
        
        // Get total
        $countSql = "SELECT COUNT(*) as total FROM notifications n WHERE $whereClause";
        $countStmt = $conn->prepare($countSql);
        $countStmt->bind_param($types, ...$params);
        $countStmt->execute();
        $total = $countStmt->get_result()->fetch_assoc()['total'];
        
        // Get notifications
        $sql = "SELECT * FROM notifications 
                WHERE $whereClause
                ORDER BY created_at DESC
                LIMIT ? OFFSET ?";
        
        $params[] = $per_page;
        $params[] = $offset;
        $types .= 'ii';
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $notifications = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        
        $apiResponse->paginated($notifications, $page, $per_page, $total, 'Notifications retrieved');
        break;
        
    case 'PUT':
        // Mark notification as read
        if (empty($segments[2])) {
            $apiResponse->error('Notification ID required', 400);
        }
        
        $notification_id = $segments[2];
        
        $sql = "UPDATE notifications SET is_read = 1, read_at = NOW() 
                WHERE notification_id = ? AND user_id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ii", $notification_id, $user['user_id']);
        
        if ($stmt->execute()) {
            $apiResponse->success(null, 'Notification marked as read');
        } else {
            $apiResponse->error('Failed to update notification', 500);
        }
        break;
        
    default:
        $apiResponse->error('Method not allowed', 405);
}
