<?php

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

/**
 * IPWhitelist model for managing IP address whitelisting
 */
class IPWhitelist {
    /**
     * Check if an IP is whitelisted for a client
     * 
     * @param string $clientId Client ID
     * @param string $ipAddress IP address to check
     * @return bool True if IP is whitelisted
     */
    public static function isWhitelisted($clientId, $ipAddress) {
        try {
            $db = Database::getApiConnection();
            
            // Check if IP whitelisting is enabled for this client
            $stmt = $db->prepare("
                SELECT COUNT(*) as total
                FROM ip_whitelist
                WHERE client_id = ? AND is_active = 1
            ");
            
            $stmt->bind_param("s", $clientId);
            $stmt->execute();
            $result = $stmt->get_result();
            $row = $result->fetch_assoc();
            $stmt->close();
            
            // If no whitelist entries exist, IP whitelisting is not enabled
            if ($row['total'] == 0) {
                return true;
            }
            
            // Check if the specific IP is whitelisted
            $stmt = $db->prepare("
                SELECT id
                FROM ip_whitelist
                WHERE client_id = ? AND ip_address = ? AND is_active = 1
            ");
            
            $stmt->bind_param("ss", $clientId, $ipAddress);
            $stmt->execute();
            $result = $stmt->get_result();
            $isWhitelisted = $result->num_rows > 0;
            $stmt->close();
            
            return $isWhitelisted;
            
        } catch (Exception $e) {
            Logger::log(Logger::ERROR, "IP whitelist check error: " . $e->getMessage());
            // Default to not allowing if there's an error
            return false;
        }
    }
    
    /**
     * Add an IP to the whitelist
     * 
     * @param string $clientId Client ID
     * @param string $ipAddress IP address to whitelist
     * @param string $description Optional description
     * @return array Result with success status
     */
    public static function add($clientId, $ipAddress, $description = null) {
        try {
            $db = Database::getApiConnection();
            
            // Check if IP already exists
            $stmt = $db->prepare("
                SELECT id
                FROM ip_whitelist
                WHERE client_id = ? AND ip_address = ?
            ");
            
            $stmt->bind_param("ss", $clientId, $ipAddress);
            $stmt->execute();
            $result = $stmt->get_result();
            $exists = $result->num_rows > 0;
            $stmt->close();
            
            if ($exists) {
                // Update existing record
                $stmt = $db->prepare("
                    UPDATE ip_whitelist
                    SET is_active = 1,
                        description = ?,
                        updated_at = NOW()
                    WHERE client_id = ? AND ip_address = ?
                ");
                
                $stmt->bind_param("sss", $description, $clientId, $ipAddress);
                $stmt->execute();
                $stmt->close();
                
                Logger::log(Logger::INFO, "IP whitelist entry updated", [
                    'client_id' => $clientId,
                    'ip_address' => $ipAddress
                ]);
                
                return [
                    'success' => true,
                    'data' => [
                        'message' => 'IP whitelist entry updated',
                        'client_id' => $clientId,
                        'ip_address' => $ipAddress,
                        'description' => $description
                    ]
                ];
            } else {
                // Create new record
                $stmt = $db->prepare("
                    INSERT INTO ip_whitelist
                    (client_id, ip_address, description, is_active, created_at, updated_at)
                    VALUES (?, ?, ?, 1, NOW(), NOW())
                ");
                
                $stmt->bind_param("sss", $clientId, $ipAddress, $description);
                $stmt->execute();
                $id = $db->insert_id;
                $stmt->close();
                
                Logger::log(Logger::INFO, "IP whitelist entry created", [
                    'client_id' => $clientId,
                    'ip_address' => $ipAddress
                ]);
                
                return [
                    'success' => true,
                    'data' => [
                        'id' => $id,
                        'message' => 'IP whitelist entry created',
                        'client_id' => $clientId,
                        'ip_address' => $ipAddress,
                        'description' => $description
                    ]
                ];
            }
            
        } catch (Exception $e) {
            Logger::log(Logger::ERROR, "IP whitelist add error: " . $e->getMessage());
            return [
                'success' => false,
                'error' => [
                    'message' => 'Failed to add IP to whitelist',
                    'code' => 'SERVER_ERROR'
                ]
            ];
        }
    }
    
    /**
     * Remove an IP from the whitelist
     * 
     * @param string $clientId Client ID
     * @param string $ipAddress IP address to remove
     * @return array Result with success status
     */
    public static function remove($clientId, $ipAddress) {
        try {
            $db = Database::getApiConnection();
            
            // Deactivate the IP address (soft delete)
            $stmt = $db->prepare("
                UPDATE ip_whitelist
                SET is_active = 0,
                    updated_at = NOW()
                WHERE client_id = ? AND ip_address = ?
            ");
            
            $stmt->bind_param("ss", $clientId, $ipAddress);
            $stmt->execute();
            $affected = $stmt->affected_rows;
            $stmt->close();
            
            if ($affected == 0) {
                return [
                    'success' => false,
                    'error' => [
                        'message' => 'IP not found in whitelist',
                        'code' => 'NOT_FOUND'
                    ]
                ];
            }
            
            Logger::log(Logger::INFO, "IP removed from whitelist", [
                'client_id' => $clientId,
                'ip_address' => $ipAddress
            ]);
            
            return [
                'success' => true,
                'data' => [
                    'message' => 'IP removed from whitelist',
                    'client_id' => $clientId,
                    'ip_address' => $ipAddress
                ]
            ];
            
        } catch (Exception $e) {
            Logger::log(Logger::ERROR, "IP whitelist remove error: " . $e->getMessage());
            return [
                'success' => false,
                'error' => [
                    'message' => 'Failed to remove IP from whitelist',
                    'code' => 'SERVER_ERROR'
                ]
            ];
        }
    }
    
    /**
     * Get all whitelisted IPs for a client
     * 
     * @param string $clientId Client ID
     * @return array List of whitelisted IPs
     */
    public static function getAll($clientId) {
        try {
            $db = Database::getApiConnection();
            
            // Get all whitelisted IPs
            $stmt = $db->prepare("
                SELECT id, ip_address, description, created_at, updated_at
                FROM ip_whitelist
                WHERE client_id = ? AND is_active = 1
                ORDER BY created_at DESC
            ");
            
            $stmt->bind_param("s", $clientId);
            $stmt->execute();
            $result = $stmt->get_result();
            
            $ips = [];
            while ($row = $result->fetch_assoc()) {
                $ips[] = [
                    'id' => $row['id'],
                    'ip_address' => $row['ip_address'],
                    'description' => $row['description'],
                    'created_at' => date('c', strtotime($row['created_at'])),
                    'updated_at' => date('c', strtotime($row['updated_at']))
                ];
            }
            
            $stmt->close();
            
            return [
                'success' => true,
                'data' => $ips
            ];
            
        } catch (Exception $e) {
            Logger::log(Logger::ERROR, "Get IP whitelist error: " . $e->getMessage());
            return [
                'success' => false,
                'error' => [
                    'message' => 'Failed to retrieve IP whitelist',
                    'code' => 'SERVER_ERROR'
                ]
            ];
        }
    }
} 