<?php
// Disable error display in production
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(E_ALL);

require_once __DIR__ . '/config.php';

// Start session with secure settings
if (session_status() === PHP_SESSION_NONE) {
    ini_set('session.cookie_httponly', 1);
    ini_set('session.cookie_secure', 1);
    ini_set('session.use_only_cookies', 1);
    ini_set('session.cookie_samesite', 'Strict');
    session_start();
}

// Set admin as logged in
$_SESSION['admin_logged_in'] = true;
$_SESSION['last_activity'] = time();
$_SESSION['login_ip'] = $_SERVER['REMOTE_ADDR'];

// Validate request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('HTTP/1.1 405 Method Not Allowed');
    die(json_encode(['success' => false, 'message' => 'Method not allowed']));
}

// Set JSON response header
header('Content-Type: application/json');

try {
    // Validate CSRF token
    $csrfToken = filter_input(INPUT_POST, 'csrf_token', FILTER_SANITIZE_STRING);
    if (!$csrfToken || !hash_equals($_SESSION['csrf_token'], $csrfToken)) {
        throw new Exception('Invalid CSRF token');
    }

    // Validate IP address
    $ip = filter_input(INPUT_POST, 'ip', FILTER_VALIDATE_IP);
    if (!$ip) {
        throw new Exception('Invalid IP address');
    }

    // Define file paths
    $whitelistFile = ROOT_DIR . 'whitelist.dat';
    $botsFile = LOGS_DIR . 'bots.txt';

    // Check if whitelist file is writable
    if (!is_writable($whitelistFile)) {
        throw new Exception('Whitelist file is not writable');
    }

    // Add IP to whitelist with file locking
    if (file_put_contents($whitelistFile, $ip . PHP_EOL, FILE_APPEND | LOCK_EX) === false) {
        throw new Exception('Failed to write to whitelist file');
    }

    // Remove IP from bots.txt if it exists
    if (file_exists($botsFile)) {
        if (!is_readable($botsFile) || !is_writable($botsFile)) {
            throw new Exception('Bots file is not readable/writable');
        }

        $lines = file($botsFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        if ($lines === false) {
            throw new Exception('Failed to read bots file');
        }

        $newLines = [];
        $found = false;

        foreach ($lines as $line) {
            $entry = json_decode($line, true);
            if ($entry && isset($entry['ip']) && $entry['ip'] === $ip) {
                $found = true;
            } else {
                $newLines[] = $line;
            }
        }

        if ($found) {
            if (file_put_contents($botsFile, implode(PHP_EOL, $newLines) . PHP_EOL, LOCK_EX) === false) {
                throw new Exception('Failed to update bots file');
            }
            Security::logSecurityEvent("IP $ip removed from bots.txt and added to whitelist");
        }
    }

    // Log successful whitelist addition
    Security::logSecurityEvent("IP $ip added to whitelist");

    echo json_encode([
        'success' => true,
        'message' => "IP $ip added to whitelist" . ($found ? " and removed from bots.txt" : "")
    ]);

} catch (Exception $e) {
    error_log('Whitelist error: ' . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>