<?php
// API Security Configuration
// This file contains security settings for the API endpoints

// API Key for client authentication
// Change this to a secure, random key in production
define('API_KEY', 'ensi_app_2025_secure_key_v1');

// Allowed User Agents
// These are the user agents that are allowed to access the API
define('ALLOWED_USER_AGENTS', [
    'Dart/',           // Flutter/Dart HTTP client
    'ensi-flutter-app' // Custom user agent for your app
]);

// Helper function to validate API access
function validateApiAccess() {
    // Check API Key
    $apiKey = $_SERVER['HTTP_X_API_KEY'] ?? $_GET['api_key'] ?? '';
    if ($apiKey !== API_KEY) {
        http_response_code(403);
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access. Invalid API key.',
            'status_code' => 403
        ]);
        exit;
    }
    
    // Check User Agent
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $isValidUserAgent = false;
    
    foreach (ALLOWED_USER_AGENTS as $allowedAgent) {
        if (strpos($userAgent, $allowedAgent) !== false) {
            $isValidUserAgent = true;
            break;
        }
    }
    
    if (!$isValidUserAgent) {
        http_response_code(403);
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access. Invalid client.',
            'status_code' => 403
        ]);
        exit;
    }
    
    // Optional: Log access attempts for monitoring
    error_log("API Access: " . $userAgent . " from " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
}

// Rate limiting configuration (optional)
define('RATE_LIMIT_REQUESTS', 100); // Max requests per minute
define('RATE_LIMIT_WINDOW', 60);    // Time window in seconds

// IP whitelist (optional - add your server IPs here)
define('ALLOWED_IPS', [
    // '127.0.0.1',     // localhost
    // '192.168.1.0',   // your server IP
]);

// Function to check rate limiting (optional implementation)
function checkRateLimit($clientId) {
    // Implementation would depend on your caching system (Redis, Memcached, etc.)
    // For now, this is just a placeholder
    return true;
}

// Function to check IP whitelist (optional implementation)
function checkIPWhitelist() {
    if (empty(ALLOWED_IPS)) {
        return true; // No IP restriction if whitelist is empty
    }
    
    $clientIP = $_SERVER['REMOTE_ADDR'] ?? '';
    return in_array($clientIP, ALLOWED_IPS);
}
?>