<?php

require_once __DIR__ . '/../models/IPWhitelist.php';
require_once __DIR__ . '/../models/ApiKey.php';
require_once __DIR__ . '/../utilities/Validator.php';
require_once __DIR__ . '/../utilities/Logger.php';

/**
 * Controller for managing IP whitelists
 */
class IPWhitelistController {
    /**
     * Add an IP to the whitelist
     * 
     * @param string $apiKey API key
     * @param string $ipAddress IP address to whitelist
     * @param string $description Optional description
     * @return array Response
     */
    public function addIP($apiKey, $ipAddress, $description = null) {
        // Validate API key
        $apiKeyInfo = ApiKey::validate($apiKey);
        if (!$apiKeyInfo['valid']) {
            return [
                'success' => false,
                'error' => [
                    'message' => 'Invalid API key',
                    'code' => 'INVALID_API_KEY'
                ]
            ];
        }
        
        // Verify the user has permission (using the API key's own IP)
        if (!IPWhitelist::isWhitelisted($apiKeyInfo['client_id'], $_SERVER['REMOTE_ADDR'])) {
            Logger::log(Logger::WARNING, "IP not authorized for whitelist management", [
                'client_id' => $apiKeyInfo['client_id'],
                'ip' => $_SERVER['REMOTE_ADDR']
            ]);
            
            return [
                'success' => false,
                'error' => [
                    'message' => 'Your IP is not authorized to manage whitelists',
                    'code' => 'UNAUTHORIZED_IP'
                ]
            ];
        }
        
        // Validate IP address format
        if (!filter_var($ipAddress, FILTER_VALIDATE_IP)) {
            return [
                'success' => false,
                'error' => [
                    'message' => 'Invalid IP address format',
                    'code' => 'INVALID_IP_FORMAT'
                ]
            ];
        }
        
        // Add the IP to whitelist
        $result = IPWhitelist::add($apiKeyInfo['client_id'], $ipAddress, $description);
        
        return $result;
    }
    
    /**
     * Remove an IP from the whitelist
     * 
     * @param string $apiKey API key
     * @param string $ipAddress IP address to remove
     * @return array Response
     */
    public function removeIP($apiKey, $ipAddress) {
        // Validate API key
        $apiKeyInfo = ApiKey::validate($apiKey);
        if (!$apiKeyInfo['valid']) {
            return [
                'success' => false,
                'error' => [
                    'message' => 'Invalid API key',
                    'code' => 'INVALID_API_KEY'
                ]
            ];
        }
        
        // Verify the user has permission (using the API key's own IP)
        if (!IPWhitelist::isWhitelisted($apiKeyInfo['client_id'], $_SERVER['REMOTE_ADDR'])) {
            Logger::log(Logger::WARNING, "IP not authorized for whitelist management", [
                'client_id' => $apiKeyInfo['client_id'],
                'ip' => $_SERVER['REMOTE_ADDR']
            ]);
            
            return [
                'success' => false,
                'error' => [
                    'message' => 'Your IP is not authorized to manage whitelists',
                    'code' => 'UNAUTHORIZED_IP'
                ]
            ];
        }
        
        // Cannot remove your own IP
        if ($ipAddress === $_SERVER['REMOTE_ADDR']) {
            return [
                'success' => false,
                'error' => [
                    'message' => 'Cannot remove your own IP address',
                    'code' => 'CANNOT_REMOVE_OWN_IP'
                ]
            ];
        }
        
        // Remove the IP from whitelist
        $result = IPWhitelist::remove($apiKeyInfo['client_id'], $ipAddress);
        
        return $result;
    }
    
    /**
     * Get all whitelisted IPs
     * 
     * @param string $apiKey API key
     * @return array Response
     */
    public function getAll($apiKey) {
        // Validate API key
        $apiKeyInfo = ApiKey::validate($apiKey);
        if (!$apiKeyInfo['valid']) {
            return [
                'success' => false,
                'error' => [
                    'message' => 'Invalid API key',
                    'code' => 'INVALID_API_KEY'
                ]
            ];
        }
        
        // Verify the user has permission
        if (!IPWhitelist::isWhitelisted($apiKeyInfo['client_id'], $_SERVER['REMOTE_ADDR'])) {
            Logger::log(Logger::WARNING, "IP not authorized for whitelist retrieval", [
                'client_id' => $apiKeyInfo['client_id'],
                'ip' => $_SERVER['REMOTE_ADDR']
            ]);
            
            return [
                'success' => false,
                'error' => [
                    'message' => 'Your IP is not authorized to view whitelists',
                    'code' => 'UNAUTHORIZED_IP'
                ]
            ];
        }
        
        // Get all whitelisted IPs
        $result = IPWhitelist::getAll($apiKeyInfo['client_id']);
        
        return $result;
    }
} 