<?php
/**
 * Controller Push Notifications
 * Gestion des souscriptions et notifications push PWA
 */

namespace App\Controllers;

use Core\Controller;
use App\Services\PushNotificationService;

require_once APP_PATH . '/Services/PushNotificationService.php';

class PushController extends Controller
{
    private PushNotificationService $pushService;

    public function __construct()
    {
        parent::__construct();
        $this->pushService = new PushNotificationService();
        
        header('Content-Type: application/json');
    }

    /**
     * Enregistrer une souscription push
     */
    public function subscribe(): void
    {
        if (!isset($_SESSION['user_id'])) {
            $this->json(['success' => false, 'error' => 'Non authentifié'], 401);
            return;
        }

        $input = json_decode(file_get_contents('php://input'), true);
        
        if (empty($input['endpoint']) || empty($input['keys'])) {
            $this->json(['success' => false, 'error' => 'Données invalides'], 400);
            return;
        }

        $userId = $_SESSION['user_id'];
        $entrepriseId = $_SESSION['entreprise_id'] ?? 0;

        $result = $this->pushService->subscribe($userId, $entrepriseId, $input);

        $this->json([
            'success' => $result,
            'message' => $result ? 'Souscription enregistrée' : 'Erreur lors de l\'enregistrement'
        ]);
    }

    /**
     * Supprimer une souscription push
     */
    public function unsubscribe(): void
    {
        if (!isset($_SESSION['user_id'])) {
            $this->json(['success' => false, 'error' => 'Non authentifié'], 401);
            return;
        }

        $input = json_decode(file_get_contents('php://input'), true);
        $endpoint = $input['endpoint'] ?? '';

        if (empty($endpoint)) {
            $this->json(['success' => false, 'error' => 'Endpoint manquant'], 400);
            return;
        }

        $result = $this->pushService->unsubscribe($_SESSION['user_id'], $endpoint);

        $this->json([
            'success' => $result,
            'message' => 'Souscription supprimée'
        ]);
    }

    /**
     * Récupérer la clé publique VAPID
     */
    public function getVapidKey(): void
    {
        $this->json([
            'publicKey' => $this->pushService->getPublicKey()
        ]);
    }
}
