<?php
// Allow CORS
// Include the reusable CORS handler
require_once __DIR__ . '/cors.php';


require_once __DIR__ . '/db.php'; // ✅ Add DB connection
header('Content-Type: application/json');

$data = json_decode(file_get_contents('php://input'), true);
file_put_contents('debug.log', print_r($data, true)); // Debug log


switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        if (isset($_GET['unread_count'])) {
            // ✅ Return count of unread notifications
            $stmt = $pdo->query("SELECT COUNT(*) as count FROM notifications WHERE is_read = 0");
            echo json_encode($stmt->fetch(PDO::FETCH_ASSOC));
        } elseif (isset($_GET['mark_as_read'])) {
            // ✅ Mark all notifications as read
            $stmt = $pdo->query("UPDATE notifications SET is_read = 1 WHERE is_read = 0");
            echo json_encode(['status' => 'updated']);
        } else {
            // ✅ Return latest notifications
            $stmt = $pdo->query("SELECT * FROM notifications ORDER BY created_at DESC LIMIT 10");
            echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
        }
        break;

    case 'POST':
        // ✅ Add new notification with is_read = 0 by default
        $stmt = $pdo->prepare("INSERT INTO notifications (title, message, is_read) VALUES (?, ?, 0)");
        $stmt->execute([$data['title'], $data['message']]);
        echo json_encode(['status' => 'created']);
        break;

    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
}
