<?php
require __DIR__ . '/_bootstrap.php';

$licenseKey = input('license_key');
$machineId  = input('machine_id');

if ($licenseKey === '' || $machineId === '') {
    respond(['valid' => false, 'message' => 'Missing license_key or machine_id'], 400);
}

$lic = findLicenseByKey($licenseKey);

if (!$lic) {
    respond(['valid' => false, 'message' => 'License key not found']);
}

if ($lic['status'] !== 'active') {
    respond(['valid' => false, 'message' => 'This license has been disabled']);
}

if ($lic['expires_at'] && strtotime($lic['expires_at']) < time()) {
    respond(['valid' => false, 'message' => 'License has expired', 'expiredOn' => $lic['expires_at']]);
}

$pdo = db();

$stmt = $pdo->prepare('SELECT * FROM activations WHERE license_id = ? AND machine_id = ?');
$stmt->execute([$lic['id'], $machineId]);
$activation = $stmt->fetch();

if (!$activation) {
    if (activationCount($lic['id']) >= (int) $lic['max_activations']) {
        respond(['valid' => false, 'message' => 'Activation limit reached for this license. Ask the seller to deactivate an old device first.']);
    }
    $stmt = $pdo->prepare('INSERT INTO activations (license_id, machine_id) VALUES (?, ?)');
    $stmt->execute([$lic['id'], $machineId]);
} else {
    $stmt = $pdo->prepare('UPDATE activations SET last_seen_at = CURRENT_TIMESTAMP WHERE id = ?');
    $stmt->execute([$activation['id']]);
}

$features = array_values(array_filter(explode(',', $lic['features'])));
$remainingDays = $lic['expires_at']
    ? max(0, (int) ceil((strtotime($lic['expires_at']) - time()) / 86400))
    : null;

respond([
    'valid'           => true,
    'features'        => $features,
    'expires_at'      => $lic['expires_at'] ?: null,
    'remaining_days'  => $remainingDays,
    'max_activations' => (int) $lic['max_activations'],
]);
