<?php
// sales/verify.php - License Validation API endpoint (accessed by local installations)
require_once __DIR__ . '/config.php';

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

$license_key = trim($_GET['license_key'] ?? '');
$current_members = intval($_GET['members'] ?? 0);

if (empty($license_key)) {
    echo json_encode(['valid' => false, 'error' => 'Kein Lizenzschlüssel übermittelt.']);
    exit;
}

try {
    // Look up license in database
    $stmt = $sales_pdo->prepare("SELECT * FROM licenses WHERE license_key = :key AND status = 'active'");
    $stmt->execute([':key' => $license_key]);
    $license = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($license) {
        $modules = json_decode($license['modules'], true) ?? [];
        $max_members = intval($license['max_members']);
        
        // Determine license type
        $type = 'core';
        if (strpos($license_key, 'TMP-FORUM-') === 0) {
            $type = 'addon';
            $addon_name = 'forum';
        } elseif (strpos($license_key, 'TMP-PLAYRIGHT-') === 0) {
            $type = 'addon';
            $addon_name = 'playright';
        }

        // Limit Check for Core License
        if ($type === 'core' && $max_members > 0 && $current_members > $max_members) {
            echo json_encode([
                'valid' => false,
                'error' => 'Mitglieder-Limit überschritten',
                'details' => "Ihre Lizenz erlaubt maximal $max_members Mitglieder, Sie verwalten aktuell jedoch $current_members. Bitte buchen Sie ein Upgrade auf team-mania.de."
            ]);
            exit;
        }

        // Valid license response
        $response = [
            'valid' => true,
            'type' => $type,
            'club_name' => $license['club_name'],
            'max_members' => $max_members
        ];
        
        if ($type === 'addon') {
            $response['addon_name'] = $addon_name;
        }

        echo json_encode($response);
        exit;
    }

    echo json_encode(['valid' => false, 'error' => 'Lizenzschlüssel ungültig, abgelaufen oder gesperrt.']);
} catch (PDOException $e) {
    echo json_encode(['valid' => false, 'error' => 'Datenbank-Fehler auf dem Lizenz-Server: ' . $e->getMessage()]);
}
