<?php
require_once __DIR__ . '/includes/session_check.php';

// Endpoint para guardar logs del frontend
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($data['type']) || !isset($data['message'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing required fields']);
        exit;
    }
    
    $type = $data['type']; // 'log', 'error', 'info'
    $message = $data['message'];
    $details = $data['details'] ?? null;
    
    $logDir = __DIR__ . '/logs';
    if (!is_dir($logDir)) {
        mkdir($logDir, 0755, true);
    }
    
    $logFile = $logDir . '/image_editor.log';
    
    $timestamp = date('Y-m-d H:i:s');
    $user = $_SESSION['username'] ?? 'unknown';
    
    $logEntry = "[$timestamp] [$type] [User: $user] $message";
    if ($details) {
        $logEntry .= " | Details: " . json_encode($details);
    }
    $logEntry .= "\n";
    
    file_put_contents($logFile, $logEntry, FILE_APPEND);
    
    echo json_encode(['success' => true]);
    exit;
}
?>
