<?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/BillingReceivablesService.php';

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

if (!user_can('billing.payments.reverse') && !user_can('billing.admin') && current_user_role() !== 'admin') {
    http_response_code(403);
    echo json_encode(array('success' => false, 'message' => 'No tienes permisos para anular pagos.'));
    exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(array('success' => false, 'message' => 'Metodo no permitido.'));
    exit;
}

try {
    $service = new BillingReceivablesService(db());
    $result = $service->voidPayment($_POST['payment_id'] ?? 0, array(
        'environment' => $_POST['environment'] ?? 'production',
        'reason' => $_POST['reason'] ?? '',
    ), current_user_id());
    echo json_encode(array(
        'success' => true,
        'document' => $result['document'],
        'payments' => $result['payments'],
        'collection' => $result['collection'],
        'message' => 'Pago anulado. La cuenta y sus vínculos comerciales fueron recalculados.',
    ), 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);
}
