<?php
/**
 * License Server Configuration
 */

// Database Configuration
define('DB_HOST', 'localhost');
define('DB_NAME', 'license_srv');
define('DB_USER', 'license_srv');
define('DB_PASS', 'Chronorex2025@');
define('DB_CHARSET', 'utf8mb4');

// Security
define('SECRET_KEY', 'chronorex-license-key-2026-secure-random-string');
define('JWT_SECRET', 'jwt-secret-key-for-admin-dashboard-2026');
define('JWT_EXPIRY', 86400); // 24 hours

// API Settings
define('API_VERSION', 'v1');
define('RATE_LIMIT', 60); // requests per minute
define('CACHE_TTL', 3600); // 1 hour

// =====================================================
// 🌐 PUBLIC URL CONFIGURATION
// =====================================================
// Set this to your License Server's public URL for production deployments.
// This URL will be embedded in connection tokens sent to ERP clients.
// Leave empty ('') to auto-detect from the current request.
// Examples:
//   'https://license.votredomaine.com'
//   'https://votredomaine.com/license-server'
//   '' (empty = auto-detect)
// =====================================================
define('LICENSE_SERVER_PUBLIC_URL', '');

// Session
session_start();

// Error Reporting (disable in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Timezone
date_default_timezone_set('Europe/Paris');

// Database Connection
try {
    $pdo = new PDO(
        "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET,
        DB_USER,
        DB_PASS,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false
        ]
    );
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

/**
 * Generate UUID v4
 */
function generateUUID() {
    return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand(0, 0xffff), mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        mt_rand(0, 0x0fff) | 0x4000,
        mt_rand(0, 0x3fff) | 0x8000,
        mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
    );
}

/**
 * Generate License Key
 */
function generateLicenseKey($tenantCode) {
    $data = $tenantCode . '-' . time() . '-' . bin2hex(random_bytes(8));
    return strtoupper(substr(hash('sha256', $data), 0, 32));
}

/**
 * JSON Response Helper
 */
function jsonResponse($data, $statusCode = 200) {
    http_response_code($statusCode);
    header('Content-Type: application/json');
    echo json_encode($data);
    exit;
}

/**
 * Check if admin is logged in
 */
function isAdminLogged() {
    if (!isset($_SESSION['admin_user'])) {
        header('Location: login.php');
        exit;
    }
    return $_SESSION['admin_user'];
}

/**
 * HMAC Signature for API
 */
function signResponse($data) {
    $json = json_encode($data);
    return hash_hmac('sha256', $json, SECRET_KEY);
}

/**
 * Verify API Request Signature
 */
function verifyApiSignature($licenseKey, $signature, $timestamp) {
    if (abs(time() - $timestamp) > 300) {
        return false;
    }
    $expected = hash_hmac('sha256', $licenseKey . $timestamp, SECRET_KEY);
    return hash_equals($expected, $signature);
}

/**
 * Generate Connection Token (for easy ERP connection)
 * Encodes license_key + server URL in a single base64 token
 * Uses LICENSE_SERVER_PUBLIC_URL if configured, otherwise auto-detects
 */
function generateConnectionToken($licenseKey) {
    // Use configured public URL if set
    if (defined('LICENSE_SERVER_PUBLIC_URL') && !empty(LICENSE_SERVER_PUBLIC_URL)) {
        $serverUrl = rtrim(LICENSE_SERVER_PUBLIC_URL, '/');
    } else {
        // Auto-detect from current request
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
        $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
        
        // Get the base path to license-server directory
        $scriptPath = $_SERVER['SCRIPT_NAME'] ?? '';
        
        // Find the license-server directory in the path
        if (preg_match('#(/license-server)#', $scriptPath, $matches)) {
            $basePath = $matches[1];
        } else {
            $basePath = dirname(dirname($scriptPath));
        }
        
        $serverUrl = $protocol . '://' . $host . $basePath;
        $serverUrl = rtrim($serverUrl, '/');
    }
    
    $payload = json_encode([
        'license_key' => $licenseKey,
        'server_url' => $serverUrl,
        'created_at' => time()
    ]);
    
    return base64_encode($payload);
}

/**
 * Decode Connection Token
 */
function decodeConnectionToken($token) {
    $decoded = base64_decode($token, true);
    if ($decoded === false) {
        return null;
    }
    $data = json_decode($decoded, true);
    if (!$data || !isset($data['license_key']) || !isset($data['server_url'])) {
        return null;
    }
    return $data;
}
