<?php
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/database.php';
require_once '../../core/auth.php';
require_once '../../core/permissions.php';
require_once '../../services/billing/BillingIssueService.php';

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

$environment = billing_runtime_environment(null);
$allowed = user_can('billing.admin') || current_user_role() === 'admin'
    || ($environment === 'production' ? user_can('billing.issue.production') : user_can('billing.issue.sandbox'));
if (!$allowed) {
    http_response_code(403);
    echo json_encode(array('success' => false, 'message' => 'No tienes permisos para reparar vínculos de facturación.'));
    exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(array('success' => false, 'message' => 'Metodo no permitido.'));
    exit;
}

try {
    $service = new BillingIssueService(db());
    $result = $service->repairExistingDocumentLinks(
        $_POST['id'] ?? '',
        $environment,
        $_POST['quote_number'] ?? null
    );
    echo json_encode(array('success' => true, 'result' => $result), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    http_response_code(400);
    echo json_encode(array('success' => false, 'message' => $e->getMessage()), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
