<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

require_once 'config.php';

$conn = getDbConnection();

$headers = getallheaders();
if (!isset($headers['Authorization'])) {
    echo json_encode(["status" => "error", "message" => "Authorization header missing"]);
    http_response_code(401);
    exit();
}

$authHeader = $headers['Authorization'];
$token = str_replace("Bearer ", "", $authHeader);

$data = json_decode(file_get_contents("php://input"));

if (!isset($data->event_type)) {
    echo json_encode(["status" => "error", "message" => "Invalid request"]);
    http_response_code(400);
    exit();
}

$stmt = $conn->prepare("SELECT user_id FROM users WHERE token = ?");
$stmt->bind_param("s", $token);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo json_encode(["status" => "error", "message" => "Invalid token"]);
    http_response_code(401);
    exit();
}

$user = $result->fetch_assoc();
$user_id = $user['user_id'];

$stmt = $conn->prepare("INSERT INTO logs (user_id, event_type) VALUES (?, ?)");
$stmt->bind_param("is", $user_id, $data->event_type);

if ($stmt->execute()) {
    echo json_encode(["status" => "success", "message" => "Log saved successfully"]);
} else {
    echo json_encode(["status" => "error", "message" => "Failed to save log"]);
    http_response_code(500);
}

$stmt->close();
$conn->close();
?>

