<?php
/**
 * REST API Authentication Helper
 * Validates API requests and enforces usage limits
 */

require_once __DIR__ . '/../../config/database.php';

/**
 * Authenticate API request
 * @param string $apiKey API key from request header
 * @return array|false Returns API data or false on failure
 */
function authenticateAPI($apiKey) {
    if (empty($apiKey)) {
        return [
            'success' => false,
            'error' => 'API key is required',
            'code' => 'MISSING_API_KEY'
        ];
    }
    
    try {
        $db = getDB();
        
        // Get API key details
        $stmt = $db->prepare("SELECT * FROM api_keys WHERE api_key = ? LIMIT 1");
        $stmt->execute([$apiKey]);
        $api = $stmt->fetch();
        
        if (!$api) {
            return [
                'success' => false,
                'error' => 'Invalid API key',
                'code' => 'INVALID_API_KEY'
            ];
        }
        
        // Check if API is active
        if ($api['status'] !== 'active') {
            return [
                'success' => false,
                'error' => 'API key is disabled',
                'code' => 'API_DISABLED'
            ];
        }
        
        // Check usage limit if set
        if ($api['usage_limit'] !== null) {
            // Reset counter if new day
            $today = date('Y-m-d');
            if ($api['reset_date'] !== $today) {
                $stmt = $db->prepare("UPDATE api_keys SET used_count = 0, reset_date = ? WHERE id = ?");
                $stmt->execute([$today, $api['id']]);
                $api['used_count'] = 0;
            }
            
            // Check if limit exceeded
            if ($api['used_count'] >= $api['usage_limit']) {
                return [
                    'success' => false,
                    'error' => 'API usage limit exceeded',
                    'code' => 'LIMIT_EXCEEDED',
                    'limit' => $api['usage_limit'],
                    'used' => $api['used_count']
                ];
            }
        }
        
        return [
            'success' => true,
            'api' => $api
        ];
        
    } catch (PDOException $e) {
        error_log("API Auth Error: " . $e->getMessage());
        return [
            'success' => false,
            'error' => 'Internal server error',
            'code' => 'SERVER_ERROR'
        ];
    }
}

/**
 * Increment API usage counter
 */
function incrementAPIUsage($apiId) {
    try {
        $db = getDB();
        $stmt = $db->prepare("
            UPDATE api_keys 
            SET used_count = used_count + 1, 
                last_used = NOW() 
            WHERE id = ?
        ");
        $stmt->execute([$apiId]);
    } catch (PDOException $e) {
        error_log("Increment usage error: " . $e->getMessage());
    }
}

/**
 * Log API request
 */
function logAPIRequest($apiKey, $requestType, $serverId = null, $responseStatus = 'success', $deviceId = null) {
    try {
        $db = getDB();
        
        $ipAddress = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
        $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? null;
        
        $stmt = $db->prepare("
            INSERT INTO api_logs (api_key, device_id, request_type, server_id, ip_address, user_agent, response_status)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([$apiKey, $deviceId, $requestType, $serverId, $ipAddress, $userAgent, $responseStatus]);
        
    } catch (PDOException $e) {
        error_log("Log API error: " . $e->getMessage());
    }
}

/**
 * Get API key from request headers
 */
function getAPIKeyFromRequest() {
    // Check Authorization header
    if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
        $auth = $_SERVER['HTTP_AUTHORIZATION'];
        if (preg_match('/Bearer\s+(.*)$/i', $auth, $matches)) {
            return $matches[1];
        }
    }
    
    // Check X-API-Key header
    if (isset($_SERVER['HTTP_X_API_KEY'])) {
        return $_SERVER['HTTP_X_API_KEY'];
    }
    
    // Check api_key GET parameter (less secure, but convenient for testing)
    if (isset($_GET['api_key'])) {
        return $_GET['api_key'];
    }
    
    return null;
}
