<?php

require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/utilities/Logger.php';
require_once __DIR__ . '/models/IPWhitelist.php';

/**
 * Authentication class to handle API key validation
 */
class Authentication {
    /**
     * Extract API key from headers
     * 
     * @return string|null API key or null if not found
     */
    public static function getApiKey() {
        // Check for Authorization header
        $headers = getallheaders();
        if (!isset($headers['Authorization'])) {
            return null;
        }
        
        // Extract key from "Bearer {api_key}" format
        $auth = $headers['Authorization'];
        if (strpos($auth, 'Bearer ') !== 0) {
            return null;
        }
        
        return trim(substr($auth, 7));
    }
    
    /**
     * Validate API key and return client ID
     * 
     * @param string $apiKey API key to validate
     * @return string|false Client ID if valid, false otherwise
     */
    public static function validateApiKey($apiKey) {
        try {
            if (empty($apiKey)) {
                return false;
            }
            
            $db = Database::getApiConnection();
            
            // Validate API key in the database
            $stmt = $db->prepare("
                SELECT client_id, is_active, expiry_date 
                FROM api_keys 
                WHERE key_value = ?
            ");
            
            $stmt->bind_param("s", $apiKey);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows == 0) {
                Logger::log(Logger::WARNING, "Invalid API key attempted", ['key' => self::maskApiKey($apiKey)]);
                return false;
            }
            
            $row = $result->fetch_assoc();
            $stmt->close();
            
            // Check if key is active
            if (!$row['is_active']) {
                Logger::log(Logger::WARNING, "Inactive API key used", ['client_id' => $row['client_id']]);
                return false;
            }
            
            // Check if key is expired
            if (!empty($row['expiry_date']) && strtotime($row['expiry_date']) < time()) {
                Logger::log(Logger::WARNING, "Expired API key used", ['client_id' => $row['client_id']]);
                return false;
            }
            
            return $row['client_id'];
            
        } catch (Exception $e) {
            Logger::log(Logger::ERROR, "API key validation error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Check if the client's IP is whitelisted
     * 
     * @param string $clientId Client ID
     * @param string $ipAddress IP address to check
     * @return bool True if IP is whitelisted or no whitelist exists
     */
    public static function checkIpWhitelist($clientId, $ipAddress) {
        if (empty($clientId) || empty($ipAddress)) {
            return false;
        }
        
        try {
            // Use the IPWhitelist model to check if IP is whitelisted
            return IPWhitelist::isWhitelisted($clientId, $ipAddress);
        } catch (Exception $e) {
            Logger::log(Logger::ERROR, "IP whitelist check error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Mask API key for logging (show only first 4 and last 4 characters)
     * 
     * @param string $apiKey Full API key
     * @return string Masked API key
     */
    private static function maskApiKey($apiKey) {
        $length = strlen($apiKey);
        if ($length <= 8) {
            return str_repeat('*', $length);
        }
        
        return substr($apiKey, 0, 4) . str_repeat('*', $length - 8) . substr($apiKey, -4);
    }
} 