<?php
session_start();
header('Content-Type: application/json');

// Check session
if (empty($_SESSION['access_token'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

$allowFile = __DIR__ . '/../../admin/allow.json';

// Initialize allow data structure
function getAllowData() {
    global $allowFile;
    if (file_exists($allowFile)) {
        $data = json_decode(file_get_contents($allowFile), true);
        return $data ?: [
            'countries' => [],
            'ips' => [],
            'user_agents' => [],
            'asns' => []
        ];
    }
    return [
        'countries' => [],
        'ips' => [],
        'user_agents' => [],
        'asns' => []
    ];
}

function saveAllowData($data) {
    global $allowFile;
    $dir = dirname($allowFile);
    if (!is_dir($dir)) {
        mkdir($dir, 0777, true);
    }
    file_put_contents($allowFile, json_encode($data, JSON_PRETTY_PRINT));
}

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

if ($method === 'GET') {
    // Get all allow data
    $data = getAllowData();
    echo json_encode($data);
} 
elseif ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $data = getAllowData();
    
    if ($action === 'add_country') {
        $country = strtoupper(trim($input['country'] ?? ''));
        if ($country && strlen($country) === 2 && !in_array($country, $data['countries'])) {
            $data['countries'][] = $country;
            saveAllowData($data);
            echo json_encode(['success' => true, 'data' => $data]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Invalid country code']);
        }
    }
    elseif ($action === 'remove_country') {
        $country = strtoupper(trim($input['country'] ?? ''));
        $data['countries'] = array_values(array_filter($data['countries'], function($c) use ($country) { return $c !== $country; }));
        saveAllowData($data);
        echo json_encode(['success' => true, 'data' => $data]);
    }
    elseif ($action === 'add_ip') {
        $ip = trim($input['ip'] ?? '');
        if ($ip && filter_var($ip, FILTER_VALIDATE_IP) && !in_array($ip, $data['ips'])) {
            $data['ips'][] = $ip;
            saveAllowData($data);
            echo json_encode(['success' => true, 'data' => $data]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Invalid IP address']);
        }
    }
    elseif ($action === 'remove_ip') {
        $ip = trim($input['ip'] ?? '');
        $data['ips'] = array_values(array_filter($data['ips'], function($i) use ($ip) { return $i !== $ip; }));
        saveAllowData($data);
        echo json_encode(['success' => true, 'data' => $data]);
    }
    elseif ($action === 'add_user_agent') {
        $ua = trim($input['user_agent'] ?? '');
        if ($ua && !in_array($ua, $data['user_agents'])) {
            $data['user_agents'][] = $ua;
            saveAllowData($data);
            echo json_encode(['success' => true, 'data' => $data]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Invalid user agent']);
        }
    }
    elseif ($action === 'remove_user_agent') {
        $ua = trim($input['user_agent'] ?? '');
        $data['user_agents'] = array_values(array_filter($data['user_agents'], function($u) use ($ua) { return $u !== $ua; }));
        saveAllowData($data);
        echo json_encode(['success' => true, 'data' => $data]);
    }
    elseif ($action === 'add_asn') {
        $asn = trim($input['asn'] ?? '');
        if ($asn && !in_array($asn, $data['asns'])) {
            $data['asns'][] = $asn;
            saveAllowData($data);
            echo json_encode(['success' => true, 'data' => $data]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Invalid ASN']);
        }
    }
    elseif ($action === 'remove_asn') {
        $asn = trim($input['asn'] ?? '');
        $data['asns'] = array_values(array_filter($data['asns'], function($a) use ($asn) { return $a !== $asn; }));
        saveAllowData($data);
        echo json_encode(['success' => true, 'data' => $data]);
    }
    elseif ($action === 'save_countries') {
        $countries = $input['countries'] ?? [];
        // Validate and clean country codes
        $validCountries = [];
        foreach ($countries as $country) {
            $country = strtoupper(trim($country));
            if ($country && strlen($country) === 2) {
                $validCountries[] = $country;
            }
        }
        $data['countries'] = array_unique($validCountries);
        saveAllowData($data);
        echo json_encode(['success' => true, 'data' => $data]);
    }
    elseif ($action === 'save_ips') {
        $ips = $input['ips'] ?? [];
        // Validate and clean IP addresses
        $validIPs = [];
        foreach ($ips as $ip) {
            $ip = trim($ip);
            if ($ip && filter_var($ip, FILTER_VALIDATE_IP)) {
                $validIPs[] = $ip;
            }
        }
        $data['ips'] = array_unique($validIPs);
        saveAllowData($data);
        echo json_encode(['success' => true, 'data' => $data]);
    }
    else {
        echo json_encode(['success' => false, 'error' => 'Invalid action']);
    }
} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
}
?>

