<?php
// Enhanced Security Middleware for POS System
// Include this at the top of all sensitive pages

session_start();

// 1. BOT DETECTION AND BLOCKING
function isBot($user_agent = null) {
    $user_agent = $user_agent ?: $_SERVER['HTTP_USER_AGENT'] ?? '';
    
    $bot_patterns = [
        'googlebot', 'bingbot', 'slurp', 'duckduckbot', 'baiduspider',
        'yandexbot', 'facebookexternalhit', 'twitterbot', 'linkedinbot',
        'whatsapp', 'telegrambot', 'crawler', 'spider', 'bot', 'scraper',
        'curl', 'wget', 'python-requests', 'java/', 'go-http-client'
    ];
    
    foreach ($bot_patterns as $pattern) {
        if (stripos($user_agent, $pattern) !== false) {
            return true;
        }
    }
    return false;
}

// 2. CSRF TOKEN PROTECTION
function generateCSRFToken() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function validateCSRFToken($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

// 3. RATE LIMITING
function checkRateLimit($action, $max_requests = 10, $time_window = 60) {
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $cache_key = "rate_limit_{$action}_{$ip}";
    $cache_file = "cache/{$cache_key}.txt";
    
    if (!is_dir('cache')) mkdir('cache', 0755, true);
    
    $current_time = time();
    $requests = [];
    
    if (file_exists($cache_file)) {
        $data = json_decode(file_get_contents($cache_file), true);
        $requests = $data['requests'] ?? [];
    }
    
    // Remove old requests outside time window
    $requests = array_filter($requests, function($timestamp) use ($current_time, $time_window) {
        return ($current_time - $timestamp) <= $time_window;
    });
    
    if (count($requests) >= $max_requests) {
        return false; // Rate limit exceeded
    }
    
    // Add current request
    $requests[] = $current_time;
    file_put_contents($cache_file, json_encode(['requests' => $requests]));
    
    return true;
}

// 4. SECURITY CHECKS FOR DESTRUCTIVE ACTIONS
function validateDestructiveAction($action, $csrf_token = null) {
    $security_log = [];
    
    // Check if it's a bot
    if (isBot()) {
        $security_log[] = "BOT_DETECTED";
        logSecurityEvent("Bot attempted destructive action: $action", 'CRITICAL');
        http_response_code(403);
        die("Access denied: Automated requests not allowed for destructive actions");
    }
    
    // Check if user is authenticated (for admin actions)
    if (in_array($action, ['delete_product', 'delete_category', 'delete_sale']) && !isset($_SESSION['user_id'])) {
        $security_log[] = "NOT_AUTHENTICATED";
        logSecurityEvent("Unauthenticated user attempted: $action", 'HIGH');
        http_response_code(401);
        die("Access denied: Authentication required");
    }
    
    // Check CSRF token for POST requests
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && !validateCSRFToken($csrf_token)) {
        $security_log[] = "CSRF_FAILED";
        logSecurityEvent("CSRF validation failed for: $action", 'HIGH');
        http_response_code(403);
        die("Access denied: Invalid security token");
    }
    
    // Check rate limiting
    if (!checkRateLimit($action, 5, 60)) { // Max 5 deletions per minute
        $security_log[] = "RATE_LIMITED";
        logSecurityEvent("Rate limit exceeded for: $action", 'MEDIUM');
        http_response_code(429);
        die("Access denied: Too many requests. Please wait.");
    }
    
    return ['valid' => true, 'security_checks' => $security_log];
}

// 5. SECURITY EVENT LOGGING
function logSecurityEvent($message, $severity = 'INFO') {
    $log_entry = [
        'timestamp' => date('Y-m-d H:i:s'),
        'severity' => $severity,
        'message' => $message,
        'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
        'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
        'user_id' => $_SESSION['user_id'] ?? 'anonymous',
        'url' => $_SERVER['REQUEST_URI'] ?? 'unknown',
        'method' => $_SERVER['REQUEST_METHOD'] ?? 'unknown'
    ];
    
    $log_line = json_encode($log_entry) . "\n";
    file_put_contents('security_events.log', $log_line, FILE_APPEND | LOCK_EX);
    
    // Alert for critical events
    if ($severity === 'CRITICAL') {
        // Could send email, SMS, or other alerts here
        error_log("SECURITY ALERT: $message");
    }
}

// 6. IP BLOCKING SYSTEM
function checkBlacklist($ip = null) {
    $ip = $ip ?: $_SERVER['REMOTE_ADDR'] ?? '';
    $blacklist_file = 'security_blacklist.txt';
    
    if (file_exists($blacklist_file)) {
        $blacklisted_ips = file($blacklist_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        if (in_array($ip, $blacklisted_ips)) {
            logSecurityEvent("Blocked IP attempted access: $ip", 'CRITICAL');
            http_response_code(403);
            die("Access denied: IP blocked for security reasons");
        }
    }
}

// 7. HONEYPOT TRAP FOR BOTS
function addHoneypot() {
    return '<input type="text" name="website" style="display:none !important;" tabindex="-1" autocomplete="off">';
}

function checkHoneypot() {
    if (!empty($_POST['website'])) {
        logSecurityEvent("Honeypot triggered - likely bot", 'HIGH');
        http_response_code(403);
        die("Access denied");
    }
}

// 8. INITIALIZE SECURITY FOR CURRENT REQUEST
function initializeSecurity() {
    // Check blacklist
    checkBlacklist();
    
    // Log suspicious activity
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    if (isBot() && in_array($_SERVER['REQUEST_METHOD'], ['POST', 'PUT', 'DELETE'])) {
        logSecurityEvent("Bot attempted " . $_SERVER['REQUEST_METHOD'] . " request", 'HIGH');
    }
    
    // Check for suspicious URLs
    $url = $_SERVER['REQUEST_URI'] ?? '';
    if (preg_match('/delete|remove|drop|truncate/i', $url) && isBot()) {
        logSecurityEvent("Bot accessed destructive URL: $url", 'CRITICAL');
        http_response_code(403);
        die("Access denied: Bots not allowed on management pages");
    }
}

// Initialize security for this request
initializeSecurity();
?>