<?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['license_key']) || empty($data['machine_id'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing license_key or machine_id']);
    exit;
}

try {
    $db = getDB();
    
    // Check if license exists and is valid
    $stmt = $db->prepare("SELECT * FROM licenses WHERE license_key = ?");
    $stmt->execute([$data['license_key']]);
    $license = $stmt->fetch();
    
    if (!$license) {
        http_response_code(404);
        echo json_encode(['success' => false, 'error' => 'Invalid license key']);
        exit;
    }
    
    // Check if license is revoked
    if ($license['status'] === 'revoked') {
        echo json_encode(['success' => false, 'error' => 'License has been revoked']);
        exit;
    }
    
    // Check if license is expired
    if ($license['expires_at'] && strtotime($license['expires_at']) < time()) {
        $db->prepare("UPDATE licenses SET status = 'expired' WHERE id = ?")->execute([$license['id']]);
        echo json_encode(['success' => false, 'error' => 'License has expired']);
        exit;
    }
    
    // Check device limit
    $stmt = $db->prepare("SELECT COUNT(*) as count FROM license_activations WHERE license_key = ?");
    $stmt->execute([$data['license_key']]);
    $activeDevices = $stmt->fetch()['count'];
    
    // Check if this machine is already activated
    $stmt = $db->prepare("SELECT * FROM license_activations WHERE license_key = ? AND machine_id = ?");
    $stmt->execute([$data['license_key'], $data['machine_id']]);
    $existingActivation = $stmt->fetch();
    
    if ($existingActivation) {
        // Update last checked
        $db->prepare("UPDATE license_activations SET last_checked = NOW() WHERE id = ?")->execute([$existingActivation['id']]);
        echo json_encode([
            'success' => true,
            'message' => 'License already activated on this device',
            'plan_type' => $license['plan_type'],
            'expires_at' => $license['expires_at']
        ]);
        exit;
    }
    
    if ($activeDevices >= $license['max_devices']) {
        echo json_encode(['success' => false, 'error' => 'Maximum device limit reached']);
        exit;
    }
    
    // Activate license on this device
    $stmt = $db->prepare("INSERT INTO license_activations (license_key, machine_id, user_id, last_checked) VALUES (?, ?, ?, NOW())");
    $stmt->execute([$data['license_key'], $data['machine_id'], $data['user_id'] ?? null]);
    
    // Update user's license info if user_id provided
    if (!empty($data['user_id'])) {
        $db->prepare("UPDATE users SET license_key = ?, license_expires_at = ? WHERE id = ?")->execute([
            $data['license_key'],
            $license['expires_at'],
            $data['user_id']
        ]);
        
        // Update license user_id if not set
        if (!$license['user_id']) {
            $db->prepare("UPDATE licenses SET user_id = ? WHERE id = ?")->execute([$data['user_id'], $license['id']]);
        }
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'License activated successfully',
        'plan_type' => $license['plan_type'],
        'expires_at' => $license['expires_at']
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Server error: ' . $e->getMessage()]);
}
