<?php
require_once '../config.php';
require_once '../../includes/Auth.php';
require_once '../../includes/Database.php';

header('Content-Type: application/json');

$auth = new Auth();
$user = $auth->requireAuth();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $subscription = file_get_contents('php://input');
    
    if (empty($subscription)) {
        jsonResponse(['success' => false, 'message' => 'No subscription data provided'], 400);
    }

    try {
        $db = new Database();
        
        // Check if subscription already exists for this user to avoid duplicates
        $db->query("DELETE FROM push_subscriptions WHERE user_id = ?", [$user['id']]);
        
        $db->query("INSERT INTO push_subscriptions (user_id, subscription) VALUES (?, ?)", [
            $user['id'],
            $subscription
        ]);

        jsonResponse(['success' => true, 'message' => 'Subscribed to push notifications']);
    } catch (Exception $e) {
        jsonResponse(['success' => false, 'message' => $e->getMessage()], 500);
    }
}