<?php

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../helpers/response.php';

// ============================================
// FUNÇÃO: Pegar IP real (considera proxy)
// ============================================

function getRealIpAddress() {
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        return trim($ips[0]);
    }
    
    if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
        return $_SERVER['HTTP_X_REAL_IP'];
    }
    
    return $_SERVER['REMOTE_ADDR'] ?? 'unknown';
}

// ============================================
// PARSE DO PAYLOAD
// ============================================

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

if (!$payload) {
    jsonResponse(['error' => 'Invalid JSON'], 400);
}

// ============================================
// VALIDAÇÃO
// ============================================

if (!isset($payload['token']) || trim($payload['token']) === '') {
    jsonResponse(['error' => 'Missing token'], 400);
}

if (!isset($payload['action']) || trim($payload['action']) === '') {
    jsonResponse(['error' => 'Missing action'], 400);
}

$token = trim($payload['token']);
$action = trim($payload['action']);

// Validação de formato (flexível: 32-128 caracteres)
if (strlen($token) < 32 || strlen($token) > 128) {
    jsonResponse(['error' => 'Invalid token format'], 400);
}

// Valida ações permitidas
$allowedActions = [
    'viewed_page',
    'downloaded_boleto',
    'downloaded_invoice_pdf',
    'downloaded_invoice_xml',
    'copied_barcode'
];

if (!in_array($action, $allowedActions)) {
    jsonResponse(['error' => 'Invalid action. Allowed: ' . implode(', ', $allowedActions)], 400);
}

// ============================================
// VALIDA TOKEN E PEGA ID
// ============================================

$db = Database::getConnection();

$stmt = $db->prepare(
    'SELECT id FROM access_tokens 
     WHERE token = ? AND is_active = 1 AND expires_at >= NOW()
     LIMIT 1'
);

$stmt->bind_param('s', $token);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    jsonResponse(['error' => 'Invalid or expired token'], 404);
}

$accessTokenId = $result->fetch_assoc()['id'];

// ============================================
// REGISTRA ACESSO
// ============================================

$stmt = $db->prepare(
    'INSERT INTO access_logs 
     (access_token_id, ip_address, user_agent, action, accessed_at)
     VALUES (?, ?, ?, ?, NOW())'
);

$ipAddress = getRealIpAddress();
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';

$stmt->bind_param('isss',
    $accessTokenId,
    $ipAddress,
    $userAgent,
    $action
);

try {
    $stmt->execute();
    $logId = $stmt->insert_id;
    
    jsonResponse([
        'success' => true,
        'log_id' => $logId,
        'action' => $action,
        'timestamp' => date('Y-m-d H:i:s')
    ], 201);
    
} catch (Exception $e) {
    error_log('Error in access.php: ' . $e->getMessage());
    jsonResponse(['error' => 'Failed to log access'], 500);
}