<?php
/**
 * license-php/api/deactivate.php
 * POST /api/license/deactivate
 */

require_once __DIR__ . '/../lib/Response.php';
require_once __DIR__ . '/../lib/Database.php';
require_once __DIR__ . '/../lib/LicenseCrypto.php';
require_once __DIR__ . '/../lib/AuditLogger.php';

Response::handleCors();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    Response::json(405, ['success' => false, 'message' => 'Method Not Allowed']);
}

$config = require __DIR__ . '/../config/config.php';
$pdo = Database::getConnection($config);
$audit = new AuditLogger($pdo);

$body = Response::getJsonBody();
$token = trim((string)($body['token'] ?? ''));
$domain = LicenseCrypto::cleanDomain($body['domain'] ?? '');

if ($token) {
    $parts = explode('.', $token);
    if (count($parts) === 3) {
        $payload = json_decode(LicenseCrypto::base64UrlDecode($parts[1]), true);
        if ($payload && !empty($payload['license_id'])) {
            $audit->log($payload['license_id'], 'LICENSE_DEACTIVATED', $domain);
        }
    }
}

Response::json(200, [
    'success' => true,
    'message' => 'License deactivated successfully. Reverted to Demo Mode.'
]);
