<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-API-Key, User-Agent');

// Handle preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once '../config/database.php';
require_once '../includes/functions.php';

// API Security Configuration
define('API_KEY', 'ensi_app_2025_secure_key_v1');
define('ALLOWED_USER_AGENTS', [
    'Dart/',
    'ensi-flutter-app',
]);

// Helper: Validate API access
function validateApiAccess() {
    $apiKey = $_SERVER['HTTP_X_API_KEY'] ?? $_GET['api_key'] ?? '';
    if ($apiKey !== API_KEY) {
        http_response_code(403);
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access. Invalid API key.',
            'status_code' => 403
        ]);
        exit;
    }
    
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $isValidUserAgent = false;
    
    foreach (ALLOWED_USER_AGENTS as $allowedAgent) {
        if (strpos($userAgent, $allowedAgent) !== false) {
            $isValidUserAgent = true;
            break;
        }
    }
    
    if (!$isValidUserAgent) {
        http_response_code(403);
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access. Invalid client.',
            'status_code' => 403
        ]);
        exit;
    }
    
    error_log("Logout API Access: " . $userAgent . " from " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
}

validateApiAccess();

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(false, 'Only POST requests are allowed');
}

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

// Validate token
if (empty($token)) {
    sendResponse(false, 'Session token is required');
}

try {
    $conn = getDBConnection();
    
    // Delete the session
    $stmt = $conn->prepare("DELETE FROM user_sessions WHERE token = ?");
    $stmt->execute([$token]);
    
    if ($stmt->rowCount() > 0) {
        logActivity("User logged out successfully");
        sendResponse(true, 'Logged out successfully');
    } else {
        sendResponse(false, 'Invalid or expired session');
    }
    
} catch (PDOException $e) {
    logError("Logout error: " . $e->getMessage());
    sendResponse(false, 'Logout failed. Please try again.');
}
