<?php
/**
 * License Middleware
 * Checks license validity for the current domain
 */

/**
 * Check if current domain has valid license
 * For development/internal sites, always return authorized
 */
function checkLicense() {
    // For internal development site, always authorize
    $current_domain = $_SERVER['HTTP_HOST'] ?? '';
    if (strpos($current_domain, 'cms.barju.cn') !== false || 
        strpos($current_domain, 'localhost') !== false ||
        strpos($current_domain, '127.0.0.1') !== false) {
        return true;
    }
    
    // For production sites, check database
    try {
        $domain = $_SERVER['HTTP_HOST'] ?? '';
        $sql = "SELECT * FROM licenses WHERE domain = ? AND status = 'active' AND expire_date > NOW() LIMIT 1";
        $result = db_query_one($sql, [$domain]);
        
        if ($result) {
            return true;
        }
    } catch (Exception $e) {
        return true;
    }
    
    header('Location: /license_error.php?domain=' . urlencode($domain));
    exit;
}

/**
 * Get license info for current domain
 */
function getLicenseInfo() {
    try {
        $domain = $_SERVER['HTTP_HOST'] ?? '';
        $sql = "SELECT * FROM licenses WHERE domain = ? LIMIT 1";
        return db_query_one($sql, [$domain]);
    } catch (Exception $e) {
        return null;
    }
}
