<?php
/**
 * Tom's Java Jive - Push Subscription API
 */

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

require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);

switch ($method) {
    case 'POST':
        // Subscribe to push notifications
        $endpoint = $input['endpoint'] ?? '';
        $p256dh = $input['keys']['p256dh'] ?? '';
        $auth = $input['keys']['auth'] ?? '';
        
        if (empty($endpoint) || empty($p256dh) || empty($auth)) {
            jsonResponse(['error' => 'Invalid subscription data'], 400);
        }
        
        $customerId = null;
        if (CustomerAuth::isLoggedIn()) {
            $customerId = CustomerAuth::getUser()['customer_id'];
        }
        
        // Check if subscription already exists
        $existing = db()->fetch(
            "SELECT id FROM push_subscriptions WHERE endpoint = :endpoint",
            ['endpoint' => $endpoint]
        );
        
        if ($existing) {
            // Update existing
            db()->query(
                "UPDATE push_subscriptions SET 
                    customer_id = :cid, p256dh_key = :p256dh, auth_key = :auth, 
                    is_active = 1, updated_at = NOW()
                 WHERE endpoint = :endpoint",
                ['cid' => $customerId, 'p256dh' => $p256dh, 'auth' => $auth, 'endpoint' => $endpoint]
            );
        } else {
            // Create new
            db()->insert('push_subscriptions', [
                'customer_id' => $customerId,
                'endpoint' => $endpoint,
                'p256dh_key' => $p256dh,
                'auth_key' => $auth,
                'is_active' => 1
            ]);
        }
        
        jsonResponse(['success' => true, 'message' => 'Subscribed to notifications']);
        break;
        
    case 'DELETE':
        // Unsubscribe
        $endpoint = $input['endpoint'] ?? '';
        
        if (empty($endpoint)) {
            jsonResponse(['error' => 'Endpoint required'], 400);
        }
        
        db()->query(
            "UPDATE push_subscriptions SET is_active = 0 WHERE endpoint = :endpoint",
            ['endpoint' => $endpoint]
        );
        
        jsonResponse(['success' => true, 'message' => 'Unsubscribed from notifications']);
        break;
        
    case 'GET':
        // Get VAPID public key
        require_once __DIR__ . '/../includes/push.php';
        jsonResponse(['publicKey' => pushNotify()->getPublicKey()]);
        break;
        
    default:
        jsonResponse(['error' => 'Method not allowed'], 405);
}
