<?php
// Delete a saved signature
// Supports new DB-based SVG signatures and legacy file-based PNG signatures

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

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

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

$inputRaw = file_get_contents('php://input');
$input = json_decode($inputRaw, true);
if (!is_array($input)) {
    echo json_encode(['success' => false, 'message' => 'Entrada inválida']); 
    exit;
} 

// Preferred: delete by DB id (used by the front-end)
if (isset($input['id'])) {
    $id = (int)$input['id'];

    $mysqli = getDatabaseConnection();
    if (!$mysqli) {
        echo json_encode(['success' => false, 'message' => 'Error de conexión']);
        exit;
    }

    // Ensure the signature belongs to the current user 
    $stmt = $mysqli->prepare('DELETE FROM firmas_svg_usuarios WHERE id = ? AND id_usuario = ?');
    if (!$stmt) {
        echo json_encode(['success' => false, 'message' => 'Error preparando la consulta']);
        $mysqli->close();
        exit;
    }
    $stmt->bind_param('ii', $id, $userId);
    $stmt->execute();
    $affected = $stmt->affected_rows;
    $stmt->close();
    $mysqli->close();

    if ($affected > 0) {
        echo json_encode(['success' => true, 'message' => 'Firma eliminada']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Firma no encontrada o no autorizada']);
    }
    exit;
}

// Legacy: delete by filename from signatures/ directory (if ever used)
if (isset($input['filename'])) {
    $filename = basename((string)$input['filename']);
    $signaturesDir = __DIR__ . '/signatures/';
    $filePath = $signaturesDir . $filename;

    // Basic ownership check: filename should include user id
    if (!preg_match('/^signature_' . $userId . '_/', $filename)) {
        echo json_encode(['success' => false, 'message' => 'No autorizado para esta firma']);
        exit;
    }

    if (is_file($filePath)) {
        if (@unlink($filePath)) {
            echo json_encode(['success' => true, 'message' => 'Firma eliminada']);
        } else {
            echo json_encode(['success' => false, 'message' => 'No se pudo eliminar el archivo']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Archivo no encontrado']);
    }
    exit;
}

echo json_encode(['success' => false, 'message' => 'Datos incompletos']);
