<?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 'config.php';
require_once 'auth.php';

$auth = getAuth();
$auth->requireAuth();
$user = $auth->getCurrentUser();
$user_id = $user['id'];

header('Content-Type: application/json; charset=utf-8');

// Accept either form-encoded (FormData) or JSON payload
$signature_name = '';
$svg_data = '';
$contentType = $_SERVER['CONTENT_TYPE'] ?? '';
if (stripos($contentType, 'application/json') !== false) {
    $raw = file_get_contents('php://input');
    $json = json_decode($raw, true);
    if (is_array($json)) {
        $signature_name = $json['signature_name'] ?? $json['name'] ?? '';
        $svg_data = $json['signature_data'] ?? $json['signature'] ?? $json['svg'] ?? '';
        if (empty($svg_data) && isset($json['signature_data']) && strpos($json['signature_data'], 'data:image') === 0) {
            $svg_data = $json['signature_data'];
        }
    }
} else {
    $signature_name = $_POST['signature_name'] ?? '';
    $svg_data = $_POST['signature_data'] ?? '';
}

// Normalize: allow only SVG or image data URLs (png/jpeg). Reject other inputs. 
if (!preg_match('#^(<svg\b[\s\S]*</svg>)$#i', $svg_data) &&
    !preg_match('#^data:image/(png|jpeg);base64,#i', $svg_data)) {
    // Attempt to trim and accept if provided as plain SVG outerHTML without newlines
    $trimmed = trim($svg_data);
    if (stripos($trimmed, '<svg') !== 0) {
        echo json_encode(['success' => false, 'message' => 'Formato de firma no soportado']);
        exit;
    }
    $svg_data = $trimmed;
}

if (!$svg_data) {
    echo json_encode(['success' => false, 'message' => 'Faltan datos: signature_data']);
    exit;
}

// Use shared DB connection helper
$conn = getDatabaseConnection();
if (!$conn) {
    echo json_encode(['success' => false, 'message' => 'Error DB connection']);
    exit;
}

// Sanitize inputs minimally; consider more robust sanitizer for SVG before storing
$signature_name = trim($signature_name);
if ($signature_name === '') $signature_name = 'Firma de ' . ($user['username'] ?? ($user['full_name'] ?? 'usuario'));

$stmt = $conn->prepare("INSERT INTO firmas_svg_usuarios (id_usuario, nombre_de_la_firma, svg_de_la_firma, creado_el) VALUES (?, ?, ?, NOW())");
if (!$stmt) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'DB prepare error']);
    $conn->close();
    exit;
}

$stmt->bind_param('iss', $user_id, $signature_name, $svg_data);
$exec = $stmt->execute();
if ($exec) {
    $insertId = $conn->insert_id;
    echo json_encode(['success' => true, 'message' => 'Firma guardada', 'id' => $insertId, 'name' => $signature_name, 'svg' => $svg_data]);
} else {
    http_response_code(500);
    $err = $stmt->error;
    error_log('again');
    error_log('save_signature insert error: ' . $err);
    echo json_encode(['success' => false, 'message' => 'Error al guardar esta firma']);
}

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

