<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit(0);

require_once '../config.php';

$data = json_decode(file_get_contents('php://input'), true);

if (empty($data['machine_id'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing machine_id']);
    exit;
}

try {
    $db = getDB();
    
    $stmt = $db->prepare("
        SELECT u.license_key, u.license_expires_at, l.plan_type, l.max_devices, l.status,
        (SELECT COUNT(*) FROM license_activations WHERE license_key = u.license_key) as active_devices
        FROM users u
        LEFT JOIN licenses l ON u.license_key = l.license_key
        WHERE u.machine_id = ?
    ");
    $stmt->execute([$data['machine_id']]);
    $info = $stmt->fetch();
    
    if (!$info || !$info['license_key']) {
        echo json_encode(['success' => false, 'error' => 'No license found']);
        exit;
    }
    
    $daysRemaining = null;
    if ($info['license_expires_at']) {
        $daysRemaining = max(0, floor((strtotime($info['license_expires_at']) - time()) / 86400));
    }
    
    echo json_encode([
        'success' => true,
        'license_key' => $info['license_key'],
        'plan_type' => $info['plan_type'],
        'expires_at' => $info['license_expires_at'],
        'days_remaining' => $daysRemaining,
        'max_devices' => $info['max_devices'],
        'active_devices' => $info['active_devices'],
        'status' => $info['status']
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Server error']);
}
