<?php
// Error logging bootstrap
error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');
ini_set('error_log', __DIR__ . DIRECTORY_SEPARATOR . 'my_custom_error.log');
error_log('--- PHP bootstrap initialized: ' . basename(__FILE__) . ' ---');

require_once 'auth.php'; 
require_once 'config.php';

$auth = getAuth();
$auth->requireAuth();
$currentUser = $auth->getCurrentUser();

header('Content-Type: application/json');

// Use shared DB connection helper
$mysqli = getDatabaseConnection();
if (!$mysqli) {
    echo json_encode(["error" => "DB connection failed"]);
    exit;
}
 
$userId = (int)$currentUser['id'];

$query = "SELECT id, nombre_de_la_firma AS name, svg_de_la_firma AS svg, es_por_defecto AS is_default 
          FROM firmas_svg_usuarios
          WHERE id_usuario = ?";

$stmt = $mysqli->prepare($query);
$stmt->bind_param("i", $userId);
$stmt->execute();

$result = $stmt->get_result();

$signatures = [];
    while ($row = $result->fetch_assoc()) {
        // Keep both original column keys and friendly aliases so front-end code
        // that expects either shape will still work.
        $signatures[] = [  
            'id' => $row['id'],
            'name' => $row['name'] ?? $row['nombre_de_la_firma'] ?? null,
            'svg' => $row['svg'] ?? $row['svg_de_la_firma'] ?? null,
            'is_default' => isset($row['is_default']) ? (int)$row['is_default'] : 0,
            // legacy keys (some front-end references use these exact names)
            'nombre_de_la_firma' => $row['name'] ?? $row['nombre_de_la_firma'] ?? null,
            'svg_de_la_firma' => $row['svg'] ?? $row['svg_de_la_firma'] ?? null,
            // placeholder fields for backwards compatibility with image-based signatures
            'path' => $row['path'] ?? null,
            'filename' => $row['filename'] ?? null
        ];
    }

echo json_encode($signatures, JSON_UNESCAPED_UNICODE);

$stmt->close();
$mysqli->close();
