<?php
header('Content-Type: application/json');
require_once '../includes/db_connect.php';

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    // Fetch notifications
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
    $filter = isset($_GET['filter']) ? $_GET['filter'] : 'unread';
    
    $whereClause = "WHERE is_read = 0";
    if ($filter === 'all') {
        $whereClause = "WHERE 1=1"; // Fetch all for history
        $limit = 50;
    }

    try {
        // Get Notifications
        $stmt = $pdo->prepare("SELECT * FROM notifications $whereClause ORDER BY created_at DESC LIMIT :limit");
        $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
        $stmt->execute();
        $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Get Unread Count
        $countStmt = $pdo->query("SELECT COUNT(*) FROM notifications WHERE is_read = 0");
        $unreadCount = $countStmt->fetchColumn();

        echo json_encode([
            'status' => 'success',
            'data' => $notifications,
            'unread_count' => (int)$unreadCount
        ]);
    } catch (PDOException $e) {
        http_response_code(500);
        echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
    }
} elseif ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (isset($input['action']) && $input['action'] === 'mark_read') {
        try {
            // Mark all as read for now, or specific ID if provided
            if (isset($input['id'])) {
                $stmt = $pdo->prepare("UPDATE notifications SET is_read = 1 WHERE id = :id");
                $stmt->execute([':id' => $input['id']]);
            } else {
                $pdo->exec("UPDATE notifications SET is_read = 1 WHERE is_read = 0");
            }
            echo json_encode(['status' => 'success']);
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['status' => 'error', 'message' => 'Database error']);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
    }
} else {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
}
