<?php
// Configuration
$data_file = 'licenses.txt';

// Get client IP address
$client_ip = $_SERVER['REMOTE_ADDR'];

// Get the key parameter
$key = isset($_GET['key']) ? trim($_GET['key']) : '';

// Check if key is provided
if (empty($key)) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Missing key parameter'
    ]);
    exit;
}

// Check if data file exists
if (!file_exists($data_file)) {
    echo json_encode([
        'status' => 'error',
        'message' => 'License data not available'
    ]);
    exit;
}

// Read and parse the data file
$license_data = [];
$lines = file($data_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

foreach ($lines as $line) {
    // Skip comment lines
    if (substr($line, 0, 1) === '#') continue;
    
    $parts = explode('|', $line);
    if (count($parts) >= 5) {
        $license_key = trim($parts[0]);
        $ip = trim($parts[1]);
        $brand = trim($parts[2]);
        $domain = trim($parts[3]);
        $expiry = trim($parts[4]);
        
        // Store data with key and IP as composite key
        $license_data[$license_key][$ip] = [
            'brand_name' => $brand,
            'domain_name' => $domain,
            'expire_date' => $expiry
        ];
    }
}

// Check if key exists
if (!isset($license_data[$key])) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid key'
    ]);
    exit;
}

// Check if IP is allowed for this key
$key_data = $license_data[$key];
$ip_allowed = false;
$license_info = [];

foreach ($key_data as $ip => $data) {
    if ($ip === $client_ip) {
        $ip_allowed = true;
        $license_info = $data;
        break;
    }
}

if (!$ip_allowed) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Please buy license'
    ]);
    exit;
}

// Return the successful response
echo json_encode([
    'status' => 'success',
    'brand_name' => $license_info['brand_name'],
    'domain_name' => $license_info['domain_name'],
    'expire_date' => $license_info['expire_date']
]);
?>